Programs & Examples On #Curb

Curb provides Ruby-language bindings for the libcurl, a fully-featured client-side URL transfer library.

FB OpenGraph og:image not pulling images (possibly https?)

Similar symptoms (Facebook et al not correctly fetching og:image and other assets over https) can occur when the site's https certificate is not fully compliant.

Your site's https cert may seem valid (green key in the browser and all), but it will not scrape correctly if it's missing an intermediate or chain certificate. This can lead to many wasted hours checking and rechecking all the various caches and meta tags.

Might not have been your problem, but could be other's with similar symptoms (like mine). There's many ways to check your cert - the one I happened to use: https://www.sslshopper.com/ssl-checker.html

Ruby: How to post a file via HTTP as multipart/form-data?

curb looks like a great solution, but in case it doesn't meet your needs, you can do it with Net::HTTP. A multipart form post is just a carefully-formatted string with some extra headers. It seems like every Ruby programmer who needs to do multipart posts ends up writing their own little library for it, which makes me wonder why this functionality isn't built-in. Maybe it is... Anyway, for your reading pleasure, I'll go ahead and give my solution here. This code is based off of examples I found on a couple of blogs, but I regret that I can't find the links anymore. So I guess I just have to take all the credit for myself...

The module I wrote for this contains one public class, for generating the form data and headers out of a hash of String and File objects. So for example, if you wanted to post a form with a string parameter named "title" and a file parameter named "document", you would do the following:

#prepare the query
data, headers = Multipart::Post.prepare_query("title" => my_string, "document" => my_file)

Then you just do a normal POST with Net::HTTP:

http = Net::HTTP.new(upload_uri.host, upload_uri.port)
res = http.start {|con| con.post(upload_uri.path, data, headers) }

Or however else you want to do the POST. The point is that Multipart returns the data and headers that you need to send. And that's it! Simple, right? Here's the code for the Multipart module (you need the mime-types gem):

# Takes a hash of string and file parameters and returns a string of text
# formatted to be sent as a multipart form post.
#
# Author:: Cody Brimhall <mailto:[email protected]>
# Created:: 22 Feb 2008
# License:: Distributed under the terms of the WTFPL (http://www.wtfpl.net/txt/copying/)

require 'rubygems'
require 'mime/types'
require 'cgi'


module Multipart
  VERSION = "1.0.0"

  # Formats a given hash as a multipart form post
  # If a hash value responds to :string or :read messages, then it is
  # interpreted as a file and processed accordingly; otherwise, it is assumed
  # to be a string
  class Post
    # We have to pretend we're a web browser...
    USERAGENT = "Mozilla/5.0 (Macintosh; U; PPC Mac OS X; en-us) AppleWebKit/523.10.6 (KHTML, like Gecko) Version/3.0.4 Safari/523.10.6"
    BOUNDARY = "0123456789ABLEWASIEREISAWELBA9876543210"
    CONTENT_TYPE = "multipart/form-data; boundary=#{ BOUNDARY }"
    HEADER = { "Content-Type" => CONTENT_TYPE, "User-Agent" => USERAGENT }

    def self.prepare_query(params)
      fp = []

      params.each do |k, v|
        # Are we trying to make a file parameter?
        if v.respond_to?(:path) and v.respond_to?(:read) then
          fp.push(FileParam.new(k, v.path, v.read))
        # We must be trying to make a regular parameter
        else
          fp.push(StringParam.new(k, v))
        end
      end

      # Assemble the request body using the special multipart format
      query = fp.collect {|p| "--" + BOUNDARY + "\r\n" + p.to_multipart }.join("") + "--" + BOUNDARY + "--"
      return query, HEADER
    end
  end

  private

  # Formats a basic string key/value pair for inclusion with a multipart post
  class StringParam
    attr_accessor :k, :v

    def initialize(k, v)
      @k = k
      @v = v
    end

    def to_multipart
      return "Content-Disposition: form-data; name=\"#{CGI::escape(k)}\"\r\n\r\n#{v}\r\n"
    end
  end

  # Formats the contents of a file or string for inclusion with a multipart
  # form post
  class FileParam
    attr_accessor :k, :filename, :content

    def initialize(k, filename, content)
      @k = k
      @filename = filename
      @content = content
    end

    def to_multipart
      # If we can tell the possible mime-type from the filename, use the
      # first in the list; otherwise, use "application/octet-stream"
      mime_type = MIME::Types.type_for(filename)[0] || MIME::Types["application/octet-stream"][0]
      return "Content-Disposition: form-data; name=\"#{CGI::escape(k)}\"; filename=\"#{ filename }\"\r\n" +
             "Content-Type: #{ mime_type.simplified }\r\n\r\n#{ content }\r\n"
    end
  end
end

How to use dashes in HTML-5 data-* attributes in ASP.NET MVC

You can use it like this:

In Mvc:

@Html.TextBoxFor(x=>x.Id,new{@data_val_number="10"});

In Html:

<input type="text" name="Id" data_val_number="10"/>

Convert URL to File or Blob for FileReader.readAsDataURL

This information is outdated as of now, but cannot be deleted.

  1. You can create File instances just by specifying a path when your code is chrome-privileged:

    new File("/path/to/file");
    

    File is a sub-class of Blob, so all File instances are also valid Blobs. Please note that this requires a platform path, and not a file URL.

  2. Yes, FileReader is available to addons.

File and FileReader are available in all windows. If you want to use them in a non-window scope (like bootstrap.js or a code module), you may use nsIDOMFile/nsIDOMFileReader.

Return positions of a regex match() in Javascript?

In modern browsers, you can accomplish this with string.matchAll().

The benefit to this approach vs RegExp.exec() is that it does not rely on the regex being stateful, as in @Gumbo's answer.

_x000D_
_x000D_
let regexp = /bar/g;
let str = 'foobarfoobar';

let matches = [...str.matchAll(regexp)];
matches.forEach((match) => {
    console.log("match found at " + match.index);
});
_x000D_
_x000D_
_x000D_

make arrayList.toArray() return more specific types

 public static <E> E[] arrayListToTypedArray(List<E> list) {

    if (list == null) {
      return null;
    }
    int noItems = list.size();
    if (noItems == 0) {
      return null;
    }

    E[] listAsTypedArray;
    E typeHelper = list.get(0);

    try {
      Object o = Array.newInstance(typeHelper.getClass(), noItems);
      listAsTypedArray = (E[]) o;
      for (int i = 0; i < noItems; i++) {
        Array.set(listAsTypedArray, i, list.get(i));
      }
    } catch (Exception e) {
      return null;
    }

    return listAsTypedArray;
  }

Force index use in Oracle

If you think the performance of the query will be better using the index, how could you force the query to use the index?

First you would of course verify that the index gave a better result for returning the complete data set, right?

The index hint is the key here, but the more up to date way of specifying it is with the column naming method rather than the index naming method. In your case you would use:

select /*+ index(table_name (column_having_index)) */ *
from   table_name
where  column_having_index="some value"; 

In more complex cases you might ...

select /*+ index(t (t.column_having_index)) */ *
from   my_owner.table_name t,
       ...
where  t.column_having_index="some value"; 

With regard to composite indexes, I'm not sure that you need to specify all columns, but it seems like a good idea. See the docs here http://docs.oracle.com/cd/E11882_01/server.112/e26088/sql_elements006.htm#autoId18 on multiple index_specs and use of index_combine for multiple indexes, and here http://docs.oracle.com/cd/E11882_01/server.112/e26088/sql_elements006.htm#BABGFHCH for the specification of multiple columns in the index_spec.

SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder". error

Paste this code to your pom.xml file. It works for me.

<dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-simple</artifactId>
    <version>1.6.1</version>
    <scope>test</scope>
</dependency>

Change the icon of the exe file generated from Visual Studio 2010

I found it easier to edit the project file directly e.g. YourApp.csproj.

You can do this by modifying ApplicationIcon property element:

<ApplicationIcon>..\Path\To\Application.ico</ApplicationIcon>

Also, if you create an MSI installer for your application e.g. using WiX, you can use the same icon again for display in Add/Remove Programs. See tip 5 here.

Python copy files to a new directory and rename if file name already exists

I would say you have an indentation problem, at least as you wrote it here:

while not os.path.exists(file + "_" + str(i) + extension):
   i+=1
   print "Already 2x exists..."
   print "Renaming"
   shutil.copy(path, file + "_" + str(i) + extension)

should be:

while os.path.exists(file + "_" + str(i) + extension):
    i+=1
print "Already 2x exists..."
print "Renaming"
shutil.copy(path, file + "_" + str(i) + extension)

Check this out, please!

Could not load file or assembly "Oracle.DataAccess" or one of its dependencies

In my case the following solved the problem:

  1. Downloading the "32-bit Oracle Data Access Components (ODAC) with Oracle Developer Tools for Visual Studio" from http://www.oracle.com/technetwork/topics/dotnet/utilsoft-086879.html
  2. Then adding reference oracle.dataaccess.dll to the bin file by browsing the file location or just from the refence list in .NET tab.

Running an executable in Mac Terminal

Unix will only run commands if they are available on the system path, as you can view by the $PATH variable

echo $PATH

Executables located in directories that are not on the path cannot be run unless you specify their full location. So in your case, assuming the executable is in the current directory you are working with, then you can execute it as such

./my-exec

Where my-exec is the name of your program.

how do I strip white space when grabbing text with jQuery?

Use the replace function in js:

var emailAdd = $(this).text().replace(/ /g,'');

That will remove all the spaces

If you want to remove the leading and trailing whitespace only, use the jQuery $.trim method :

var emailAdd = $.trim($(this).text());

Git fast forward VS no fast forward merge

I can give an example commonly seen in project.

Here, option --no-ff (i.e. true merge) creates a new commit with multiple parents, and provides a better history tracking. Otherwise, --ff (i.e. fast-forward merge) is by default.

$ git checkout master
$ git checkout -b newFeature
$ ...
$ git commit -m 'work from day 1'
$ ...
$ git commit -m 'work from day 2'
$ ...
$ git commit -m 'finish the feature'
$ git checkout master
$ git merge --no-ff newFeature -m 'add new feature'
$ git log
// something like below
commit 'add new feature'         // => commit created at merge with proper message
commit 'finish the feature'
commit 'work from day 2'
commit 'work from day 1'
$ gitk                           // => see details with graph

$ git checkout -b anotherFeature        // => create a new branch (*)
$ ...
$ git commit -m 'work from day 3'
$ ...
$ git commit -m 'work from day 4'
$ ...
$ git commit -m 'finish another feature'
$ git checkout master
$ git merge anotherFeature       // --ff is by default, message will be ignored
$ git log
// something like below
commit 'work from day 4'
commit 'work from day 3'
commit 'add new feature'
commit 'finish the feature'
commit ...
$ gitk                           // => see details with graph

(*) Note that here if the newFeature branch is re-used, instead of creating a new branch, git will have to do a --no-ff merge anyway. This means fast forward merge is not always eligible.

WCF Error "This could be due to the fact that the server certificate is not configured properly with HTTP.SYS in the HTTPS case"

Since everything was working fine for weeks then stopped, I doubt this has anything to do with your code. Perhaps the error is occurring when the service is activated within IIS/ASP.NET, not when your code is called. The runtime could just be checking the configuration of the web site and throwing a generic error message which has nothing to do with the service.

My suspicion is that a certificate has expired or that the bindings are set up incorrectly. If the web site is mis-configured for HTTPS, whether your code uses them or not, you may be getting this error.

Getting all selected checkboxes in an array

Use this:

var arr = $('input:checkbox:checked').map(function () {
  return this.value;
}).get();

Check if element exists in jQuery

Try to check the length of the selector, if it returns you something then the element must exists else not.

 if( $('#selector').length )         // use this if you are using id to check
{
     // it exists
}


 if( $('.selector').length )         // use this if you are using class to check
{
     // it exists
}

Remove leading or trailing spaces in an entire column of data

I was able to use Find & Replace with the "Find what:" input field set to:

" * "

(space asterisk space with no double-quotes)

and "Replace with:" set to:

""

(nothing)

Detecting negative numbers

You could use a ternary operator like this one, to make it a one liner.

echo ($profitloss < 0) ? 'false' : 'true';

undefined reference to `std::ios_base::Init::Init()'

Most of these linker errors occur because of missing libraries.

I added the libstdc++.6.dylib in my Project->Targets->Build Phases-> Link Binary With Libraries.

That solved it for me on Xcode 6.3.2 for iOS 8.3

Cheers!

The program can’t start because MSVCR71.dll is missing from your computer. Try reinstalling the program to fix this program

Here is the solution I found:

How to fix the missing MSVCR711.dll problem

You can find MSVCR71.dll file in following location of your installed SQL Developer 2.1 directory:

sqldeveloper-2.1.0.63.10\sqldeveloper\jdk\jre\bin\MSVCR71.dll

Breaking up long strings on multiple lines in Ruby without stripping newlines

You can use \ to indicate that any line of Ruby continues on the next line. This works with strings too:

string = "this is a \
string that spans lines"

puts string.inspect

will output "this is a string that spans lines"

Checking for an empty field with MySQL

You could use

IFNULL(email, '') > ''

Horizontal scroll on overflow of table

The solution for those who cannot or do not want to wrap the table in a div (e.g. if the HTML is generated from Markdown) but still want to have scrollbars:

_x000D_
_x000D_
table {_x000D_
  display: block;_x000D_
  max-width: -moz-fit-content;_x000D_
  max-width: fit-content;_x000D_
  margin: 0 auto;_x000D_
  overflow-x: auto;_x000D_
  white-space: nowrap;_x000D_
}
_x000D_
<table>_x000D_
  <tr>_x000D_
    <td>Especially on mobile, a table can easily become wider than the viewport.</td>_x000D_
    <td>Using the right CSS, you can get scrollbars on the table without wrapping it.</td>_x000D_
  </tr>_x000D_
</table>_x000D_
_x000D_
<table>_x000D_
  <tr>_x000D_
    <td>A centered table.</td>_x000D_
  </tr>_x000D_
</table>
_x000D_
_x000D_
_x000D_

Explanation: display: block; makes it possible to have scrollbars. By default (and unlike tables), blocks span the full width of the parent element. This can be prevented with max-width: fit-content;, which allows you to still horizontally center tables with less content using margin: 0 auto;. white-space: nowrap; is optional (but useful for this demonstration).

Send password when using scp to copy files from one server to another

// copy /tmp/abc.txt to /tmp/abc.txt (target path)

// username and password of 10.1.1.2 is "username" and "password"

sshpass -p "password" scp /tmp/abc.txt [email protected]:/tmp/abc.txt

// install sshpass (ubuntu)

sudo apt-get install sshpass

Make page to tell browser not to cache/preserve input values

This worked for me in newer browsers:

autocomplete="new-password"

How to check if android checkbox is checked within its onClick method (declared in XML)?

try this one :

public void itemClicked(View v) {
  //code to check if this checkbox is checked!
  CheckBox checkBox = (CheckBox)v;
  if(checkBox.isChecked()){

  }
}

Why does JSHint throw a warning if I am using const?

For SublimeText 3 on Mac:

  1. Create a .jshintrc file in your root directory (or wherever you prefer) and specify the esversion:
    # .jshintrc
    {
      "esversion": 6
    }
  1. Reference the pwd of the file you just created in SublimeLinter user settings (Sublime Text > Preference > Package Settings > SublimeLinter > Settings)
    // SublimeLinter Settings - User
    {
      "linters": {
        "jshint": {
          "args": ["--config", "/Users/[your_username]/.jshintrc"]
        }
      }
    }
  1. Quit and relaunch SublimeText

Why there is this "clear" class before footer?

Most likely, as mentioned by others, it is a class carrying the css values:

.clear{clear: both;} 

in order to prevent any more page elements from extending into the footer element. It is a quick and easy way of making sure that pages with columns of varying heights don't cause the footer to render oddly, by possibly setting its top position at the end of a shorter column.

In many cases it is not necessary, but if you are using best-practice standards it is a good idea to use, if you are floating page elements left and right. It functions with page elements similar to the way a horizontal rule works with text, to ensure proper and complete sepperation.

Process with an ID #### is not running in visual studio professional 2013 update 3

What I did to make this go away:

Open C:\Users\gr_mext1\Documents\IISExpress\config\applicationhost.config and remove all <site> entries in <sites> do not remove <siteDefaults>!

In your project, go to Properties, Web and click "Create Virtual Directory".

Close and re-open visual studio, load your project and run

Fixed!

How to delete from a table where ID is in a list of IDs?

delete from t
where id in (1, 4, 6, 7)

List of Java processes

The following commands will return only Java ProcessIDs. These commands are very useful especially whenever you want to feed another process by these return values (java PIDs).

sudo netstat -nlpt | awk '/java/ {print $7}' | tr '/java' ' '

sudo netstat -nlpt | awk '/java/ {print $7}' | sed 's/\/java/ /g'

But if you remove the latest pipe, you will be noticed these are java process

sudo netstat -nlpt | awk '/java/ {print $7}'

sudo netstat -nlpt | awk '/java/ {print $7}'

Should you use rgba(0, 0, 0, 0) or rgba(255, 255, 255, 0) for transparency in CSS?

There a small difference when u use rgba(255,255,255,a),background color becomes more and more lighter as the value of 'a' increase from 0.0 to 1.0. Where as when use rgba(0,0,0,a), the background color becomes more and more darker as the value of 'a' increases from 0.0 to 1.0. Having said that, its clear that both (255,255,255,0) and (0,0,0,0) make background transparent. (255,255,255,1) would make the background completely white where as (0,0,0,1) would make background completely black.

How to correctly get image from 'Resources' folder in NetBeans

Thanks, Valter Henrique, with your tip i managed to realise, that i simply entered incorrect path to this image. In one of my tries i use

    String pathToImageSortBy = "resources/testDataIcons/filling.png";
    ImageIcon SortByIcon = new ImageIcon(getClass().getClassLoader().getResource(pathToImageSortBy));

But correct way was use name of my project in path to resource

String pathToImageSortBy = "nameOfProject/resources/testDataIcons/filling.png";
ImageIcon SortByIcon = new ImageIcon(getClass().getClassLoader().getResource(pathToImageSortBy));

What's the point of 'meta viewport user-scalable=no' in the Google Maps API

From the v3 documentation (Developer's Guide > Concepts > Developing for Mobile Devices):

Android and iOS devices respect the following <meta> tag:

<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />

This setting specifies that the map should be displayed full-screen and should not be resizable by the user. Note that the iPhone's Safari browser requires this <meta> tag be included within the page's <head> element.

Filtering Pandas Dataframe using OR statement

From the docs:

Another common operation is the use of boolean vectors to filter the data. The operators are: | for or, & for and, and ~ for not. These must be grouped by using parentheses.

http://pandas.pydata.org/pandas-docs/version/0.15.2/indexing.html#boolean-indexing

Try:

alldata_balance = alldata[(alldata[IBRD] !=0) | (alldata[IMF] !=0)]

How to fix error "Updating Maven Project". Unsupported IClasspathEntry kind=4?

Try mvn clean install eclipse:eclipse -Dwtpversion=2.0 command on DOS command prompt. Suggesting you because , It worked for me!!

Is there a "standard" format for command line/shell help text?

Typically, your help output should include:

  • Description of what the app does
  • Usage syntax, which:
    • Uses [options] to indicate where the options go
    • arg_name for a required, singular arg
    • [arg_name] for an optional, singular arg
    • arg_name... for a required arg of which there can be many (this is rare)
    • [arg_name...] for an arg for which any number can be supplied
    • note that arg_name should be a descriptive, short name, in lower, snake case
  • A nicely-formatted list of options, each:
    • having a short description
    • showing the default value, if there is one
    • showing the possible values, if that applies
    • Note that if an option can accept a short form (e.g. -l) or a long form (e.g. --list), include them together on the same line, as their descriptions will be the same
  • Brief indicator of the location of config files or environment variables that might be the source of command line arguments, e.g. GREP_OPTS
  • If there is a man page, indicate as such, otherwise, a brief indicator of where more detailed help can be found

Note further that it's good form to accept both -h and --help to trigger this message and that you should show this message if the user messes up the command-line syntax, e.g. omits a required argument.

Move SQL Server 2008 database files to a new folder location

Some notes to complement the ALTER DATABASE process:

1) You can obtain a full list of databases with logical names and full paths of MDF and LDF files:

   USE master SELECT name, physical_name FROM sys.master_files

2) You can move manually the files with CMD move command:

Move "Source" "Destination"

Example:

md "D:\MSSQLData"
Move "C:\test\SYSADMIT-DB.mdf" "D:\MSSQLData\SYSADMIT-DB_Data.mdf"
Move "C:\test\SYSADMIT-DB_log.ldf" "D:\MSSQLData\SYSADMIT-DB_log.ldf"

3) You should change the default database path for new databases creation. The default path is obtained from the Windows registry.

You can also change with T-SQL, for example, to set default destination to: D:\MSSQLData

USE [master]

GO

EXEC xp_instance_regwrite N'HKEY_LOCAL_MACHINE', N'Software\Microsoft\MSSQLServer\MSSQLServer', N'DefaultData', REG_SZ, N'D:\MSSQLData'

GO

EXEC xp_instance_regwrite N'HKEY_LOCAL_MACHINE', N'Software\Microsoft\MSSQLServer\MSSQLServer', N'DefaultLog', REG_SZ, N'D:\MSSQLData'

GO

Extracted from: http://www.sysadmit.com/2016/08/mover-base-de-datos-sql-server-a-otro-disco.html

How to use log levels in java

This tip shows how to use Logger in any java application. Logger needs to configure Formatter and Handler. There are many types of handlers and formatters present. In this example FileHandler is used to store all the log messages in a log file. And Simple formatter is used to format the log messages in human readable form.

package MyProject;

import java.io.IOException;
import java.util.logging.FileHandler;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.logging.SimpleFormatter;

public class MyLogger {

  public static void main(String[] args) {

    Logger logger = Logger.getLogger("MyLog");
    FileHandler fh;

    try {

      // This block configure the logger with handler and formatter
      fh = new FileHandler("c:\\MyLogFile.log", true);
      logger.addHandler(fh);
      logger.setLevel(Level.ALL);
      SimpleFormatter formatter = new SimpleFormatter();
      fh.setFormatter(formatter);

      // the following statement is used to log any messages   
      logger.log(Level.WARNING,"My first log");

    } catch (SecurityException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }

  }

}

some more examples you can find here https://docs.oracle.com/javase/7/docs/api/java/util/logging/Logger.html

What does "connection reset by peer" mean?

It's fatal. The remote server has sent you a RST packet, which indicates an immediate dropping of the connection, rather than the usual handshake. This bypasses the normal half-closed state transition. I like this description:

"Connection reset by peer" is the TCP/IP equivalent of slamming the phone back on the hook. It's more polite than merely not replying, leaving one hanging. But it's not the FIN-ACK expected of the truly polite TCP/IP converseur.

JQUERY: Uncaught Error: Syntax error, unrecognized expression

If you're using jQuery 2.1.4 or above, try this:

$("#" + this.d);

Or, you can define var before using it. It makes your code simpler.

var d = this.d
$("#" + d);

Check if a Class Object is subclass of another Class Object in Java

Another option is instanceof:

Object o =...
if (o instanceof Number) {
  double d = ((Number)o).doubleValue(); //this cast is safe
}

How do I draw a set of vertical lines in gnuplot?

Here is a snippet from my perl script to do this:

print OUTPUT "set arrow from $x1,$y1 to $x1,$y2 nohead lc rgb \'red\'\n";

As you might guess from above, it's actually drawn as a "headless" arrow.

Index was outside the bounds of the Array. (Microsoft.SqlServer.smo)

Restarting the Management Studio worked for me.

How to sort an ArrayList in Java

Try BeanComparator from Apache Commons.

import org.apache.commons.beanutils.BeanComparator;


BeanComparator fieldComparator = new BeanComparator("fruitName");
Collections.sort(fruits, fieldComparator);

Reading column names alone in a csv file

Thanking Daniel Jimenez for his perfect solution to fetch column names alone from my csv, I extend his solution to use DictReader so we can iterate over the rows using column names as indexes. Thanks Jimenez.

with open('myfile.csv') as csvfile:

    rest = []
    with open("myfile.csv", "rb") as f:
        reader = csv.reader(f)
        i = reader.next()
        i=i[1:]
        re=csv.DictReader(csvfile)
        for row in re:
            for x in i:
                print row[x]

Get int value from enum in C#

Just cast the enum, e.g.

int something = (int) Question.Role;

The above will work for the vast majority of enums you see in the wild, as the default underlying type for an enum is int.

However, as cecilphillip points out, enums can have different underlying types. If an enum is declared as a uint, long, or ulong, it should be cast to the type of the enum; e.g. for

enum StarsInMilkyWay:long {Sun = 1, V645Centauri = 2 .. Wolf424B = 2147483649};

you should use

long something = (long)StarsInMilkyWay.Wolf424B;

.bashrc at ssh login

For an excellent resource on how bash invocation works, what dotfiles do what, and how you should use/configure them, read this:

Python: find position of element in array

Suppose if the list is a collection of objects like given below:

obj =  [
        {

            "subjectId" : "577a54c09c57916109142248", 
            "evaluableMaterialCount" : 0, 
            "subjectName" : "ASP.net"

        }, 
        {

            "subjectId" : "56645cd63c43a07b61c2c650", 
            "subjectName" : ".NET",         
        }, 
        {

            "subjectId" : "5656a2ec3c43a07b61c2bd83", 
            "subjectName" : "Python",

        }, 
        {

            "subjectId" : "5662add93c43a07b61c2c58c", 
            "subjectName" : "HTML"
        }
    ]

You can use the following method to find the index. Suppose the subjectId is 5662add93c43a07b61c2c58c then to get the index of the object in the list,

subjectId = "5662add93c43a07b61c2c58c"

for i, subjobj in enumerate(obj):
    if(subjectId == subjobj['subjectId']):
        print(i)

Converting time stamps in excel to dates

If your file is really big try to use following formula: =A1 / 86400 + 25569

A1 should be replaced to what your need. Should work faster than =(((COLUMN_ID_HERE/60)/60)/24)+DATE(1970,1,1) cause of less number of calculations needed.

Force to open "Save As..." popup open at text link click for PDF in HTML

Just put the below code in your .htaccess file:

AddType application/octet-stream .csv
AddType application/octet-stream .xls
AddType application/octet-stream .doc
AddType application/octet-stream .avi
AddType application/octet-stream .mpg
AddType application/octet-stream .mov
AddType application/octet-stream .pdf

Or you can also do trick by JavaScript

element.setAttribute( 'download', whatever_string_you_want);

How can I pass parameters to a partial view in mvc 4

For Asp.Net core you better use

<partial name="_MyPartialView" model="MyModel" />

So for example

@foreach (var item in Model)
{
   <partial name="_MyItemView" model="item" />
}

Adding the "Clear" Button to an iPhone UITextField

This button is a built-in overlay that is provided by the UITextField class, but as of the iOS 2.2 SDK, there isn't any way to set it via Interface Builder. You have to enable it programmatically.

Add this line of code somewhere (viewDidLoad, for example):

Objective-C

myUITextField.clearButtonMode = UITextFieldViewModeWhileEditing;

Swift 5.0

myUITextField.clearButtonMode = .whileEditing

What is the effect of encoding an image in base64?

Here's a really helpful overview of when to base64 encode and when not to by David Calhoun.

Basic answer = gzipped base64 encoded files will be roughly comparable in file size to standard binary (jpg/png). Gzip'd binary files will have a smaller file size.

Takeaway = There's some advantage to encoding and gzipping your UI icons, etc, but unwise to do this for larger images.

How to find current transaction level?

just run DBCC useroptions and you'll get something like this:

Set Option                  Value
--------------------------- --------------
textsize                    2147483647
language                    us_english
dateformat                  mdy
datefirst                   7
lock_timeout                -1
quoted_identifier           SET
arithabort                  SET
ansi_null_dflt_on           SET
ansi_warnings               SET
ansi_padding                SET
ansi_nulls                  SET
concat_null_yields_null     SET
isolation level             read committed

How to fix Error: this class is not key value coding-compliant for the key tableView.'

Any chance that you changed the name of your table view from "tableView" to "myTableView" at some point?

CodeIgniter Active Record not equal

It worked fine with me,

$this->db->where("your_id !=",$your_id);

Or try this one,

$this->db->where("your_id <>",$your_id);

Or try this one,

$this->db->where("your_id IS NOT NULL");

all will work.

Angular and Typescript: Can't find names - Error: cannot find name

The accepted answer doesn't provide a viable fix, and most of the other ones suggest the "triple-slashes" workaround which is not viable anymore, since the browser.d.ts has been removed by the Angular2 latest RC's and thus is not available anymore.

I strongly suggest to install the typings module as suggested by a couple solutions here, yet it's not necessary to do it manually or globally - there's an effective way to do that for your project only and within VS2015 interface. Here's what you need to do:

  • add typings in the project's package.json file.
  • add a script block in the package.json file to execute/update typings after each NPM action.
  • add a typings.json file in the project's root folder containing a reference to core-js (overall better than es6-shim atm).

That's it.

You can also take a look to this other SO thread and/or read this post on my blog for additional details.

Callback when DOM is loaded in react.js

Add onload listener in componentDidMount

class Comp1 extends React.Component {
 constructor(props) {
    super(props);
    this.handleLoad = this.handleLoad.bind(this);
 }

 componentDidMount() {
    window.addEventListener('load', this.handleLoad);
 }

 componentWillUnmount() { 
   window.removeEventListener('load', this.handleLoad)  
 }

 handleLoad() {
  $("myclass") //  $ is available here
 }
}

Get checkbox list values with jQuery

var nameCheckBoxList = "myCheckListName";
var selectedValues = $("[name=" + nameCheckBoxList + "]:checked").map(function(){return this.value;});

mysql data directory location

Well, if yo don't know where is my.cnf (such Mac OS X installed with homebrew), or You are looking found others choices:

ps aux|grep mysql
abkrim            1160   0.0  0.2  2913068  26224   ??  R    Tue04PM   0:14.63 /usr/local/opt/mariadb/bin/mysqld --basedir=/usr/local/opt/mariadb --datadir=/usr/local/var/mysql --plugin-dir=/usr/local/opt/mariadb/lib/plugin --bind-address=127.0.0.1 --log-error=/usr/local/var/mysql/iMac-2.local.err --pid-file=iMac-2.local.pid

You get datadir=/usr/local/var/mysql

How to replace comma (,) with a dot (.) using java

in the java src you can add a new tool like this:

public static String remplaceVirguleParpoint(String chaine) {
       return chaine.replaceAll(",", "\\.");
}

How to format a java.sql Timestamp for displaying?

Use String.format (or java.util.Formatter):

Timestamp timestamp = ...
String.format("%1$TD %1$TT", timestamp)

EDIT:
please see the documentation of Formatter to know what TD and TT means: click on java.util.Formatter

The first 'T' stands for:

't', 'T'    date/time   Prefix for date and time conversion characters.

and the character following that 'T':

'T'     Time formatted for the 24-hour clock as "%tH:%tM:%tS".
'D'     Date formatted as "%tm/%td/%ty". 

Is there a Sleep/Pause/Wait function in JavaScript?

You can't (and shouldn't) block processing with a sleep function. However, you can use setTimeout to kick off a function after a delay:

setTimeout(function(){alert("hi")}, 1000);

Depending on your needs, setInterval might be useful, too.

Best way to get user GPS location in background in Android

You can archive it with a Service and Alarm Manager, but be careful with this, because if you setup a high priority you gonna drain the battery of the phone, in other hand, you really need notify the location every minute? This is because the only way to see a considerably change of the user location, it's traveling in a car or train. I only ask, because that gonna depend of you app and the requirement of the tracking.

Table row and column number in jQuery

Get COLUMN INDEX on click:

$(this).closest("td").index();

Get ROW INDEX on click:

$(this).closest("tr").index();

How to add and remove classes in Javascript without jQuery

When you remove RegExp from the equation you leave a less "friendly" code, but it still can be done with the (much) less elegant way of split().

function removeClass(classString, toRemove) {
    classes = classString.split(' ');
    var out = Array();
    for (var i=0; i<classes.length; i++) {
        if (classes[i].length == 0) // double spaces can create empty elements
            continue;
        if (classes[i] == toRemove) // don't include this one
            continue;
        out.push(classes[i])
    }
    return out.join(' ');
}

This method is a lot bigger than a simple replace() but at least it can be used on older browsers. And in case the browser doesn't even support the split() command it's relatively easy to add it using prototype.

html5 input for money/currency

_x000D_
_x000D_
var currencyInput = document.querySelector('input[type="currency"]')
var currency = 'USD' // https://www.currency-iso.org/dam/downloads/lists/list_one.xml

 // format inital value
onBlur({target:currencyInput})

// bind event listeners
currencyInput.addEventListener('focus', onFocus)
currencyInput.addEventListener('blur', onBlur)


function localStringToNumber( s ){
  return Number(String(s).replace(/[^0-9.-]+/g,""))
}

function onFocus(e){
  var value = e.target.value;
  e.target.value = value ? localStringToNumber(value) : ''
}

function onBlur(e){
  var value = e.target.value

  var options = {
      maximumFractionDigits : 2,
      currency              : currency,
      style                 : "currency",
      currencyDisplay       : "symbol"
  }
  
  e.target.value = value 
    ? localStringToNumber(value).toLocaleString(undefined, options)
    : ''
}
_x000D_
input{
  padding: 10px;
  font: 20px Arial;
  width: 70%;
}
_x000D_
<input type='currency' value="123" placeholder='Type a number & click outside' />
_x000D_
_x000D_
_x000D_

Image re-size to 50% of original size in HTML

You did not do anything wrong here, it will any other thing that is overriding the image size.

You can check this working fiddle.

And in this fiddle I have alter the image size using %, and it is working.

Also try using this code:

<img src="image.jpg" style="width: 50%; height: 50%"/>?

Here is the example fiddle.

Generating random integer from a range

In this thread rejection sampling was already discussed, but I wanted to suggest one optimization based on the fact that rand() % 2^something does not introduce any bias as already mentioned above.

The algorithm is really simple:

  • calculate the smallest power of 2 greater than the interval length
  • randomize one number in that "new" interval
  • return that number if it is less than the length of the original interval
    • reject otherwise

Here's my sample code:

int randInInterval(int min, int max) {
    int intervalLen = max - min + 1;
    //now calculate the smallest power of 2 that is >= than `intervalLen`
    int ceilingPowerOf2 = pow(2, ceil(log2(intervalLen)));

    int randomNumber = rand() % ceilingPowerOf2; //this is "as uniform as rand()"

    if (randomNumber < intervalLen)
        return min + randomNumber;      //ok!
    return randInInterval(min, max);    //reject sample and try again
} 

This works well especially for small intervals, because the power of 2 will be "nearer" to the real interval length, and so the number of misses will be smaller.

PS
Obviously avoiding the recursion would be more efficient (no need to calculate over and over the log ceiling..) but I thought it was more readable for this example.

jquery - Click event not working for dynamically created button

You create buttons dynamically because of that you need to call them with .live() method if you use jquery 1.7

but this method is deprecated (you can see the list of all deprecated method here) in newer version. if you want to use jquery 1.10 or above you need to call your buttons in this way:

$(document).on('click', 'selector', function(){ 
     // Your Code
});

For Example

If your html is something like this

<div id="btn-list">
    <div class="btn12">MyButton</div>
</div>

You can write your jquery like this

$(document).on('click', '#btn-list .btn12', function(){ 
     // Your Code
});

How to remove title bar from the android activity?

You just add following lines of code in style.xml file

<style name="AppTheme.NoTitleBar" parent="Theme.AppCompat.Light.DarkActionBar">
<item name="windowActionBar">false</item>
<item name="windowNoTitle">true</item>
<item name="android:windowFullscreen">true</item>

change apptheme in AndroidManifest.xml file

android:theme="@style/AppTheme.NoTitleBar"

How to return a PNG image from Jersey REST service method to the browser

in regard of answer from @Perception, its true to be very memory-consuming when working with byte arrays, but you could also simply write back into the outputstream

@Path("/picture")
public class ProfilePicture {
  @GET
  @Path("/thumbnail")
  @Produces("image/png")
  public StreamingOutput getThumbNail() {
    return new StreamingOutput() {
      @Override
      public void write(OutputStream os) throws IOException, WebApplicationException {
        //... read your stream and write into os
      }
    };
  }
}

Change content of div - jQuery

You can try the same with replacewith()

$('.click').click(function() {
    // get the contents of the link that was clicked
    var linkText = $(this).text();

    // replace the contents of the div with the link text
    $('#content-container').replaceWith(linkText);

    // cancel the default action of the link by returning false
    return false;
});

The .replaceWith() method removes content from the DOM and inserts new content in its place with a single call.

How to scroll page in flutter

Use LayoutBuilder and Get the output you want

Wrap the SingleChildScrollView with LayoutBuilder and implement the Builder function.

we can use a LayoutBuilder to get the box contains or the amount of space available.

LayoutBuilder(
    builder: (BuildContext context, BoxConstraints constraints){
      return SingleChildScrollView(
        child: Stack(
          children: <Widget>[
            Container(
              height: constraints.maxHeight,
            ),
            topTitle(context),
            middleView(context),
            bottomView(context),
          ],
        ),
      );
    }
)

Ruby - test for array

Also consider using Array(). From the Ruby Community Style Guide:

Use Array() instead of explicit Array check or [*var], when dealing with a variable you want to treat as an Array, but you're not certain it's an array.

# bad
paths = [paths] unless paths.is_a? Array
paths.each { |path| do_something(path) }

# bad (always creates a new Array instance)
[*paths].each { |path| do_something(path) }

# good (and a bit more readable)
Array(paths).each { |path| do_something(path) }

CSS float right not working correctly

Verry Easy, change order of element:

Origin

<div style="">

    My Text

    <button type="button" style="float: right; margin:5px;">
       My Button
    </button>

</div>

Change to:

<div style=""> 

    <button type="button" style="float: right; margin:5px;">
       My Button
     </button>

   My Text

</div>

How to solve npm error "npm ERR! code ELIFECYCLE"

This solution is for Windows users.

You can open the node.js installer and give the installer some time to compute space requirements and then click next and click remove. This will remove node.js from your computer and again reopen the installer and install it in this path - C:\Windows\System32

or

Cleaning Cache and Node_module will work. Follow this steps:

  • npm cache clean --force
  • delete node_modules folder
  • delete package-lock.json file
  • npm install

How to get the first line of a file in a bash script?

This suffices and stores the first line of filename in the variable $line:

read -r line < filename

I also like awk for this:

awk 'NR==1 {print; exit}' file

To store the line itself, use the var=$(command) syntax. In this case, line=$(awk 'NR==1 {print; exit}' file).

Or even sed:

sed -n '1p' file

With the equivalent line=$(sed -n '1p' file).


See a sample when we feed the read with seq 10, that is, a sequence of numbers from 1 to 10:

$ read -r line < <(seq 10) 
$ echo "$line"
1

$ line=$(awk 'NR==1 {print; exit}' <(seq 10))
$ echo "$line"
1

Formula to determine brightness of RGB color

This link explains everything in depth, including why those multiplier constants exist before the R, G and B values.

Edit: It has an explanation to one of the answers here too (0.299*R + 0.587*G + 0.114*B)

How to create a XML object from String in Java?

try something like

public static Document loadXML(String xml) throws Exception
{
   DocumentBuilderFactory fctr = DocumentBuilderFactory.newInstance();
   DocumentBuilder bldr = fctr.newDocumentBuilder();
   InputSource insrc = new InputSource(new StringReader(xml));
   return bldr.parse(insrc);
}

I want to execute shell commands from Maven's pom.xml

Thanks! Tomer Ben David. it helped me. as I am doing pip install in demo folder as you mentioned npm install

<groupId>org.codehaus.mojo</groupId>
            <artifactId>exec-maven-plugin</artifactId>
            <version>1.3.2</version>
            <executions>
              <execution>
                <goals>
                  <goal>exec</goal>
                </goals>
              </execution>
            </executions>
            <configuration>
              <executable>pip</executable>
              <arguments><argument>install</argument></arguments>                            
             <workingDirectory>${project.build.directory}/Demo</workingDirectory>
            </configuration>

Multiple Updates in MySQL

Since you have dynamic values, you need to use an IF or CASE for the columns to be updated. It gets kinda ugly, but it should work.

Using your example, you could do it like:

UPDATE table SET Col1 = CASE id 
                          WHEN 1 THEN 1 
                          WHEN 2 THEN 2 
                          WHEN 4 THEN 10 
                          ELSE Col1 
                        END, 
                 Col2 = CASE id 
                          WHEN 3 THEN 3 
                          WHEN 4 THEN 12 
                          ELSE Col2 
                        END
             WHERE id IN (1, 2, 3, 4);

Spring Boot without the web server

Remove folowing dependancy on your pom file will work for me

  <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

Send a SMS via intent

Create the Intent like this:

   Uri uriSms = Uri.parse("smsto:1234567899");   
   Intent intentSMS = new Intent(Intent.ACTION_SENDTO, uriSms);   
   intentSMS.putExtra("sms_body", "The SMS text");   
   startActivity(intentSMS); 

How to detect my browser version and operating system using JavaScript?

Code to detect the operating system of an user

let os = navigator.userAgent.slice(13).split(';')
os = os[0]
console.log(os)
Windows NT 10.0

How to get start and end of day in Javascript?

In MomentJs We can declare it like :

   const start = moment().format('YYYY-MM-DD 00:00:01');
   const end = moment().format('YYYY-MM-DD 23:59:59');

Autoresize View When SubViews are Added

Yes, it is because you are using auto layout. Setting the view frame and resizing mask will not work.

You should read Working with Auto Layout Programmatically and Visual Format Language.

You will need to get the current constraints, add the text field, adjust the contraints for the text field, then add the correct constraints on the text field.

JavaScript function in href vs. onclick

bad:

<a id="myLink" href="javascript:MyFunction();">link text</a>

good:

<a id="myLink" href="#" onclick="MyFunction();">link text</a>

better:

<a id="myLink" href="#" onclick="MyFunction();return false;">link text</a>

even better 1:

<a id="myLink" title="Click to do something"
 href="#" onclick="MyFunction();return false;">link text</a>

even better 2:

<a id="myLink" title="Click to do something"
 href="PleaseEnableJavascript.html" onclick="MyFunction();return false;">link text</a>

Why better? because return false will prevent browser from following the link

best:

Use jQuery or other similar framework to attach onclick handler by element's ID.

$('#myLink').click(function(){ MyFunction(); return false; });

What's a good (free) visual merge tool for Git? (on windows)

On Windows, a good 3-way diff/merge tool remains kdiff3 (WinMerge, for now, is still 2-way based, pending WinMerge3)

See "How do you merge in GIT on Windows?" and this config.


Update 7 years later (Aug. 2018): Artur Kedzior mentions in the comments:

If you guys happen to use Visual Studio (Community Edition is free), try the tool that is shipped with it: vsDiffMerge.exe. It's really awesome and easy to use.

How to use Jackson to deserialise an array of objects

here is an utility which is up to transform json2object or Object2json, whatever your pojo (entity T)

import java.io.IOException;
import java.io.StringWriter;
import java.util.List;

import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;

/**
 * 
 * @author TIAGO.MEDICI
 * 
 */
public class JsonUtils {

    public static boolean isJSONValid(String jsonInString) {
        try {
            final ObjectMapper mapper = new ObjectMapper();
            mapper.readTree(jsonInString);
            return true;
        } catch (IOException e) {
            return false;
        }
    }

    public static String serializeAsJsonString(Object object) throws JsonGenerationException, JsonMappingException, IOException {
        ObjectMapper objMapper = new ObjectMapper();
        objMapper.enable(SerializationFeature.INDENT_OUTPUT);
        objMapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
        StringWriter sw = new StringWriter();
        objMapper.writeValue(sw, object);
        return sw.toString();
    }

    public static String serializeAsJsonString(Object object, boolean indent) throws JsonGenerationException, JsonMappingException, IOException {
        ObjectMapper objMapper = new ObjectMapper();
        if (indent == true) {
            objMapper.enable(SerializationFeature.INDENT_OUTPUT);
            objMapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
        }

        StringWriter stringWriter = new StringWriter();
        objMapper.writeValue(stringWriter, object);
        return stringWriter.toString();
    }

    public static <T> T jsonStringToObject(String content, Class<T> clazz) throws JsonParseException, JsonMappingException, IOException {
        T obj = null;
        ObjectMapper objMapper = new ObjectMapper();
        obj = objMapper.readValue(content, clazz);
        return obj;
    }

    @SuppressWarnings("rawtypes")
    public static <T> T jsonStringToObjectArray(String content) throws JsonParseException, JsonMappingException, IOException {
        T obj = null;
        ObjectMapper mapper = new ObjectMapper();
        obj = mapper.readValue(content, new TypeReference<List>() {
        });
        return obj;
    }

    public static <T> T jsonStringToObjectArray(String content, Class<T> clazz) throws JsonParseException, JsonMappingException, IOException {
        T obj = null;
        ObjectMapper mapper = new ObjectMapper();
        mapper = new ObjectMapper().configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);
        obj = mapper.readValue(content, mapper.getTypeFactory().constructCollectionType(List.class, clazz));
        return obj;
    }

Create new project on Android, Error: Studio Unknown host 'services.gradle.org'

I also faced it and encorrected it like below successfully.

File > Settings > Build, Execution, Deployment > Gradle > Use local gradle distribution

Set the home path as : C:/Program Files/Android/Android Studio/gradle/gradle-version

You may need to upgrade your gradle version.

Python: finding an element in a list

I use function for returning index for the matching element (Python 2.6):

def index(l, f):
     return next((i for i in xrange(len(l)) if f(l[i])), None)

Then use it via lambda function for retrieving needed element by any required equation e.g. by using element name.

element = mylist[index(mylist, lambda item: item["name"] == "my name")]

If i need to use it in several places in my code i just define specific find function e.g. for finding element by name:

def find_name(l, name):
     return l[index(l, lambda item: item["name"] == name)]

And then it is quite easy and readable:

element = find_name(mylist,"my name")

SSIS how to set connection string dynamically from a config file

Goto Package properties->Configurations->Enable Package Configurations->Add->xml configuration file->Specify dtsconfig file->click next->In OLEDB Properties tick the connection string->connection string value will be displayed->click next and finish package is hence configured.

You can add Environment variable also in this process

error: src refspec master does not match any

This is happend to me once I forgot to add files. So I got the same error. All you need to do is add your files.

  1. Add your files => git add . or the name of the files you want to add. you supposed to init first your repo with git init.
  2. Commit your changes => git commit -m 'Initial Commit'.
  3. Now push your changes => git push -u origin master

DataGridView checkbox column - value and functionality

If you try it on CellContentClick Event

Use:

dataGridView1.EndEdit();  //Stop editing of cell.
MessageBox.Show("0 = " + dataGridView1.Rows[e.RowIndex].Cells[0].Value.ToString());

Call break in nested if statements

But there is switch-case :)

switch (true) {
    case true:
        console.log("Yes, its ture :) Break from the switch-case");
        break;
    case false:
        console.log("Nope, but if the condition was set to false this would be used and then break");
        break;

    default:
        console.log("If all else fails");
        break;
}

javascript: using a condition in switch case

Although in the particular example of the OP's question, switch is not appropriate, there is an example where switch is still appropriate/beneficial, but other evaluation expressions are also required. This can be achieved by using the default clause for the expressions:

switch (foo) {
  case 'bar':
    // do something
    break;
  case 'foo':
    // do something
    break;
  ... // other plain comparison cases
  default:
    if (foo.length > 16) {
      // something specific
    } else if (foo.length < 2) {
      // maybe error
    } else {
      // default action for everything else
    }
}

Linux find file names with given string recursively

This is a very simple solution using the tree command in the directory you want to search for. -f shows the full file path and | is used to pipe the output of tree to grep to find the file containing the string filename in the name.

tree -f | grep filename

File upload progress bar with jQuery

check this out: http://hayageek.com/docs/jquery-upload-file.php I've found it accidentally on the net.

converting multiple columns from character to numeric format in r

type.convert()

Convert a data object to logical, integer, numeric, complex, character or factor as appropriate.

Add the as.is argument type.convert(df,as.is = T) to prevent character vectors from becoming factors when there is a non-numeric in the data set.

See.

Check if a given key already exists in a dictionary and increment it

To answer the question "how can I find out if a given index in that dict has already been set to a non-None value", I would prefer this:

try:
  nonNone = my_dict[key] is not None
except KeyError:
  nonNone = False

This conforms to the already invoked concept of EAFP (easier to ask forgiveness then permission). It also avoids the duplicate key lookup in the dictionary as it would in key in my_dict and my_dict[key] is not None what is interesting if lookup is expensive.

For the actual problem that you have posed, i.e. incrementing an int if it exists, or setting it to a default value otherwise, I also recommend the

my_dict[key] = my_dict.get(key, default) + 1

as in the answer of Andrew Wilkinson.

There is a third solution if you are storing modifyable objects in your dictionary. A common example for this is a multimap, where you store a list of elements for your keys. In that case, you can use:

my_dict.setdefault(key, []).append(item)

If a value for key does not exist in the dictionary, the setdefault method will set it to the second parameter of setdefault. It behaves just like a standard my_dict[key], returning the value for the key (which may be the newly set value).

JavaScript: How to join / combine two arrays to concatenate into one array?

var a = ['a','b','c'];
var b = ['d','e','f'];
var c = a.concat(b); //c is now an an array with: ['a','b','c','d','e','f']
console.log( c[3] ); //c[3] will be 'd'

Do Git tags only apply to the current branch?

We can create a tag for some past commit:

git tag [tag_name] [reference_of_commit]

eg:

git tag v1.0 5fcdb03

jackson deserialization json to java-objects

Your product class needs a parameterless constructor. You can make it private, but Jackson needs the constructor.

As a side note: You should use Pascal casing for your class names. That is Product, and not product.

Should I Dispose() DataSet and DataTable?

Update (December 1, 2009):

I'd like to amend this answer and concede that the original answer was flawed.

The original analysis does apply to objects that require finalization – and the point that practices shouldn’t be accepted on the surface without an accurate, in-depth understanding still stands.

However, it turns out that DataSets, DataViews, DataTables suppress finalization in their constructors – this is why calling Dispose() on them explicitly does nothing.

Presumably, this happens because they don’t have unmanaged resources; so despite the fact that MarshalByValueComponent makes allowances for unmanaged resources, these particular implementations don’t have the need and can therefore forgo finalization.

(That .NET authors would take care to suppress finalization on the very types that normally occupy the most memory speaks to the importance of this practice in general for finalizable types.)

Notwithstanding, that these details are still under-documented since the inception of the .NET Framework (almost 8 years ago) is pretty surprising (that you’re essentially left to your own devices to sift though conflicting, ambiguous material to put the pieces together is frustrating at times but does provide a more complete understanding of the framework we rely on everyday).

After lots of reading, here’s my understanding:

If an object requires finalization, it could occupy memory longer than it needs to – here’s why: a) Any type that defines a destructor (or inherits from a type that defines a destructor) is considered finalizable; b) On allocation (before the constructor runs), a pointer is placed on the Finalization queue; c) A finalizable object normally requires 2 collections to be reclaimed (instead of the standard 1); d) Suppressing finalization doesn’t remove an object from the finalization queue (as reported by !FinalizeQueue in SOS) This command is misleading; Knowing what objects are on the finalization queue (in and of itself) isn’t helpful; Knowing what objects are on the finalization queue and still require finalization would be helpful (is there a command for this?)

Suppressing finalization turns a bit off in the object's header indicating to the runtime that it doesn’t need to have its Finalizer invoked (doesn’t need to move the FReachable queue); It remains on the Finalization queue (and continues to be reported by !FinalizeQueue in SOS)

The DataTable, DataSet, DataView classes are all rooted at MarshalByValueComponent, a finalizable object that can (potentially) handle unmanaged resources

  • Because DataTable, DataSet, DataView don’t introduce unmanaged resources, they suppress finalization in their constructors
  • While this is an unusual pattern, it frees the caller from having to worry about calling Dispose after use
  • This, and the fact that DataTables can potentially be shared across different DataSets, is likely why DataSets don’t care to dispose child DataTables
  • This also means that these objects will appear under the !FinalizeQueue in SOS
  • However, these objects should still be reclaimable after a single collection, like their non-finalizable counterparts

4 (new references):

Original Answer:

There are a lot of misleading and generally very poor answers on this - anyone who's landed here should ignore the noise and read the references below carefully.

Without a doubt, Dispose should be called on any Finalizable objects.

DataTables are Finalizable.

Calling Dispose significantly speeds up the reclaiming of memory.

MarshalByValueComponent calls GC.SuppressFinalize(this) in its Dispose() - skipping this means having to wait for dozens if not hundreds of Gen0 collections before memory is reclaimed:

With this basic understanding of finalization we can already deduce some very important things:

First, objects that need finalization live longer than objects that do not. In fact, they can live a lot longer. For instance, suppose an object that is in gen2 needs to be finalized. Finalization will be scheduled but the object is still in gen2, so it will not be re-collected until the next gen2 collection happens. That could be a very long time indeed, and, in fact, if things are going well it will be a long time, because gen2 collections are costly and thus we want them to happen very infrequently. Older objects needing finalization might have to wait for dozens if not hundreds of gen0 collections before their space is reclaimed.

Second, objects that need finalization cause collateral damage. Since the internal object pointers must remain valid, not only will the objects directly needing finalization linger in memory but everything the object refers to, directly and indirectly, will also remain in memory. If a huge tree of objects was anchored by a single object that required finalization, then the entire tree would linger, potentially for a long time as we just discussed. It is therefore important to use finalizers sparingly and place them on objects that have as few internal object pointers as possible. In the tree example I just gave, you can easily avoid the problem by moving the resources in need of finalization to a separate object and keeping a reference to that object in the root of the tree. With that modest change only the one object (hopefully a nice small object) would linger and the finalization cost is minimized.

Finally, objects needing finalization create work for the finalizer thread. If your finalization process is a complex one, the one and only finalizer thread will be spending a lot of time performing those steps, which can cause a backlog of work and therefore cause more objects to linger waiting for finalization. Therefore, it is vitally important that finalizers do as little work as possible. Remember also that although all object pointers remain valid during finalization, it might be the case that those pointers lead to objects that have already been finalized and might therefore be less than useful. It is generally safest to avoid following object pointers in finalization code even though the pointers are valid. A safe, short finalization code path is the best.

Take it from someone who's seen 100s of MBs of non-referenced DataTables in Gen2: this is hugely important and completely missed by the answers on this thread.

References:

1 - http://msdn.microsoft.com/en-us/library/ms973837.aspx

2 - http://vineetgupta.spaces.live.com/blog/cns!8DE4BDC896BEE1AD!1104.entry http://www.dotnetfunda.com/articles/article524-net-best-practice-no-2-improve-garbage-collector-performance-using-finalizedispose-pattern.aspx

3 - http://codeidol.com/csharp/net-framework/Inside-the-CLR/Automatic-Memory-Management/

Get class name of object as string in Swift

Swift 5.1

You can get class, struct, enum, protocol and NSObject names though Self.self.

print("\(Self.self)")

new Runnable() but no new thread?

The Runnable interface is another way in which you can implement multi-threading other than extending the Thread class due to the fact that Java allows you to extend only one class.

You can however, use the new Thread(Runnable runnable) constructor, something like this:

private Thread thread = new Thread(new Runnable() {
public void run() {
   final long start = mStartTime;
   long millis = SystemClock.uptimeMillis() - start;
   int seconds = (int) (millis / 1000);
   int minutes = seconds / 60;
   seconds     = seconds % 60;

   if (seconds < 10) {
       mTimeLabel.setText("" + minutes + ":0" + seconds);
   } else {
       mTimeLabel.setText("" + minutes + ":" + seconds);            
   }

   mHandler.postAtTime(this,
           start + (((minutes * 60) + seconds + 1) * 1000));
   }
});

thread.start();

Retrieving Property name from lambda expression

I have done the INotifyPropertyChanged implementation similar to the method below. Here the properties are stored in a dictionary in the base class shown below. It is of course not always desirable to use inheritance, but for view models I think it is acceptable and gives very clean property references in the view model classes.

public class PhotoDetailsViewModel
    : PropertyChangedNotifierBase<PhotoDetailsViewModel>
{
    public bool IsLoading
    {
        get { return GetValue(x => x.IsLoading); }
        set { SetPropertyValue(x => x.IsLoading, value); }
    }

    public string PendingOperation
    {
        get { return GetValue(x => x.PendingOperation); }
        set { SetPropertyValue(x => x.PendingOperation, value); }
    }

    public PhotoViewModel Photo
    {
        get { return GetValue(x => x.Photo); }
        set { SetPropertyValue(x => x.Photo, value); }
    }
}

The somewhat more complex base class is shown below. It handles the translation from lambda expression to property name. Note that the properties are really pseudo properties since only the names are used. But it will appear transparent to the view model and references to the properties on the view model.

public class PropertyChangedNotifierBase<T> : INotifyPropertyChanged
{
    readonly Dictionary<string, object> _properties = new Dictionary<string, object>();

    protected U GetValue<U>(Expression<Func<T, U>> property)
    {
        var propertyName = GetPropertyName(property);

        return GetValue<U>(propertyName);
    }

    private U GetValue<U>(string propertyName)
    {
        object value;

        if (!_properties.TryGetValue(propertyName, out value))
        {
            return default(U);
        }

        return (U)value;
    }

    protected void SetPropertyValue<U>(Expression<Func<T, U>> property, U value)
    {
        var propertyName = GetPropertyName(property);

        var oldValue = GetValue<U>(propertyName);

        if (Object.ReferenceEquals(oldValue, value))
        {
            return;
        }
        _properties[propertyName] = value;

        RaisePropertyChangedEvent(propertyName);
    }

    protected void RaisePropertyChangedEvent<U>(Expression<Func<T, U>> property)
    {
        var name = GetPropertyName(property);
        RaisePropertyChangedEvent(name);
    }

    protected void RaisePropertyChangedEvent(string propertyName)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }

    private static string GetPropertyName<U>(Expression<Func<T, U>> property)
    {
        if (property == null)
        {
            throw new NullReferenceException("property");
        }

        var lambda = property as LambdaExpression;

        var memberAssignment = (MemberExpression) lambda.Body;
        return memberAssignment.Member.Name;
    }

    public event PropertyChangedEventHandler PropertyChanged;
}

How to add a new column to an existing sheet and name it?

For your question as asked

Columns(3).Insert
Range("c1:c4") = Application.Transpose(Array("Loc", "uk", "us", "nj"))

If you had a way of automatically looking up the data (ie matching uk against employer id) then you could do that in VBA

Do you recommend using semicolons after every statement in JavaScript?

I think this is similar to what the last podcast discussed. The "Be liberal in what you accept" means that extra work had to be put into the Javascript parser to fix cases where semicolons were left out. Now we have a boatload of pages out there floating around with bad syntax, that might break one day in the future when some browser decides to be a little more stringent on what it accepts. This type of rule should also apply to HTML and CSS. You can write broken HTML and CSS, but don't be surprise when you get weird and hard to debug behaviors when some browser doesn't properly interpret your incorrect code.

JOptionPane Input to int

This because the input that the user inserts into the JOptionPane is a String and it is stored and returned as a String.

Java cannot convert between strings and number by itself, you have to use specific functions, just use:

int ans = Integer.parseInt(JOptionPane.showInputDialog(...))

Swift GET request with parameters

Use NSURLComponents to build your NSURL like this

var urlComponents = NSURLComponents(string: "https://www.google.de/maps/")!

urlComponents.queryItems = [
  NSURLQueryItem(name: "q", value: String(51.500833)+","+String(-0.141944)),
  NSURLQueryItem(name: "z", value: String(6))
]
urlComponents.URL // returns https://www.google.de/maps/?q=51.500833,-0.141944&z=6

font: https://www.ralfebert.de/snippets/ios/encoding-nsurl-get-parameters/

How and when to use SLEEP() correctly in MySQL?

If you don't want to SELECT SLEEP(1);, you can also DO SLEEP(1); It's useful for those situations in procedures where you don't want to see output.

e.g.

SELECT ...
DO SLEEP(5);
SELECT ...

R - " missing value where TRUE/FALSE needed "

Can you change the if condition to this:

if (!is.na(comments[l])) print(comments[l]);

You can only check for NA values with is.na().

Using 'make' on OS X

There is now another way to install the gcc toolchain on OS X through the osx-gcc-installer this includes:

  • GCC
  • LLVM
  • Clang
  • Developer CLI Tools (purge, make, etc)
  • DevSDK (headers, etc)

The download is 282MB vs 3GB for Xcode.

How to append rows to an R data frame

Update with purrr, tidyr & dplyr

As the question is already dated (6 years), the answers are missing a solution with newer packages tidyr and purrr. So for people working with these packages, I want to add a solution to the previous answers - all quite interesting, especially .

The biggest advantage of purrr and tidyr are better readability IMHO. purrr replaces lapply with the more flexible map() family, tidyr offers the super-intuitive method add_row - just does what it says :)

map_df(1:1000, function(x) { df %>% add_row(x = x, y = toString(x)) })

This solution is short and intuitive to read, and it's relatively fast:

system.time(
   map_df(1:1000, function(x) { df %>% add_row(x = x, y = toString(x)) })
)
   user  system elapsed 
   0.756   0.006   0.766

It scales almost linearly, so for 1e5 rows, the performance is:

system.time(
  map_df(1:100000, function(x) { df %>% add_row(x = x, y = toString(x)) })
)
   user  system elapsed 
 76.035   0.259  76.489 

which would make it rank second right after data.table (if your ignore the placebo) in the benchmark by @Adam Ryczkowski:

nr  function      time
4   data.frame    228.251 
3   sqlite        133.716
2   data.table      3.059
1   rbindlist     169.998 
0   placebo         0.202

jQuery .each() index?

jQuery takes care of this for you. The first argument to your .each() callback function is the index of the current iteration of the loop. The second being the current matched DOM element So:

$('#list option').each(function(index, element){
  alert("Iteration: " + index)
});

Bootstrap 3 navbar active li not changing background-color

In Bootstrap 3.3.x make sure you use the scrollspy JavaScript capability to track active elements. It's easy to include it in your HTML. Just do the following:

<body data-spy="scroll" data-target="Id or class of the element you want to track">

In most cases I usually track active elements on my navbar, so I do the following:

<body data-spy="scroll" data-target=".navbar-fixed-top" >

Now in your CSS you can target .navbar-fixed-top .active a:

.navbar-fixed-top .active a { 
    // Put in some styling 
}

This should work if you are tracking active li elements in your top fixed navigation bar.

iPad Web App: Detect Virtual Keyboard Using JavaScript in Safari?

The problem is that, even in 2014, devices handle screen resize events, as well as scroll events, inconsistently while the soft keyboard is open.

I've found that, even if you're using a bluetooth keyboard, iOS in particular triggers some strange layout bugs; so instead of detecting a soft keyboard, I've just had to target devices that are very narrow and have touchscreens.

I use media queries (or window.matchMedia) for width detection and Modernizr for touch event detection.

What is the 'override' keyword in C++ used for?

override is a C++11 keyword which means that a method is an "override" from a method from a base class. Consider this example:

   class Foo
   {
   public:
        virtual void func1();
   }

   class Bar : public Foo
   {
   public:
        void func1() override;
   }

If B::func1() signature doesn't equal A::func1() signature a compilation error will be generated because B::func1() does not override A::func1(), it will define a new method called func1() instead.

What's wrong with foreign keys?

I have heard this argument too - from people who forgot to put an index on their foreign keys and then complained that certain operations were slow (because constraint checking could take advantage of any index). So to sum up: There is no good reason not to use foreign keys. All modern databases support cascaded deletes, so...

Is there a pure CSS way to make an input transparent?

If you want to remove the outline when focused as well try:

input[type="text"],
input[type="text"]:focus   
{
         background: transparent;
         border: none;
         outline-width: 0;
}

Serializing a list to JSON

If you're doing this in the context of a asp.Net Core API action, the conversion to Json is done implicitly.

[HttpGet]
public ActionResult Get()
{
    return Ok(TheList);
}

Concatenate two slices in Go

I would like to emphasize @icza answer and simplify it a bit since it is a crucial concept. I assume that reader is familiar with slices.

c := append(a, b...)

This is a valid answer to the question. BUT if you need to use slices 'a' and 'c' later in code in different context, this is not the safe way to concatenate slices.

To explain, lets read the expression not in terms of slices, but in terms of underlying arrays:

"Take (underlying) array of 'a' and append elements from array 'b' to it. If array 'a' has enough capacity to include all elements from 'b' - underlying array of 'c' will not be a new array, it will actually be array 'a'. Basically, slice 'a' will show len(a) elements of underlying array 'a', and slice 'c' will show len(c) of array 'a'."

append() does not necessarily create a new array! This can lead to unexpected results. See Go Playground example.

Always use make() function if you want to make sure that new array is allocated for the slice. For example here are few ugly but efficient enough options for the task.

la := len(a)
c := make([]int, la, la + len(b))
_ = copy(c, a)
c = append(c, b...)

la := len(a)
c := make([]int, la + len(b))
_ = copy(c, a)
_ = copy(c[la:], b)

Android: How can I pass parameters to AsyncTask's onPreExecute()?

1) For me that's the most simple way passing parameters to async task is like this

// To call the async task do it like this
Boolean[] myTaskParams = { true, true, true };
myAsyncTask = new myAsyncTask ().execute(myTaskParams);

Declare and use the async task like here

private class myAsyncTask extends AsyncTask<Boolean, Void, Void> {

    @Override
    protected Void doInBackground(Boolean...pParams) 
    {
        Boolean param1, param2, param3;

        //

          param1=pParams[0];    
          param2=pParams[1];
          param3=pParams[2];    
      ....
}                           

2) Passing methods to async-task In order to avoid coding the async-Task infrastructure (thread, messagenhandler, ...) multiple times you might consider to pass the methods which should be executed in your async-task as a parameter. Following example outlines this approach. In addition you might have the need to subclass the async-task to pass initialization parameters in the constructor.

 /* Generic Async Task    */
interface MyGenericMethod {
    int execute(String param);
}

protected class testtask extends AsyncTask<MyGenericMethod, Void, Void>
{
    public String mParam;                           // member variable to parameterize the function
    @Override
    protected Void doInBackground(MyGenericMethod... params) {
        //  do something here
        params[0].execute("Myparameter");
        return null;
    }       
}

// to start the asynctask do something like that
public void startAsyncTask()
{
    // 
    AsyncTask<MyGenericMethod, Void, Void>  mytest = new testtask().execute(new MyGenericMethod() {
        public int execute(String param) {
            //body
            return 1;
        }
    });     
}

NameError: name 'datetime' is not defined

It can also be used as below:

from datetime import datetime
start_date = datetime(2016,3,1)
end_date = datetime(2016,3,10)

What is the difference between an Instance and an Object?

I can't believe, except for one guy no one has used the code to explain this, let me give it a shot too!

// Design Class
class HumanClass {
    var name:String
    init(name:String) {
        self.name = name
    }
}

var humanClassObject1 = HumanClass(name: "Rehan") 

Now the left side i.e: "humanClassObject1" is the object and the right side i.e: HumanClass(name: "Rehan") is the instance of this object.

var humanClassObject2 = HumanClass(name: "Ahmad") // again object on left and it's instance on the right.

So basically, instance contains the specific values for that object and objects contains the memory location (at run-time).

Remember the famous statement "object reference not set to an instance of an object", this means that non-initialised objects don't have any instance. In some programming languages like swift the compiler will not allow you to even design a class that don't have any way to initialise all it's members (variable eg: name, age e.t.c), but in some language you are allowed to do this:

// Design Class
class HumanClass {
    var name:String // See we don't have any way to initialise name property.
}

And the error will only be shown at run time when you try to do something like this:

var myClass = HumanClass()
print(myClass.name) // will give, object reference not set to an instance of the object.

This error indicates that, the specific values (for variables\property) is the "INSTANCE" as i tried to explain this above! And the object i.e: "myClass" contains the memory location (at run-time).

Use cell's color as condition in if statement (function)

Although this does not directly address your question, you can actually sort your data by cell colour in Excel (which then makes it pretty easy to label all records with a particular colour in the same way and, hence, condition upon this label).

In Excel 2010, you can do this by going to Data -> Sort -> Sort On "Cell Colour".

What is fastest children() or find() in jQuery?

Here is a link that has a performance test you can run. find() is actually about 2 times faster than children().

Chrome on OSX10.7.6

Check if a String contains numbers Java

I think it is faster than regex .

public final boolean containsDigit(String s) {
    boolean containsDigit = false;

    if (s != null && !s.isEmpty()) {
        for (char c : s.toCharArray()) {
            if (containsDigit = Character.isDigit(c)) {
                break;
            }
        }
    }

    return containsDigit;
}

How do I compare two strings in Perl?

  • cmp Compare

    'a' cmp 'b' # -1
    'b' cmp 'a' #  1
    'a' cmp 'a' #  0
    
  • eq Equal to

    'a' eq  'b' #  0
    'b' eq  'a' #  0
    'a' eq  'a' #  1
    
  • ne Not-Equal to

    'a' ne  'b' #  1
    'b' ne  'a' #  1
    'a' ne  'a' #  0
    
  • lt Less than

    'a' lt  'b' #  1
    'b' lt  'a' #  0
    'a' lt  'a' #  0
    
  • le Less than or equal to

    'a' le  'b' #  1
    'b' le  'a' #  0
    'a' le  'a' #  1
    
  • gt Greater than

    'a' gt  'b' #  0
    'b' gt  'a' #  1
    'a' gt  'a' #  0
    
  • ge Greater than or equal to

    'a' ge  'b' #  0
    'b' ge  'a' #  1
    'a' ge  'a' #  1
    

See perldoc perlop for more information.

( I'm simplifying this a little bit as all but cmp return a value that is both an empty string, and a numerically zero value instead of 0, and a value that is both the string '1' and the numeric value 1. These are the same values you will always get from boolean operators in Perl. You should really only be using the return values for boolean or numeric operations, in which case the difference doesn't really matter. )

"Agreeing to the Xcode/iOS license requires admin privileges, please re-run as root via sudo." when using GCC

I had the same issue when I tried to use git.

It is possible to install git without it. And I doubt that gcc on mac is truly dependent on XCode. And I don't want to use root to accept something unless I'm sure I need it.

I uninstalled XCode by navigating to the applications folder and dragging XCode to the trash.

Now my git commands work as usual. I'll re-install XCode if/when I truly need it.

Converting to upper and lower case in Java

I consider this simpler than any prior correct answer. I'll also throw in javadoc. :-)

/**
 * Converts the given string to title case, where the first
 * letter is capitalized and the rest of the string is in
 * lower case.
 * 
 * @param s a string with unknown capitalization
 * @return a title-case version of the string
 */
public static String toTitleCase(String s)
{
    if (s.isEmpty())
    {
        return s;
    }
    return s.substring(0, 1).toUpperCase() + s.substring(1).toLowerCase();
}

Strings of length 1 do not needed to be treated as a special case because s.substring(1) returns the empty string when s has length 1.

How to make a browser display a "save as dialog" so the user can save the content of a string to a file on his system?

Solution using only javascript

function saveFile(fileName,urlFile){
    let a = document.createElement("a");
    a.style = "display: none";
    document.body.appendChild(a);
    a.href = urlFile;
    a.download = fileName;
    a.click();
    window.URL.revokeObjectURL(url);
    a.remove();
}

let textData = `El contenido del archivo
que sera descargado`;
let blobData = new Blob([textData], {type: "text/plain"});
let url = window.URL.createObjectURL(blobData);
//let url = "pathExample/localFile.png"; // LocalFileDownload
saveFile('archivo.txt',url);

How do I set <table> border width with CSS?

<table style="border: 5px solid black">

This only adds a border around the table.

If you want same border through CSS then add this rule:

table tr td { border: 5px solid black; }

and one thing for HTML table to avoid spaces

<table cellspacing="0" cellpadding="0">

iOS - Calling App Delegate method from ViewController

Update for Swift 3.0 and higher

//
// Step 1:- Create a method in AppDelegate.swift
//
func someMethodInAppDelegate() {

    print("someMethodInAppDelegate called")
}

calling above method from your controller by followings

//
// Step 2:- Getting a reference to the AppDelegate & calling the require method...
//
if let appDelegate = UIApplication.shared.delegate as? AppDelegate {

    appDelegate.someMethodInAppDelegate()
}

Output:

enter image description here

Regular expression which matches a pattern, or is an empty string

I'm not sure why you'd want to validate an optional email address, but I'd suggest you use

^$|^[^@\s]+@[^@\s]+$

meaning

^$        empty string
|         or
^         beginning of string
[^@\s]+   any character but @ or whitespace
@         
[^@\s]+
$         end of string

You won't stop fake emails anyway, and this way you won't stop valid addresses.

Remove warning messages in PHP

You really should fix whatever's causing the warning, but you can control visibility of errors with error_reporting(). To skip warning messages, you could use something like:

error_reporting(E_ERROR | E_PARSE);

Error in eval(expr, envir, enclos) : object not found

This can happen if you don't attach your dataset.

How can I split a text into sentences?

This function can split the entire text of Huckleberry Finn into sentences in about 0.1 seconds and handles many of the more painful edge cases that make sentence parsing non-trivial e.g. "Mr. John Johnson Jr. was born in the U.S.A but earned his Ph.D. in Israel before joining Nike Inc. as an engineer. He also worked at craigslist.org as a business analyst."

# -*- coding: utf-8 -*-
import re
alphabets= "([A-Za-z])"
prefixes = "(Mr|St|Mrs|Ms|Dr)[.]"
suffixes = "(Inc|Ltd|Jr|Sr|Co)"
starters = "(Mr|Mrs|Ms|Dr|He\s|She\s|It\s|They\s|Their\s|Our\s|We\s|But\s|However\s|That\s|This\s|Wherever)"
acronyms = "([A-Z][.][A-Z][.](?:[A-Z][.])?)"
websites = "[.](com|net|org|io|gov)"

def split_into_sentences(text):
    text = " " + text + "  "
    text = text.replace("\n"," ")
    text = re.sub(prefixes,"\\1<prd>",text)
    text = re.sub(websites,"<prd>\\1",text)
    if "Ph.D" in text: text = text.replace("Ph.D.","Ph<prd>D<prd>")
    text = re.sub("\s" + alphabets + "[.] "," \\1<prd> ",text)
    text = re.sub(acronyms+" "+starters,"\\1<stop> \\2",text)
    text = re.sub(alphabets + "[.]" + alphabets + "[.]" + alphabets + "[.]","\\1<prd>\\2<prd>\\3<prd>",text)
    text = re.sub(alphabets + "[.]" + alphabets + "[.]","\\1<prd>\\2<prd>",text)
    text = re.sub(" "+suffixes+"[.] "+starters," \\1<stop> \\2",text)
    text = re.sub(" "+suffixes+"[.]"," \\1<prd>",text)
    text = re.sub(" " + alphabets + "[.]"," \\1<prd>",text)
    if "”" in text: text = text.replace(".”","”.")
    if "\"" in text: text = text.replace(".\"","\".")
    if "!" in text: text = text.replace("!\"","\"!")
    if "?" in text: text = text.replace("?\"","\"?")
    text = text.replace(".",".<stop>")
    text = text.replace("?","?<stop>")
    text = text.replace("!","!<stop>")
    text = text.replace("<prd>",".")
    sentences = text.split("<stop>")
    sentences = sentences[:-1]
    sentences = [s.strip() for s in sentences]
    return sentences

How do I force my .NET application to run as administrator?

Another way of doing this, in code only, is to detect if the process is running as admin like in the answer by @NG.. And then open the application again and close the current one.

I use this code when an application only needs admin privileges when run under certain conditions, such as when installing itself as a service. So it doesn't need to run as admin all the time like the other answers force it too.

Note in the below code NeedsToRunAsAdmin is a method that detects if under current conditions admin privileges are required. If this returns false the code will not elevate itself. This is a major advantage of this approach over the others.

Although this code has the advantages stated above, it does need to re-launch itself as a new process which isn't always what you want.

private static void Main(string[] args)
{
    if (NeedsToRunAsAdmin() && !IsRunAsAdmin())
    {
        ProcessStartInfo proc = new ProcessStartInfo();
        proc.UseShellExecute = true;
        proc.WorkingDirectory = Environment.CurrentDirectory;
        proc.FileName = Assembly.GetEntryAssembly().CodeBase;

        foreach (string arg in args)
        {
            proc.Arguments += String.Format("\"{0}\" ", arg);
        }

        proc.Verb = "runas";

        try
        {
            Process.Start(proc);
        }
        catch
        {
            Console.WriteLine("This application requires elevated credentials in order to operate correctly!");
        }
    }
    else
    {
        //Normal program logic...
    }
}

private static bool IsRunAsAdmin()
{
    WindowsIdentity id = WindowsIdentity.GetCurrent();
    WindowsPrincipal principal = new WindowsPrincipal(id);

    return principal.IsInRole(WindowsBuiltInRole.Administrator);
}

How to read a string one letter at a time in python

# Open the file
f = open('morseCode.txt', 'r')

# Read the morse code data into "letters" [(lowercased letter, morse code), ...]
letters = []
for Line in f:
    if not Line.strip(): break
    letter, code = Line.strip().split() # Assuming the format is <letter><whitespace><morse code><newline>
    letters.append((letter.lower(), code))
f.close()

# Get the input from the user
# (Don't use input() - it calls eval(raw_input())!)
i = raw_input("Enter a string to be converted to morse code or press <enter> to quit ") 

# Convert the codes to morse code
out = []
for c in i:
    found = False
    for letter, code in letters:
        if letter == c.lower():
            found = True
            out.append(code)
            break

    if not found: 
        raise Exception('invalid character: %s' % c)

# Print the output
print ' '.join(out)

What is the meaning of {...this.props} in Reactjs

It is ES-6 feature. It means you extract all the properties of props in div.{... }

operator is used to extract properties of an object.

Which is the best IDE for Python For Windows

U can use eclipse. but u need to download pydev addon for that.

MongoDB Aggregation: How to get total records count?

Solution provided by @Divergent does work, but in my experience it is better to have 2 queries:

  1. First for filtering and then grouping by ID to get number of filtered elements. Do not filter here, it is unnecessary.
  2. Second query which filters, sorts and paginates.

Solution with pushing $$ROOT and using $slice runs into document memory limitation of 16MB for large collections. Also, for large collections two queries together seem to run faster than the one with $$ROOT pushing. You can run them in parallel as well, so you are limited only by the slower of the two queries (probably the one which sorts).

I have settled with this solution using 2 queries and aggregation framework (note - I use node.js in this example, but idea is the same):

var aggregation = [
  {
    // If you can match fields at the begining, match as many as early as possible.
    $match: {...}
  },
  {
    // Projection.
    $project: {...}
  },
  {
    // Some things you can match only after projection or grouping, so do it now.
    $match: {...}
  }
];


// Copy filtering elements from the pipeline - this is the same for both counting number of fileter elements and for pagination queries.
var aggregationPaginated = aggregation.slice(0);

// Count filtered elements.
aggregation.push(
  {
    $group: {
      _id: null,
      count: { $sum: 1 }
    }
  }
);

// Sort in pagination query.
aggregationPaginated.push(
  {
    $sort: sorting
  }
);

// Paginate.
aggregationPaginated.push(
  {
    $limit: skip + length
  },
  {
    $skip: skip
  }
);

// I use mongoose.

// Get total count.
model.count(function(errCount, totalCount) {
  // Count filtered.
  model.aggregate(aggregation)
  .allowDiskUse(true)
  .exec(
  function(errFind, documents) {
    if (errFind) {
      // Errors.
      res.status(503);
      return res.json({
        'success': false,
        'response': 'err_counting'
      });
    }
    else {
      // Number of filtered elements.
      var numFiltered = documents[0].count;

      // Filter, sort and pagiante.
      model.request.aggregate(aggregationPaginated)
      .allowDiskUse(true)
      .exec(
        function(errFindP, documentsP) {
          if (errFindP) {
            // Errors.
            res.status(503);
            return res.json({
              'success': false,
              'response': 'err_pagination'
            });
          }
          else {
            return res.json({
              'success': true,
              'recordsTotal': totalCount,
              'recordsFiltered': numFiltered,
              'response': documentsP
            });
          }
      });
    }
  });
});

Why is Node.js single threaded?

The issue with the "one thread per request" model for a server is that they don't scale well for several scenarios compared to the event loop thread model.

Typically, in I/O intensive scenarios the requests spend most of the time waiting for I/O to complete. During this time, in the "one thread per request" model, the resources linked to the thread (such as memory) are unused and memory is the limiting factor. In the event loop model, the loop thread selects the next event (I/O finished) to handle. So the thread is always busy (if you program it correctly of course).

The event loop model as all new things seems shiny and the solution for all issues but which model to use will depend on the scenario you need to tackle. If you have an intensive I/O scenario (like a proxy), the event base model will rule, whereas a CPU intensive scenario with a low number of concurrent processes will work best with the thread-based model.

In the real world most of the scenarios will be a bit in the middle. You will need to balance the real need for scalability with the development complexity to find the correct architecture (e.g. have an event base front-end that delegates to the backend for the CPU intensive tasks. The front end will use little resources waiting for the task result.) As with any distributed system it requires some effort to make it work.

If you are looking for the silver bullet that will fit with any scenario without any effort, you will end up with a bullet in your foot.

SQL Server database restore error: specified cast is not valid. (SqlManagerUI)

Could be because of restoring SQL Server 2012 version backup file into SQL Server 2008 R2 or even less.

(XML) The markup in the document following the root element must be well-formed. Start location: 6:2

In XML there can be only one root element - you have two - heading and song.

If you restructure to something like:

<?xml version="1.0" encoding="UTF-8"?>
<song> 
 <heading>
 The Twelve Days of Christmas
 </heading>
 ....
</song>

The error about well-formed XML on the root level should disappear (though there may be other issues).

UIScrollView Scrollable Content Size Ambiguity

I had the same issue. Untick this checkbox. Since you are setting the content size in code. enter image description here

Rubymine: How to make Git ignore .idea files created by Rubymine

While it's not been too long that I made the switch to Rubymine, I found it challenging ignoring .idea files of Rubymine from been committed to git.

Here's how I fixed it

If you've not done any staging/commit at all, or you just spinned up a new project in Ruby mine, then simply do this

Option 1

Add the line below to the .gitignore file which is usually placed at the root of your repository.

# Ignore .idea files
.idea/

This will ensure that all .idea files are ignored from been tracked by git, although they will still remain in your project folder locally.

Option 2

If you've however done some staging/commit, or you just opened up an existing project in Ruby mine, then simply do this

Run the code in your terminal/command line

git rm -r --cached .idea

This deletes already tracked .idea files in git

Next, include .idea/ to the .gitignore file which is usually placed at the root of your repository.

# Ignore .idea files
.idea/

This will ensure that all .idea files are ignored from been tracked by git, although they will still remain in your project folder locally.

Option 3

If you've however done some staging/commit, or you just opened up an existing project in Ruby mine, and want to totally delete .idea files locally and in git, then simply do this

Run the code in your terminal/command line

git rm -r --cached .idea

This deletes already tracked .idea files in git

Run the code in your terminal/command line

rm -r .idea

This deletes all .idea files including the folder locally

Next, include .idea/ to the .gitignore file which is usually placed at the root of your repository.

# Ignore .idea files
.idea/

This will ensure that all .idea files are ignored from been tracked by git, and also deleted from your project folder locally.

That's all

I hope this helps

What's the difference between unit, functional, acceptance, and integration tests?

I will explain you this with a practical example and no theory stuff:

A developer writes the code. No GUI is implemented yet. The testing at this level verifies that the functions work correctly and the data types are correct. This phase of testing is called Unit testing.

When a GUI is developed, and application is assigned to a tester, he verifies business requirements with a client and executes the different scenarios. This is called functional testing. Here we are mapping the client requirements with application flows.

Integration testing: let's say our application has two modules: HR and Finance. HR module was delivered and tested previously. Now Finance is developed and is available to test. The interdependent features are also available now, so in this phase, you will test communication points between the two and will verify they are working as requested in requirements.

Regression testing is another important phase, which is done after any new development or bug fixes. Its aim is to verify previously working functions.

How do I merge two dictionaries in a single expression (taking union of dictionaries)?

A hacky one-liner for 2.5+ :

>>> a = dict(x=2, y=3)
>>> b = dict(y=4, z=5)
>>> c = 'No Effect' if a.update(b) else a
>>> c
{'x': 2, 'y': 4, 'z': 5}

Things to keep in mind:

  • dict.update modifies the dict in-place, hence it evaluates to None
  • In expression A if C else B, C is evaluated first. See here

So here, a.update(b) is evaluated first, a gets updated with b and operation results in None, thus the expression will always return the value given in the else condition, i.e. a. Since, a is already modified, it will return the new value of a, which is the updated dict.

IMPROVEMENT

This can be further improved, and it be made to work for even older versions (probably python 1.0 as well?):

>>> c = a.update(b) or a

Here also, the first part produces None, hence it always returns the second part, but as the update operation is already done, it always returns the updated dict.

CRITIQUE

  • Both the solution modify the value of a, so if one wants to keep both the input dictionaries unchanged, this is not a good idea.

IMPROVEMENT

If copy of a is needed, the second one can be slightly modified:

>>> a = dict(x=2, y=3)
>>> b = dict(y=4, z=5)
>>> a, c = a.copy(), a.update(b) or a
>>> c
{'x': 2, 'y': 4, 'z': 5}
>>> d = dict(m=10, n=11)
>>> a, c = a.copy(), a.update(b) or a.update(d) or a
>>> c
{'x': 2, 'y': 4, 'z': 5, 'm': 10, 'n': 11}
>>> a
{'x': 2, 'y': 4}

CAVEATS

  • It (especially the first one) gets ugly and impractical for any number of dicts greater than 2
  • Furthermore, this is not explicit, which is un-pythonic.

Even though these solutions are extremely fast, especially the or method which is probably faster than the new python 3.9 union operator (not entirely sure, further testing required, if anyone wants to add it afterwards, they are welcome), I would not recommend these methods due to the abovementioned reasons. Added it for the sake of completeness.

MVC : The parameters dictionary contains a null entry for parameter 'k' of non-nullable type 'System.Int32'

I am also new to MVC and I received the same error and found that it is not passing proper routeValues in the Index view or whatever view is present to view the all data.

It was as below

<td>
            @Html.ActionLink("Edit", "Edit", new { /* id=item.PrimaryKey */ }) |
            @Html.ActionLink("Details", "Details", new { /* id=item.PrimaryKey */ }) |
            @Html.ActionLink("Delete", "Delete", new { /* id=item.PrimaryKey */ })
        </td>

I changed it to the as show below and started to work properly.

<td>
            @Html.ActionLink("Edit", "Edit", new { EmployeeID=item.EmployeeID }) |
            @Html.ActionLink("Details", "Details", new { /* id=item.PrimaryKey */ }) |
            @Html.ActionLink("Delete", "Delete", new { /* id=item.PrimaryKey */ })
        </td>

Basically this error can also come because of improper navigation also.

How to add new line in Markdown presentation?

I wanted to create a MarkdownPreviewer in react as part of a project in freecodecamp. So I was desperately searching for newline characters for markdown. After trying many suggestions. I finally used \n and it worked.

How to create radio buttons and checkbox in swift (iOS)?

Check out DLRadioButton. You can add and customize radio buttons directly from the Interface Builder. Also works with Swift perfectly.

Swift Radio Button for iOS

Update: version 1.3.2 added square buttons, also improved performance.

Update: version 1.4.4 added multiple selection option, can be used as checkbox as well.

Update: version 1.4.7 added RTL language support.

nginx showing blank PHP pages

None of the above answers worked for me - PHP was properly rendering everything except pages that relied on mysqli, for which it was sending a blank page with a 200 response code and not throwing any errors. As I'm on OS X, the fix was simply

sudo port install php56-mysql

followed by a restart of PHP-FPM and nginx.

I was migrating from an older Apache/PHP setup to nginx, and failed to notice the version mismatch in the driver for php-mysql and php-fpm.

Difference between dict.clear() and assigning {} in Python

Mutating methods are always useful if the original object is not in scope:

def fun(d):
    d.clear()
    d["b"] = 2

d={"a": 2}
fun(d)
d          # {'b': 2}

Re-assigning the dictionary would create a new object and wouldn't modify the original one.

How can one create an overlay in css?

Here is an overlay using a pseudo-element (eg: no need to add more markup to do it)

_x000D_
_x000D_
.box {_x000D_
  background: 0 0 url(http://ianfarb.com/wp-content/uploads/2013/10/nicholas-hodag.jpg);_x000D_
  width: 300px;_x000D_
  height: 200px;_x000D_
}_x000D_
_x000D_
.box:after {_x000D_
  content: "";_x000D_
  display: block;_x000D_
  width: 100%;_x000D_
  height: 100%;_x000D_
  background: rgba(0, 0, 0, 0.4);_x000D_
}
_x000D_
  <div class="box"></div>
_x000D_
_x000D_
_x000D_

What's the difference between an element and a node in XML?

Now i know ,the element is one of node

All node types in here"http://www.w3schools.com/dom/dom_nodetype.asp"

Element is between the start tag and end in the end tag

So text node is a node , but not a element.

BeautifulSoup getting href

You can use find_all in the following way to find every a element that has an href attribute, and print each one:

from BeautifulSoup import BeautifulSoup

html = '''<a href="some_url">next</a>
<span class="class"><a href="another_url">later</a></span>'''

soup = BeautifulSoup(html)

for a in soup.find_all('a', href=True):
    print "Found the URL:", a['href']

The output would be:

Found the URL: some_url
Found the URL: another_url

Note that if you're using an older version of BeautifulSoup (before version 4) the name of this method is findAll. In version 4, BeautifulSoup's method names were changed to be PEP 8 compliant, so you should use find_all instead.


If you want all tags with an href, you can omit the name parameter:

href_tags = soup.find_all(href=True)

Move entire line up and down in Vim

In case you want to do this on multiple lines that match a specific search:

  • Up: :g/Your query/ normal ddp or :g/Your query/ m -1
  • Down :g/Your query/ normal ddp or :g/Your query/ m +1

Getting file size in Python?

Try

os.path.getsize(filename)

It should return the size of a file, reported by os.stat().

Select 2 columns in one and combine them

select column1 || ' ' || column2 as whole_name FROM tablename;

Here || is the concat operator used for concatenating them to single column and ('') inside || used for space between two columns.

Rails 4 image-path, image-url and asset-url no longer work in SCSS files

I just had this issue myself. 3 points that will hopefully help:

  • If you place images in your app/assets/images directory, then you should be able to call the image directly with no prefix in the path. ie. image_url('logo.png')
  • Depending on where you use the asset will depend on the method. If you are using it as a background-image: property, then your line of code should be background-image: image-url('logo.png'). This works for both less and sass stylesheets. If you are using it inline in the view, then you will need to use the built in image_tag helper in rails to output your image. Once again, no prefixing <%= image_tag 'logo.png' %>
  • Lastly, if you are precompiling your assets, run rake assets:precompile to generate your assets, or rake assets:precompile RAILS_ENV=production for production, otherwise, your production environment will not have the fingerprinted assets when loading the page.

Also for those commands in point 3 you will need to prefix them with bundle exec if you are running bundler.

Makefile - missing separator

You need to precede the lines starting with gcc and rm with a hard tab. Commands in make rules are required to start with a tab (unless they follow a semicolon on the same line). The result should look like this:

PROG = semsearch
all: $(PROG)
%: %.c
        gcc -o $@ $< -lpthread

clean:
        rm $(PROG)

Note that some editors may be configured to insert a sequence of spaces instead of a hard tab. If there are spaces at the start of these lines you'll also see the "missing separator" error. If you do have problems inserting hard tabs, use the semicolon way:

PROG = semsearch
all: $(PROG)
%: %.c ; gcc -o $@ $< -lpthread

clean: ; rm $(PROG)

Best way to add Activity to an Android project in Eclipse?

An easy method suggested by Google Android Developer Community.

enter image description here

Express-js wildcard routing to cover everything under and including a path

I think you will have to have 2 routes. If you look at line 331 of the connect router the * in a path is replaced with .+ so will match 1 or more characters.

https://github.com/senchalabs/connect/blob/master/lib/middleware/router.js

If you have 2 routes that perform the same action you can do the following to keep it DRY.

var express = require("express"),
    app = express.createServer();

function fooRoute(req, res, next) {
  res.end("Foo Route\n");
}

app.get("/foo*", fooRoute);
app.get("/foo", fooRoute);

app.listen(3000);

Changing an element's ID with jQuery

I did something similar with this construct

$('li').each(function(){
  if(this.id){
    this.id = this.id+"something";
  }
});

Is it better practice to use String.format over string Concatenation in Java?

There could be a perceptible difference.

String.format is quite complex and uses a regular expression underneath, so don't make it a habit to use it everywhere, but only where you need it.

StringBuilder would be an order of magnitude faster (as someone here already pointed out).

Responsive css background images

CSS:

background-size: 100%;

That should do the trick! :)

Setting query string using Fetch GET request

Was just working with Nativescript's fetchModule and figured out my own solution using string manipulation. Append the query string bit by bit to the url. Here is an example where query is passed as a json object (query = {order_id: 1}):

function performGetHttpRequest(fetchLink='http://myapi.com/orders', query=null) {
    if(query) {
        fetchLink += '?';
        let count = 0;
        const queryLength = Object.keys(query).length;
        for(let key in query) {
            fetchLink += key+'='+query[key];
            fetchLink += (count < queryLength) ? '&' : '';
            count++;
        }
    }
    // link becomes: 'http://myapi.com/orders?order_id=1'
    // Then, use fetch as in MDN and simply pass this fetchLink as the url.
}

I tested this over a multiple number of query parameters and it worked like a charm :) Hope this helps someone.

Call javascript from MVC controller action

Since your controller actions execute on the server, and JavaScript (usually) executes on the client (browser), this doesn't make sense. If you need some action to happen by default once the page is loaded into the browser, you can use JavaScript's document.OnLoad event handler.

How to print instances of a class using print()?

You need to use __repr__. This is a standard function like __init__. For example:

class Foobar():
    """This will create Foobar type object."""

    def __init__(self):
        print "Foobar object is created."

    def __repr__(self):
        return "Type what do you want to see here."

a = Foobar()

print a

How to automatically indent source code?

In 2010 it is ctrl +k +d for indentation

Twitter Bootstrap Use collapse.js on table cells [Almost Done]

Expanding on Tony's answer, and also answering Dhaval Ptl's question, to get the true accordion effect and only allow one row to be expanded at a time, an event handler for show.bs.collapse can be added like so:

$('.collapse').on('show.bs.collapse', function () {
    $('.collapse.in').collapse('hide');
});

I modified his example to do this here: http://jsfiddle.net/QLfMU/116/

Set maxlength in Html Textarea

As I said in a comment to aqingsao's answer, it doesn't quite work when the textarea has newline characters, at least on Windows.

I've change his answer slightly thus:

$(function() {
    $("textarea[maxlength]").bind('input propertychange', function() {
        var maxLength = $(this).attr('maxlength');
        //I'm guessing JavaScript is treating a newline as one character rather than two so when I try to insert a "max length" string into the database I get an error.
        //Detect how many newlines are in the textarea, then be sure to count them twice as part of the length of the input.
        var newlines = ($(this).val().match(/\n/g) || []).length
        if ($(this).val().length + newlines > maxLength) {
            $(this).val($(this).val().substring(0, maxLength - newlines));
        }
    })
});

Now when I try to paste a lot of data in with newlines, I get exactly the right number of characters.

Tools for making latex tables in R

You can also use the latextable function from the R package micsFuncs:

http://cran.r-project.org/web/packages/miscFuncs/index.html

latextable(M) where M is a matrix with mixed alphabetic and numeric entries outputs a basic LaTeX table onto screen, which can be copied and pasted into a LaTeX document. Where there are small numbers, it also replaces these with index notation (eg 1.2x10^{-3}).

Which JDK version (Language Level) is required for Android Studio?

Android Studio now comes bundled with OpenJDK 8 . Legacy projects can still use JDK7 or JDK8

Reference: https://developer.android.com/studio/releases/index.html

Types in MySQL: BigInt(20) vs Int(20)

The number in parentheses in a type declaration is display width, which is unrelated to the range of values that can be stored in a data type. Just because you can declare Int(20) does not mean you can store values up to 10^20 in it:

[...] This optional display width may be used by applications to display integer values having a width less than the width specified for the column by left-padding them with spaces. ...

The display width does not constrain the range of values that can be stored in the column, nor the number of digits that are displayed for values having a width exceeding that specified for the column. For example, a column specified as SMALLINT(3) has the usual SMALLINT range of -32768 to 32767, and values outside the range allowed by three characters are displayed using more than three characters.

For a list of the maximum and minimum values that can be stored in each MySQL datatype, see here.

Download single files from GitHub

My simple way to do it is:

  1. click the 'Raw' button to get the file contents of github_csv.csv shown on the browser.
  2. Then create file.csv and open it in a text editor like notepad
  3. Then copy the file content from the website and paste it on the file.csv
  4. Your file.csv is github_csv.csv

Internet Access in Ubuntu on VirtualBox

I could get away with the following solution (works with Ubuntu 14 guest VM on Windows 7 host or Ubuntu 9.10 Casper guest VM on host Windows XP x86):

  1. Go to network connections -> Virtual Box Host-Only Network -> Select "Properties"
  2. Check VirtualBox Bridged Networking Driver
  3. Come to VirtualBox Manager, choose the network adapter as Bridged Adapter and Name to the device in Step #1.
  4. Restart the VM.

How can I remove 3 characters at the end of a string in php?

Just do:

echo substr($string, 0, -3);

You don't need to use a strlen call, since, as noted in the substr docs:

If length is given and is negative, then that many characters will be omitted from the end of string

How do I find out which computer is the domain controller in Windows programmatically?

In C#/.NET 3.5 you could write a little program to do:

using (PrincipalContext context = new PrincipalContext(ContextType.Domain))
{
    string controller = context.ConnectedServer;
    Console.WriteLine( "Domain Controller:" + controller );
} 

This will list all the users in the current domain:

using (PrincipalContext context = new PrincipalContext(ContextType.Domain))
{
    using (UserPrincipal searchPrincipal = new UserPrincipal(context))
    {
       using (PrincipalSearcher searcher = new PrincipalSearcher(searchPrincipal))
       {
           foreach (UserPrincipal principal in searcher.FindAll())
           {
               Console.WriteLine( principal.SamAccountName);
           }
       }
    }
}

Scroll to bottom of div with Vue.js

  1. Use ref attribute on DOM element for reference
<div class="content scrollable" ref="msgContainer">
    <!-- content -->
</div>
  1. You need to setup a WATCH
  data() {
    return {
      count: 5
    };
  },
  watch: {
    count: function() {
      this.$nextTick(function() {
        var container = this.$refs.msgContainer;
        container.scrollTop = container.scrollHeight + 120;
      });
    }
  }
  1. Ensure you're using proper CSS
.scrollable {
  overflow: hidden;
  overflow-y: scroll;
  height: calc(100vh - 20px);
}

How do I extract specific 'n' bits of a 32-bit unsigned integer in C?

There is a single BEXTR (Bit field extract (with register)) x86 instruction on Intel and AMD CPUs and UBFX on ARM. There are intrinsic functions such as _bextr_u32() (link requires sign-in) that allow to invoke this instruction explicitly.

They implement (source >> offset) & ((1 << n) - 1) C code: get n continuous bits from source starting at the offset bit. Here's a complete function definition that handles edge cases:

#include <limits.h>

unsigned getbits(unsigned value, unsigned offset, unsigned n)
{
  const unsigned max_n = CHAR_BIT * sizeof(unsigned);
  if (offset >= max_n)
    return 0; /* value is padded with infinite zeros on the left */
  value >>= offset; /* drop offset bits */
  if (n >= max_n)
    return value; /* all  bits requested */
  const unsigned mask = (1u << n) - 1; /* n '1's */
  return value & mask;
}

For example, to get 3 bits from 2273 (0b100011100001) starting at 5-th bit, call getbits(2273, 5, 3)—it extracts 7 (0b111).

For example, say I want the first 17 bits of the 32-bit value; what is it that I should do?

unsigned first_bits = value & ((1u << 17) - 1); // & 0x1ffff

Assuming CHAR_BIT * sizeof(unsigned) is 32 on your system.

I presume I am supposed to use the modulus operator and I tried it and was able to get the last 8 bits and last 16 bits

unsigned last8bitsvalue  = value & ((1u <<  8) - 1); // & 0xff
unsigned last16bitsvalue = value & ((1u << 16) - 1); // & 0xffff

If the offset is always zero as in all your examples in the question then you don't need the more general getbits(). There is a special cpu instruction BLSMSK that helps to compute the mask ((1 << n) - 1).

What value could I insert into a bit type column?

If you're using SQL Server, you can set the value of bit fields with 0 and 1

or

'true' and 'false' (yes, using strings)

...your_bit_field='false'... => equivalent to 0

Today's Date in Perl in MM/DD/YYYY format

If you like doing things the hard way:

my (undef,undef,undef,$mday,$mon,$year) = localtime;
$year = $year+1900;
$mon += 1;
if (length($mon)  == 1) {$mon = "0$mon";}
if (length($mday) == 1) {$mday = "0$mday";}
my $today = "$mon/$mday/$year";

Android Studio doesn't see device

In case anyone having problem with Samsung GT-I9060 I followed this answer on SO:

If you are on windows, many times it will not recognize the device fully and because of driver issues, the device won't show up.

  1. go to settings
  2. control panel
  3. hardware and sound
  4. device manager

And look for any devices showing an error. Many androids will show as an unknown USB device. Select that device and try to update the drivers for it.

I uninstalled the device, unplug the device and plug it again. This time Windows properly installed the driver. What a bummer.

How to detect if URL has changed after hash in JavaScript

In modern browsers (IE8+, FF3.6+, Chrome), you can just listen to the hashchange event on window.

In some old browsers, you need a timer that continually checks location.hash. If you're using jQuery, there is a plugin that does exactly that.

git diff between two different files

Specify the paths explicitly:

git diff HEAD:full/path/to/foo full/path/to/bar

Check out the --find-renames option in the git-diff docs.

Credit: twaggs.

SSH to Elastic Beanstalk instance

My experience in August 2013 with a linux client and a simple AWS Beanstalk installation (single EC2 instance) is as follows (based on Community Wiki above)

Configure Security Group

  1. In the AWS console, select EC2 to go to the EC2 Dashboard
  2. Discover the security group to which your EC2 instance belongs by clicking Instances in the left hand panel and then selecting the instance you want to connect to (in my case there is only one - called Default Environment). The details are shown at the base of the page - You should see a field for Security Groups - make a note of the name - in my case "awsweb...".
  3. From the left hand panel select Security Groups.
  4. Select the awsweb... security group and the details should show at the base of the page
  5. Select the Inbound tab and choose SSH from the "Create a New Rule" drop down. Insert the ip address/CIDR of your local machine (from which you intend to connect), e.g. 192.168.0.12/32 and click Add Rule and Apply Rule Changes.

Create Public-Private Key Pair

  1. From the EC2 dashboard select Key Pairs from the left hand panel
  2. Click Key Pair (at top) and enter a name such as myname-key-pair-myregion or whatever valid key name you like.
  3. Confirm and then accept the download of the private key from the browser saving it for instance to your home directory or wherever you fancy. Make sure the directory only has write permissions for you.

Associate the Public Private Key Pair with the Elastic Beanstalk EC2 Server

  1. To add a public-private key pair to an Elastic Beanstalk EC2 instance do: Services -> Elastic Beanstalk -> My App -> Default Environment takes you to the default environment (the one where you upload your app)
  2. Click Configuration (on left hand panel) and then on the gear/cog associated with "Instances"
  3. A page entitled "Server" is displayed
  4. Select your prebuilt key par from EC2 Key Pair and do Save
  5. Some warning message is displayed so do Save again.

Connect to AWS EC2 Instance using SSH

  1. In a terminal session change to the directory containing your private key (.pem file).
  2. If you've had a few goes at this you should probably do something about .ssh/known_hosts if you have one such as renaming it. Otherwise you may get an error about the host's identity having changed.
  3. Do: ssh -i ./myname-key-pair-my-region.pem [email protected]

Good luck

Display an image into windows forms

Here (http://www.dotnetperls.com/picturebox) there 3 ways to do this:

  • Like you are doing.
  • Using ImageLocation property of the PictureBox like:

    private void Form1_Load(object sender, EventArgs e)
    {
        PictureBox pb1 = new PictureBox();            
        pb1.ImageLocation = "../SamuderaJayaMotor.png";
        pb1.SizeMode = PictureBoxSizeMode.AutoSize;
    }
    
  • Using an image from the web like:

    private void Form1_Load(object sender, EventArgs e)
    {
        PictureBox pb1 = new PictureBox();            
        pb1.ImageLocation = "http://www.dotnetperls.com/favicon.ico";
        pb1.SizeMode = PictureBoxSizeMode.AutoSize;
    }
    

And please, be sure that "../SamuderaJayaMotor.png" is the correct path of the image that you are using.

jQuery/JavaScript to replace broken images

Here is a quick-and-dirty way to replace all the broken images, and there is no need to change the HTML code ;)

codepen example

    $("img").each(function(){
        var img = $(this);
        var image = new Image();
        image.src = $(img).attr("src");
        var no_image = "https://dummyimage.com/100x100/7080b5/000000&text=No+image";
        if (image.naturalWidth == 0 || image.readyState == 'uninitialized'){
            $(img).unbind("error").attr("src", no_image).css({
                height: $(img).css("height"),
                width: $(img).css("width"),
            });
        }
  });

Bootstrap dropdown not working

I had the same problem. After a couple of hours of trouble shooting found that,

I had

<script type="text/javascript" src="Scripts/bootstrap.min.js"></script>
<script type="text/javascript" src="Scripts/jquery-2.1.1.min.js"></script>

instead of,

<script type="text/javascript" src="Scripts/jquery-2.1.1.min.js"></script>
<script type="text/javascript" src="Scripts/bootstrap.min.js"></script>

Hope this helps someone

java.lang.NoClassDefFoundError: javax/mail/Authenticator, whats wrong?

When I had this problem, I had included the mail-api.jar in my maven pom file. That's the API specification only. The fix is to replace this:

<!-- DO NOT USE - it's just the API, not an implementation -->
<groupId>javax.mail</groupId>
<artifactId>javax.mail-api</artifactId>

with the reference implementation of that api:

<groupId>com.sun.mail</groupId>
<artifactId>javax.mail</artifactId>

I know it has sun in the package name, but that's the latest version. I learned this from https://stackoverflow.com/a/28935760/1128668

PopupWindow $BadTokenException: Unable to add window -- token null is not valid

Same problem happened with me when i try to show popup menu in activity i also got same excpetion but i encounter problem n resolve by providing context

YourActivityName.this instead of getApplicationContext() at

Dialog dialog = new Dialog(getApplicationContext());

and yes it worked for me may it will help someone else

How to invoke a Linux shell command from Java

Building on @Tim's example to make a self-contained method:

import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;
import java.util.ArrayList;

public class Shell {

    /** Returns null if it failed for some reason.
     */
    public static ArrayList<String> command(final String cmdline,
    final String directory) {
        try {
            Process process = 
                new ProcessBuilder(new String[] {"bash", "-c", cmdline})
                    .redirectErrorStream(true)
                    .directory(new File(directory))
                    .start();

            ArrayList<String> output = new ArrayList<String>();
            BufferedReader br = new BufferedReader(
                new InputStreamReader(process.getInputStream()));
            String line = null;
            while ( (line = br.readLine()) != null )
                output.add(line);

            //There should really be a timeout here.
            if (0 != process.waitFor())
                return null;

            return output;

        } catch (Exception e) {
            //Warning: doing this is no good in high quality applications.
            //Instead, present appropriate error messages to the user.
            //But it's perfectly fine for prototyping.

            return null;
        }
    }

    public static void main(String[] args) {
        test("which bash");

        test("find . -type f -printf '%T@\\\\t%p\\\\n' "
            + "| sort -n | cut -f 2- | "
            + "sed -e 's/ /\\\\\\\\ /g' | xargs ls -halt");

    }

    static void test(String cmdline) {
        ArrayList<String> output = command(cmdline, ".");
        if (null == output)
            System.out.println("\n\n\t\tCOMMAND FAILED: " + cmdline);
        else
            for (String line : output)
                System.out.println(line);

    }
}

(The test example is a command that lists all files in a directory and its subdirectories, recursively, in chronological order.)

By the way, if somebody can tell me why I need four and eight backslashes there, instead of two and four, I can learn something. There is one more level of unescaping happening than what I am counting.

Edit: Just tried this same code on Linux, and there it turns out that I need half as many backslashes in the test command! (That is: the expected number of two and four.) Now it's no longer just weird, it's a portability problem.

Getting values from JSON using Python

Using Python to extract a value from the provided Json

Working sample:-

import json
import sys

//load the data into an element
data={"test1" : "1", "test2" : "2", "test3" : "3"}

//dumps the json object into an element
json_str = json.dumps(data)

//load the json to a string
resp = json.loads(json_str)

//print the resp
print (resp)

//extract an element in the response
print (resp['test1'])