Programs & Examples On #Geometry shader

Geometry shader should not be mixed up with [vertex-shader], but are shader programs executed after vertex shaders. They take as input a whole primitive like point, line or triangle.

How to get document height and width without using jquery

var height = document.body.clientHeight;
var width = document.body.clientWidth;

Check: this article for better explanation.

ActivityCompat.requestPermissions not showing dialog box

I was having the same problem, and solved it by replacing Manifest.permission.READ_PHONE_STATE with android.Manifest.permission.READ_PHONE_STATE.

ListBox with ItemTemplate (and ScrollBar!)

ListBox will try to expand in height that is available.. When you set the Height property of ListBox you get a scrollviewer that actually works...

If you wish your ListBox to accodate the height available, you might want to try to regulate the Height from your parent controls.. In a Grid for example, setting the Height to Auto in your RowDefinition might do the trick...

HTH

Unsupported operand type(s) for +: 'int' and 'str'

try,

str_list = " ".join([str(ele) for ele in numlist])

this statement will give you each element of your list in string format

print("The list now looks like [{0}]".format(str_list))

and,

change print(numlist.pop(2)+" has been removed") to

print("{0} has been removed".format(numlist.pop(2)))

as well.

AngularJS - $http.post send data as json

i think the most proper way is to use the same piece of code angular use when doing a "get" request using you $httpParamSerializer will have to inject it to your controller so you can simply do the following without having to use Jquery at all , $http.post(url,$httpParamSerializer({param:val}))

app.controller('ctrl',function($scope,$http,$httpParamSerializer){
  $http.post(url,$httpParamSerializer({param:val,secondParam:secondVal}));
}

Sublime Text 2 - Show file navigation in sidebar

I added the Context Menu item for Folders to open in Sublime Text. In windows, you can right click on any Folder and open the structure in Sublime. You could also create a service (?) for Mac OS - I'm just not familiar with the process.

The following could be saved to a File (OpenFolderWithSublime.reg) to merge to the registry. Be Sure to modify the directory structure to appropriately point to your Sublime installation. Alternatively, you can use REGEDIT and browse to HKCR\Folder\shell and create the values manually.

Windows Registry Editor Version 5.00

[HKEY_CLASSES_ROOT\Folder\shell\Open with Sublime Text]

[HKEY_CLASSES_ROOT\Folder\shell\Open with Sublime Text\command]
@="C:\\Program Files\\Sublime Text 2\\sublime_text \"%1\""

Comparing a variable with a string python not working when redirecting from bash script

When you read() the file, you may get a newline character '\n' in your string. Try either

if UserInput.strip() == 'List contents': 

or

if 'List contents' in UserInput: 

Also note that your second file open could also use with:

with open('/Users/.../USER_INPUT.txt', 'w+') as UserInputFile:     if UserInput.strip() == 'List contents': # or if s in f:         UserInputFile.write("ls")     else:         print "Didn't work" 

DisplayName attribute from Resources?

public class Person
{
    // Before C# 6.0
    [Display(Name = "Age", ResourceType = typeof(Testi18n.Resource))]
    public string Age { get; set; }

    // After C# 6.0
    // [Display(Name = nameof(Resource.Age), ResourceType = typeof(Resource))]
}
  1. Define ResourceType of the attribute so it looks for a resource
  2. Define Name of the attribute which is used for the key of resource, after C# 6.0, you can use nameof for strong typed support instead of hard coding the key.

  3. Set the culture of current thread in the controller.

Resource.Culture = CultureInfo.GetCultureInfo("zh-CN");

  1. Set the accessibility of the resource to public

  2. Display the label in cshtml like this

@Html.DisplayNameFor(model => model.Age)

VBA: Convert Text to Number

This converts all text in columns of an Excel Workbook to numbers.

Sub ConvertTextToNumbers()
Dim wBook As Workbook
Dim LastRow As Long, LastCol As Long
Dim Rangetemp As Range

'Enter here the path of your workbook
Set wBook = Workbooks.Open("yourWorkbook")
LastRow = Cells.Find(What:="*", After:=Range("A1"), SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row
LastCol = Cells.Find(What:="*", After:=Range("A1"), SearchOrder:=xlByColumns, SearchDirection:=xlPrevious).Column

For c = 1 To LastCol
Set Rangetemp = Cells(c).EntireColumn
Rangetemp.TextToColumns DataType:=xlDelimited, _
    TextQualifier:=xlDoubleQuote, ConsecutiveDelimiter:=False, Tab:=True, _
    Semicolon:=False, Comma:=False, Space:=False, Other:=False, FieldInfo _
    :=Array(1, 1), TrailingMinusNumbers:=True
Next c
End Sub

How to sort an array in Bash

sorted=($(echo ${array[@]} | tr " " "\n" | sort))

In the spirit of bash / linux, I would pipe the best command-line tool for each step. sort does the main job but needs input separated by newline instead of space, so the very simple pipeline above simply does:

Echo array content --> replace space by newline --> sort

$() is to echo the result

($()) is to put the "echoed result" in an array

Note: as @sorontar mentioned in a comment to a different question:

The sorted=($(...)) part is using the "split and glob" operator. You should turn glob off: set -f or set -o noglob or shopt -op noglob or an element of the array like * will be expanded to a list of files.

HTML/CSS - Adding an Icon to a button

Here's what you can do using font-awesome library.

_x000D_
_x000D_
button.btn.add::before {_x000D_
  font-family: fontAwesome;_x000D_
  content: "\f067\00a0";_x000D_
}_x000D_
_x000D_
button.btn.edit::before {_x000D_
  font-family: fontAwesome;_x000D_
  content: "\f044\00a0";_x000D_
}_x000D_
_x000D_
button.btn.save::before {_x000D_
  font-family: fontAwesome;_x000D_
  content: "\f00c\00a0";_x000D_
}_x000D_
_x000D_
button.btn.cancel::before {_x000D_
  font-family: fontAwesome;_x000D_
  content: "\f00d\00a0";_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>_x000D_
<!--FA unicodes here: http://astronautweb.co/snippet/font-awesome/-->_x000D_
<h4>Buttons with text</h4>_x000D_
<button class="btn cancel btn-default">Close</button>_x000D_
<button class="btn add btn-primary">Add</button>_x000D_
<button class="btn add btn-success">Insert</button>_x000D_
<button class="btn save btn-primary">Save</button>_x000D_
<button class="btn save btn-warning">Submit Changes</button>_x000D_
<button class="btn cancel btn-link">Delete</button>_x000D_
<button class="btn edit btn-info">Edit</button>_x000D_
<button class="btn edit btn-danger">Modify</button>_x000D_
_x000D_
<br/>_x000D_
<br/>_x000D_
<h4>Buttons without text</h4>_x000D_
<button class="btn edit btn-primary" />_x000D_
<button class="btn cancel btn-danger" />_x000D_
<button class="btn add btn-info" />_x000D_
<button class="btn save btn-success" />_x000D_
<button class="btn edit btn-link"/>_x000D_
<button class="btn cancel btn-link"/>
_x000D_
_x000D_
_x000D_

Fiddle here.

How to play YouTube video in my Android application?

You may use iframe as described in https://developers.google.com/youtube/iframe_api_reference

I am not following the google advises exactly but this is the code I am using and it is working fine

public class CWebVideoView {

    private String url;
    private Context context;
    private WebView webview;
    private static final String HTML_TEMPLATE = "webvideo.html";

    public CWebVideoView(Context context, WebView webview) {
        this.webview = webview;
        this.context = context;
        webview.setBackgroundColor(0);
        webview.getSettings().setJavaScriptEnabled(true);
    }

    public void load(String url){
        this.url = url;
        String data = readFromfile(HTML_TEMPLATE, context);
        data = data.replace("%1", url);
        webview.loadData(data, "text/html", "UTF-8");
    }

    public String readFromfile(String fileName, Context context) {
        StringBuilder returnString = new StringBuilder();
        InputStream fIn = null;
        InputStreamReader isr = null;
        BufferedReader input = null;
        try {
            fIn = context.getResources().getAssets().open(fileName, Context.MODE_WORLD_READABLE);
            isr = new InputStreamReader(fIn);
            input = new BufferedReader(isr);
            String line = "";
            while ((line = input.readLine()) != null) {
                returnString.append(line);
            }
        } catch (Exception e) {
            e.getMessage();
        } finally {
            try {
                if (isr != null)
                    isr.close();
                if (fIn != null)
                    fIn.close();
                if (input != null)
                    input.close();
            } catch (Exception e2) {
                e2.getMessage();
            }
        }
        return returnString.toString();
    }

    public void reload() {
        if (url!=null){
            load(url);
        }
    }
}

in /assets I have a file called webvideo.html

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <style>
            iframe   { border: 0; position:fixed; width:100%; height:100%; bgcolor="#000000"; }
            body     { margin: 0; bgcolor="#000000"; }
        </style>        
    </head>
    <body>
        <iframe src="%1" frameborder="0" allowfullscreen></iframe>
    </body>
</html>

and now I define a webview inside my main layout

<WebView
    android:id="@+id/video"
    android:visibility="gone"
    android:background="#000000"
    android:layout_centerInParent="true"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

and I use CWebVideoView inside my activity

videoView = (WebView) view.findViewById(R.id.video);
videoView.setVisibility(View.VISIBLE);
cWebVideoView = new CWebVideoView(context, videoView);
cWebVideoView.load(url);

Set bootstrap modal body height by percentage

The scss solution for Bootstrap 4.0

.modal { max-height: 100vh; .modal-dialog { .modal-content { .modal-body { max-height: calc(80vh - 140px); overflow-y: auto; } } } }

Make sure the .modal max-height is 100vh. Then for .modal-body use calc() function to calculate desired height. In above case we want to occupy 80vh of the viewport, reduced by the size of header + footer in pixels. This is around 140px together but you can measure it easily and apply your own custom values. For smaller/taller modal modify 80vh accordingly.

How do I force "git pull" to overwrite local files?

1: Reset to a previous commit

git reset --hard HEAD

2: Delete Untracked Files

git clean -f

3: Pull the commits

git pull

Sources:

No connection string named 'MyEntities' could be found in the application config file

make sure that you make your project (with the DbContext) as startup

on the project right click and select

OR

Add to the project that is set as startup your connection string in the app.config (or web.config)

OR

Call the command like this

Update-Database -Script -ProjectName '<project name>' -StartupProjectName '<project name>' -ConnectionString 'data source=.;initial catalog=<db name>;integrated security=True;MultipleActiveResultSets=True' -ConnectionProviderName 'System.Data.SqlClient'

Then try again

Multiple parameters in a List. How to create without a class?

To add to what other suggested I like the following construct to avoid the annoyance of adding members to keyvaluepair collections.

public class KeyValuePairList<Tkey,TValue> : List<KeyValuePair<Tkey,TValue>>{
    public void Add(Tkey key, TValue value){
        base.Add(new KeyValuePair<Tkey, TValue>(key, value));
    }
}

What this means is that the constructor can be initialized with better syntax::

var myList = new KeyValuePairList<int,string>{{1,"one"},{2,"two"},{3,"three"}};

I personally like the above code over the more verbose examples Unfortunately C# does not really support tuple types natively so this little hack works wonders.

If you find yourself really needing more than 2, I suggest creating abstractions against the tuple type.(although Tuple is a class not a struct like KeyValuePair this is an interesting distinction).

Curiously enough, the initializer list syntax is available on any IEnumerable and it allows you to use any Add method, even those not actually enumerable by your object. It's pretty handy to allow things like adding an object[] member as a params object[] member.

Getting multiple values with scanf()

int a,b,c,d;
if(scanf("%d %d %d %d",&a,&b,&c,&d) == 4) {
   //read the 4 integers
} else {
   puts("Error. Please supply 4 integers");
}

How to use GROUP BY to concatenate strings in SQL Server?

An example would be

In Oracle you can use LISTAGG aggregate function.

Original records

name   type
------------
name1  type1
name2  type2
name2  type3

Sql

SELECT name, LISTAGG(type, '; ') WITHIN GROUP(ORDER BY name)
FROM table
GROUP BY name

Result in

name   type
------------
name1  type1
name2  type2; type3

window.onload vs $(document).ready()

When you say $(document).ready(f), you tell script engine to do the following:

  1. get the object document and push it, since it's not in local scope, it must do a hash table lookup to find where document is, fortunately document is globally bound so it is a single lookup.
  2. find the object $ and select it, since it's not in local scope, it must do a hash table lookup, which may or may not have collisions.
  3. find the object f in global scope, which is another hash table lookup, or push function object and initialize it.
  4. call ready of selected object, which involves another hash table lookup into the selected object to find the method and invoke it.
  5. done.

In the best case, this is 2 hash table lookups, but that's ignoring the heavy work done by jQuery, where $ is the kitchen sink of all possible inputs to jQuery, so another map is likely there to dispatch the query to correct handler.

Alternatively, you could do this:

window.onload = function() {...}

which will

  1. find the object window in global scope, if the JavaScript is optimized, it will know that since window isn't changed, it has already the selected object, so nothing needs to be done.
  2. function object is pushed on the operand stack.
  3. check if onload is a property or not by doing a hash table lookup, since it is, it is called like a function.

In the best case, this costs a single hash table lookup, which is necessary because onload must be fetched.

Ideally, jQuery would compile their queries to strings that can be pasted to do what you wanted jQuery to do but without the runtime dispatching of jQuery. This way you have an option of either

  1. do dynamic dispatch of jquery like we do today.
  2. have jQuery compile your query to pure JavaScript string that can be passed to eval to do what you want.
  3. copy the result of 2 directly into your code, and skip the cost of eval.

How to edit default.aspx on SharePoint site without SharePoint Designer

You can always use Sharepoint Solution Generator to create a project and edit in VS2008.

You can find the Generator along with Sharepoint Developer tools.

What does the "undefined reference to varName" in C mean?

You need to compile and then link the object files like this:

gcc -c a.c  
gcc -c b.c  
gcc a.o b.o -o prog  

Adding multiple columns AFTER a specific column in MySQL

Alternatively:

ALTER TABLE users
ADD COLUMN `status` INT(10) UNSIGNED NOT NULL AFTER `lastname`,
ADD COLUMN `log` VARCHAR(12) NOT NULL AFTER `lastname`,
ADD COLUMN `count` SMALLINT(6) NOT NULL AFTER `lastname`;

Will put them in the order you want while streamlining the AFTER statement.

Change background color of edittext in android

The color you are using is white "#ffffff" is white so try a different one change in the values if you want until you get your need from this link Color Codes and it should go fine

How to check whether a string contains a substring in Ruby

A more succinct idiom than the accepted answer above that's available in Rails (from 3.1.0 and above) is .in?:

my_string = "abcdefg"
if "cde".in? my_string
  puts "'cde' is in the String."
  puts "i.e. String includes 'cde'"
end

I also think it's more readable.

See the in? documentation for more information.

Note again that it's only available in Rails, and not pure Ruby.

Reflection - get attribute name and value on property

I have solved similar problems by writing a Generic Extension Property Attribute Helper:

using System;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;

public static class AttributeHelper
{
    public static TValue GetPropertyAttributeValue<T, TOut, TAttribute, TValue>(
        Expression<Func<T, TOut>> propertyExpression, 
        Func<TAttribute, TValue> valueSelector) 
        where TAttribute : Attribute
    {
        var expression = (MemberExpression) propertyExpression.Body;
        var propertyInfo = (PropertyInfo) expression.Member;
        var attr = propertyInfo.GetCustomAttributes(typeof(TAttribute), true).FirstOrDefault() as TAttribute;
        return attr != null ? valueSelector(attr) : default(TValue);
    }
}

Usage:

var author = AttributeHelper.GetPropertyAttributeValue<Book, string, AuthorAttribute, string>(prop => prop.Name, attr => attr.Author);
// author = "AuthorName"

jquery find closest previous sibling with class

Using prevUntil() will allow us to get a distant sibling without having to get all. I had a particularly long set that was too CPU intensive using prevAll().

var category = $('li.current_sub').prev('li.par_cat');
if (category.length == 0){
  category = $('li.current_sub').prevUntil('li.par_cat').last().prev();
}
category.show();

This gets the first preceding sibling if it matches, otherwise it gets the sibling preceding the one that matches, so we just back up one more with prev() to get the desired element.

Lombok added but getters and setters not recognized in Intellij IDEA

I had both the Lombok plugin installed and Annotation Processing enabled within IntelliJ and my syntax highlighting still wasn't working properly. This could have been due to the 2017 to 2018 IDEA upgrade. I was getting warnings "access exceeds rights" on private fields within classes I had used @Getter and @Setter on.

I had to uninstall the Lombok plugin, restart IntelliJ, then reinstall the plugin, and restart IntelliJ once more.

Everything is working good now.

Calculating and printing the nth prime number

You are trying to do too much in the main method. You need to break this up into more manageable parts. Write a method boolean isPrime(int n) that returns true if a number is prime, and false otherwise. Then modify the main method to use isPrime.

How to count rows with SELECT COUNT(*) with SQLAlchemy?

If you are using the SQL Expression Style approach there is another way to construct the count statement if you already have your table object.

Preparations to get the table object. There are also different ways.

import sqlalchemy

database_engine = sqlalchemy.create_engine("connection string")

# Populate existing database via reflection into sqlalchemy objects
database_metadata = sqlalchemy.MetaData()
database_metadata.reflect(bind=database_engine)

table_object = database_metadata.tables.get("table_name") # This is just for illustration how to get the table_object                    

Issuing the count query on the table_object

query = table_object.count()
# This will produce something like, where id is a primary key column in "table_name" automatically selected by sqlalchemy
# 'SELECT count(table_name.id) AS tbl_row_count FROM table_name'

count_result = database_engine.scalar(query)

TypeScript: Creating an empty typed container array

Okay you got the syntax wrong here, correct way to do this is:

var arr: Criminal[] = [];

I'm assuming you are using var so that means declaring it somewhere inside the func(),my suggestion would be use let instead of var.

If declaring it as c class property usse acces modifiers like private, public, protected.

How to set HttpResponse timeout for Android in Java

HttpParams httpParameters = new BasicHttpParams();
            HttpProtocolParams.setVersion(httpParameters, HttpVersion.HTTP_1_1);
            HttpProtocolParams.setContentCharset(httpParameters,
                    HTTP.DEFAULT_CONTENT_CHARSET);
            HttpProtocolParams.setUseExpectContinue(httpParameters, true);

            // Set the timeout in milliseconds until a connection is
            // established.
            // The default value is zero, that means the timeout is not used.
            int timeoutConnection = 35 * 1000;
            HttpConnectionParams.setConnectionTimeout(httpParameters,
                    timeoutConnection);
            // Set the default socket timeout (SO_TIMEOUT)
            // in milliseconds which is the timeout for waiting for data.
            int timeoutSocket = 30 * 1000;
            HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);

How to extract text from a string using sed?

Try this instead:

echo "This is 02G05 a test string 20-Jul-2012" | sed 's/.* \([0-9]\+G[0-9]\+\) .*/\1/'

But note, if there is two pattern on one line, it will prints the 2nd.

How to generate a random integer number from within a range

All the answers so far are mathematically wrong. Returning rand() % N does not uniformly give a number in the range [0, N) unless N divides the length of the interval into which rand() returns (i.e. is a power of 2). Furthermore, one has no idea whether the moduli of rand() are independent: it's possible that they go 0, 1, 2, ..., which is uniform but not very random. The only assumption it seems reasonable to make is that rand() puts out a Poisson distribution: any two nonoverlapping subintervals of the same size are equally likely and independent. For a finite set of values, this implies a uniform distribution and also ensures that the values of rand() are nicely scattered.

This means that the only correct way of changing the range of rand() is to divide it into boxes; for example, if RAND_MAX == 11 and you want a range of 1..6, you should assign {0,1} to 1, {2,3} to 2, and so on. These are disjoint, equally-sized intervals and thus are uniformly and independently distributed.

The suggestion to use floating-point division is mathematically plausible but suffers from rounding issues in principle. Perhaps double is high-enough precision to make it work; perhaps not. I don't know and I don't want to have to figure it out; in any case, the answer is system-dependent.

The correct way is to use integer arithmetic. That is, you want something like the following:

#include <stdlib.h> // For random(), RAND_MAX

// Assumes 0 <= max <= RAND_MAX
// Returns in the closed interval [0, max]
long random_at_most(long max) {
  unsigned long
    // max <= RAND_MAX < ULONG_MAX, so this is okay.
    num_bins = (unsigned long) max + 1,
    num_rand = (unsigned long) RAND_MAX + 1,
    bin_size = num_rand / num_bins,
    defect   = num_rand % num_bins;

  long x;
  do {
   x = random();
  }
  // This is carefully written not to overflow
  while (num_rand - defect <= (unsigned long)x);

  // Truncated division is intentional
  return x/bin_size;
}

The loop is necessary to get a perfectly uniform distribution. For example, if you are given random numbers from 0 to 2 and you want only ones from 0 to 1, you just keep pulling until you don't get a 2; it's not hard to check that this gives 0 or 1 with equal probability. This method is also described in the link that nos gave in their answer, though coded differently. I'm using random() rather than rand() as it has a better distribution (as noted by the man page for rand()).

If you want to get random values outside the default range [0, RAND_MAX], then you have to do something tricky. Perhaps the most expedient is to define a function random_extended() that pulls n bits (using random_at_most()) and returns in [0, 2**n), and then apply random_at_most() with random_extended() in place of random() (and 2**n - 1 in place of RAND_MAX) to pull a random value less than 2**n, assuming you have a numerical type that can hold such a value. Finally, of course, you can get values in [min, max] using min + random_at_most(max - min), including negative values.

Running bash script from within python

Adding an answer because I was directed here after asking how to run a bash script from python. You receive an error OSError: [Errno 2] file not found if your script takes in parameters. Lets say for instance your script took in a sleep time parameter: subprocess.call("sleep.sh 10") will not work, you must pass it as an array: subprocess.call(["sleep.sh", 10])

String comparison using '==' vs. 'strcmp()'

strcmp() and === are both case sensitive but === is much faster

sample code: http://snipplr.com/view/758/

Define: What is a HashSet?

From application perspective, if one needs only to avoid duplicates then HashSet is what you are looking for since it's Lookup, Insert and Remove complexities are O(1) - constant. What this means it does not matter how many elements HashSet has it will take same amount of time to check if there's such element or not, plus since you are inserting elements at O(1) too it makes it perfect for this sort of thing.

What Does 'zoom' do in CSS?

As Joshua M pointed out, the zoom function isn't supported only in Firefox, but you can simply fix this as shown:

div.zoom {
  zoom: 2; /* all browsers */
 -moz-transform: scale(2);  /* Firefox */
}

Using jQuery Fancybox or Lightbox to display a contact form

you'll probably want to look into jquery-ui dialog. it's highly customizable and can be made to work exactly like lightbox/fancybox and supports everything you would need for a contact form from a regular link.

there is even an example with a form.

how to make a specific text on TextView BOLD

As wtsang02 said, using HTML is an expensive overhead. Just use the native solution. If you don't have to modify the string, just use SpannableString, not SpannableStringBuilder.

String boldText = "id";
String normalText = "name";
SpannableString str = new SpannableString(boldText + normalText);
str.setSpan(new StyleSpan(Typeface.BOLD), 0, boldText.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
textView.setText(str);

Capture keyboardinterrupt in Python without try-except

Yes, you can install an interrupt handler using the module signal, and wait forever using a threading.Event:

import signal
import sys
import time
import threading

def signal_handler(signal, frame):
    print('You pressed Ctrl+C!')
    sys.exit(0)

signal.signal(signal.SIGINT, signal_handler)
print('Press Ctrl+C')
forever = threading.Event()
forever.wait()

Set custom HTML5 required field validation message

Just need to get the element and use the method setCustomValidity.

Example

var foo = document.getElementById('foo');
foo.setCustomValidity(' An error occurred');

'printf' with leading zeros in C

Your format specifier is incorrect. From the printf() man page on my machine:

0 A zero '0' character indicating that zero-padding should be used rather than blank-padding. A '-' overrides a '0' if both are used;

Field Width: An optional digit string specifying a field width; if the output string has fewer characters than the field width it will be blank-padded on the left (or right, if the left-adjustment indicator has been given) to make up the field width (note that a leading zero is a flag, but an embedded zero is part of a field width);

Precision: An optional period, '.', followed by an optional digit string giving a precision which specifies the number of digits to appear after the decimal point, for e and f formats, or the maximum number of characters to be printed from a string; if the digit string is missing, the precision is treated as zero;

For your case, your format would be %09.3f:

#include <stdio.h>

int main(int argc, char **argv)
{
  printf("%09.3f\n", 4917.24);
  return 0;
}

Output:

$ make testapp
cc     testapp.c   -o testapp
$ ./testapp 
04917.240

Note that this answer is conditional on your embedded system having a printf() implementation that is standard-compliant for these details - many embedded environments do not have such an implementation.

Go test string contains substring

To compare, there are more options:

import (
    "fmt"
    "regexp"
    "strings"
)

const (
    str    = "something"
    substr = "some"
)

// 1. Contains
res := strings.Contains(str, substr)
fmt.Println(res) // true

// 2. Index: check the index of the first instance of substr in str, or -1 if substr is not present
i := strings.Index(str, substr)
fmt.Println(i) // 0

// 3. Split by substr and check len of the slice, or length is 1 if substr is not present
ss := strings.Split(str, substr)
fmt.Println(len(ss)) // 2

// 4. Check number of non-overlapping instances of substr in str
c := strings.Count(str, substr)
fmt.Println(c) // 1

// 5. RegExp
matched, _ := regexp.MatchString(substr, str)
fmt.Println(matched) // true

// 6. Compiled RegExp
re = regexp.MustCompile(substr)
res = re.MatchString(str)
fmt.Println(res) // true

Benchmarks: Contains internally calls Index, so the speed is almost the same (btw Go 1.11.5 showed a bit bigger difference than on Go 1.14.3).

BenchmarkStringsContains-4              100000000               10.5 ns/op             0 B/op          0 allocs/op
BenchmarkStringsIndex-4                 117090943               10.1 ns/op             0 B/op          0 allocs/op
BenchmarkStringsSplit-4                  6958126               152 ns/op              32 B/op          1 allocs/op
BenchmarkStringsCount-4                 42397729                29.1 ns/op             0 B/op          0 allocs/op
BenchmarkStringsRegExp-4                  461696              2467 ns/op            1326 B/op         16 allocs/op
BenchmarkStringsRegExpCompiled-4         7109509               168 ns/op               0 B/op          0 allocs/op

How to check if function exists in JavaScript?

To illustrate the preceding answers, here a quick JSFiddle snippet :

_x000D_
_x000D_
function test () {_x000D_
console.log()_x000D_
_x000D_
}_x000D_
_x000D_
console.log(typeof test) // >> "function"_x000D_
_x000D_
// implicit test, in javascript if an entity exist it returns implcitly true unless the element value is false as :_x000D_
// var test = false_x000D_
if(test){ console.log(true)}_x000D_
else{console.log(false)}_x000D_
_x000D_
// test by the typeof method_x000D_
if( typeof test === "function"){ console.log(true)}_x000D_
else{console.log(false)}_x000D_
_x000D_
_x000D_
// confirm that the test is effective : _x000D_
// - entity with false value_x000D_
var test2 = false_x000D_
if(test2){ console.log(true)}_x000D_
else{console.log(false)}_x000D_
_x000D_
// confirm that the test is effective :_x000D_
// - typeof entity_x000D_
if( typeof test ==="foo"){ console.log(true)}_x000D_
else{console.log(false)}_x000D_
_x000D_
/* Expected :_x000D_
function_x000D_
true _x000D_
true _x000D_
false_x000D_
false_x000D_
*/
_x000D_
_x000D_
_x000D_

WPF Button with Image

Another way to Stretch image to full button. Can try the below code.

<Grid.Resources>
  <ImageBrush x:Key="AddButtonImageBrush" ImageSource="/Demoapp;component/Resources/AddButton.png" Stretch="UniformToFill"/>
</Grid.Resources>

<Button Content="Load Inventory 1" Background="{StaticResource AddButtonImageBrush}"/> 

Referred from Here

Also it might helps other. I posted the same with MouseOver Option here.

Change bootstrap datepicker date format on select

  $(function () {
    $('.datetimepicker').datetimepicker(
      {
        format: 'Y-m-d h:m:s'
     }
    );
 });`

How do you modify the web.config appSettings at runtime?

Try This:

using System;
using System.Configuration;
using System.Web.Configuration;

namespace SampleApplication.WebConfig
{
    public partial class webConfigFile : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            //Helps to open the Root level web.config file.
            Configuration webConfigApp = WebConfigurationManager.OpenWebConfiguration("~");
            //Modifying the AppKey from AppValue to AppValue1
            webConfigApp.AppSettings.Settings["ConnectionString"].Value = "ConnectionString";
            //Save the Modified settings of AppSettings.
            webConfigApp.Save();
        }
    }
}

How SID is different from Service name in Oracle tnsnames.ora

Please see: http://www.sap-img.com/oracle-database/finding-oracle-sid-of-a-database.htm

What is the difference between Oracle SIDs and Oracle SERVICE NAMES. One config tool looks for SERVICE NAME and then the next looks for SIDs! What's going on?!

Oracle SID is the unique name that uniquely identifies your instance/database where as Service name is the TNS alias that you give when you remotely connect to your database and this Service name is recorded in Tnsnames.ora file on your clients and it can be the same as SID and you can also give it any other name you want.

SERVICE_NAME is the new feature from oracle 8i onwards in which database can register itself with listener. If database is registered with listener in this way then you can use SERVICE_NAME parameter in tnsnames.ora otherwise - use SID in tnsnames.ora.

Also if you have OPS (RAC) you will have different SERVICE_NAME for each instance.

SERVICE_NAMES specifies one or more names for the database service to which this instance connects. You can specify multiple services names in order to distinguish among different uses of the same database. For example:

SERVICE_NAMES = sales.acme.com, widgetsales.acme.com

You can also use service names to identify a single service that is available from two different databases through the use of replication.

In an Oracle Parallel Server environment, you must set this parameter for every instance.

In short: SID = the unique name of your DB instance, ServiceName = the alias used when connecting

Thymeleaf: Concatenation - Could not parse as expression


We can concat Like this :


<h5 th:text ="${currentItem.first_name}+ ' ' + ${currentItem.last_name}"></h5>

How to replace case-insensitive literal substrings in Java

If you don't care about case, then you perhaps it doesn't matter if it returns all upcase:

target.toUpperCase().replace("FOO", "");

Backporting Python 3 open(encoding="utf-8") to Python 2

If you are using six, you can try this, by which utilizing the latest Python 3 API and can run in both Python 2/3:

import six

if six.PY2:
    # FileNotFoundError is only available since Python 3.3
    FileNotFoundError = IOError
    from io import open

fname = 'index.rst'
try:
    with open(fname, "rt", encoding="utf-8") as f:
        pass
        # do_something_with_f ...
except FileNotFoundError:
    print('Oops.')

And, Python 2 support abandon is just deleting everything related to six.

jQuery trigger event when click outside the element

try these..

$(document).click(function(evt) {
    var target = evt.target.className;
    var inside = $(".menuWraper");
    //alert($(target).html());
    if ($.trim(target) != '') {
        if ($("." + target) != inside) {
            alert("bleep");
        }
    }
});

Getting a File's MD5 Checksum in Java

Standard Java Runtime Environment way:

public String checksum(File file) {
  try {
    InputStream fin = new FileInputStream(file);
    java.security.MessageDigest md5er =
        MessageDigest.getInstance("MD5");
    byte[] buffer = new byte[1024];
    int read;
    do {
      read = fin.read(buffer);
      if (read > 0)
        md5er.update(buffer, 0, read);
    } while (read != -1);
    fin.close();
    byte[] digest = md5er.digest();
    if (digest == null)
      return null;
    String strDigest = "0x";
    for (int i = 0; i < digest.length; i++) {
      strDigest += Integer.toString((digest[i] & 0xff) 
                + 0x100, 16).substring(1).toUpperCase();
    }
    return strDigest;
  } catch (Exception e) {
    return null;
  }
}

The result is equal of linux md5sum utility.

Easy way to write contents of a Java InputStream to an OutputStream

I think this will work, but make sure to test it... minor "improvement", but it might be a bit of a cost at readability.

byte[] buffer = new byte[1024];
int len;
while ((len = in.read(buffer)) != -1) {
    out.write(buffer, 0, len);
}

InsecurePlatformWarning: A true SSLContext object is not available. This prevents urllib3 from configuring SSL appropriately

The docs give a fair indicator of what's required., however requests allow us to skip a few steps:

You only need to install the security package extras (thanks @admdrew for pointing it out)

$ pip install requests[security]

or, install them directly:

$ pip install pyopenssl ndg-httpsclient pyasn1

Requests will then automatically inject pyopenssl into urllib3


If you're on ubuntu, you may run into trouble installing pyopenssl, you'll need these dependencies:

$ apt-get install libffi-dev libssl-dev

Python Image Library fails with message "decoder JPEG not available" - PIL

libjpeg-dev is required to be able to process jpegs with pillow (or PIL), so you need to install it and then recompile pillow. It also seems that libjpeg8-dev is needed on Ubuntu 14.04

If you're still using PIL then you should really be using pillow these days though, so first pip uninstall PIL before following these instructions to switch, or if you have a good reason for sticking with PIL then replace "pillow" with "PIL" in the below).

On Ubuntu:

# install libjpeg-dev with apt
sudo apt-get install libjpeg-dev
# if you're on Ubuntu 14.04, also install this
sudo apt-get install libjpeg8-dev

# reinstall pillow
pip install --no-cache-dir -I pillow

If that doesn't work, try one of the below, depending on whether you are on 64bit or 32bit Ubuntu.

For Ubuntu x64:

sudo ln -s /usr/lib/x86_64-linux-gnu/libjpeg.so /usr/lib
sudo ln -s /usr/lib/x86_64-linux-gnu/libfreetype.so /usr/lib
sudo ln -s /usr/lib/x86_64-linux-gnu/libz.so /usr/lib

Or for Ubuntu 32bit:

sudo ln -s /usr/lib/i386-linux-gnu/libjpeg.so /usr/lib/
sudo ln -s /usr/lib/i386-linux-gnu/libfreetype.so.6 /usr/lib/
sudo ln -s /usr/lib/i386-linux-gnu/libz.so /usr/lib/

Then reinstall pillow:

pip install --no-cache-dir -I pillow

(Edits to include feedback from comments. Thanks Charles Offenbacher for pointing out this differs for 32bit, and t-mart for suggesting use of --no-cache-dir).

Is it possible to use vh minus pixels in a CSS calc()?

It does work indeed. Issue was with my less compiler. It was compiled in to:

.container {
  min-height: calc(-51vh);
}

Fixed with the following code in less file:

.container {
  min-height: calc(~"100vh - 150px");
}

Thanks to this link: Less Aggressive Compilation with CSS3 calc

SQL Server find and replace specific word in all rows of specific column

UPDATE tblKit
SET number = REPLACE(number, 'KIT', 'CH')
WHERE number like 'KIT%'

or simply this if you are sure that you have no values like this CKIT002

UPDATE tblKit
SET number = REPLACE(number, 'KIT', 'CH')

Singletons vs. Application Context in Android?

From: Developer > reference - Application

There is normally no need to subclass Application. In most situation, static singletons can provide the same functionality in a more modular way. If your singleton needs a global context (for example to register broadcast receivers), the function to retrieve it can be given a Context which internally uses Context.getApplicationContext() when first constructing the singleton.

PHP - Notice: Undefined index:

You're getting errors because you're attempting to read post variables that haven't been set, they only get set on form submission. Wrap your php code at the bottom in an

if ($_SERVER['REQUEST_METHOD'] === 'POST') { ... }

Also, your code is ripe for SQL injection. At the very least use mysql_real_escape_string on the post vars before using them in SQL queries. mysql_real_escape_string is not good enough for a production site, but should score you extra points in class.

With arrays, why is it the case that a[5] == 5[a]?

For pointers in C, we have

a[5] == *(a + 5)

and also

5[a] == *(5 + a)

Hence it is true that a[5] == 5[a].

How to change theme for AlertDialog

I"m not sure how Arve's solution would work in a custom Dialog with builder where the view is inflated via a LayoutInflator.

The solution should be to insert the the ContextThemeWrapper in the inflator through cloneInContext():

View sensorView = LayoutInflater.from(context).cloneInContext(
     new ContextThemeWrapper(context, R.style.AppTheme_DialogLight)
).inflate(R.layout.dialog_fingerprint, null);

using jquery $.ajax to call a PHP function

You may use my library that does that automatically, I've been improving it for the past 2 years http://phery-php-ajax.net

Phery::instance()->set(array(
   'phpfunction' => function($data){
      /* Do your thing */
      return PheryResponse::factory(); // do your dom manipulation, return JSON, etc
   }
))->process();

The javascript would be simple as

phery.remote('phpfunction');

You can pass all the dynamic javascript part to the server, with a query builder like chainable interface, and you may pass any type of data back to the PHP. For example, some functions that would take too much space in the javascript side, could be called in the server using this (in this example, mcrypt, that in javascript would be almost impossible to accomplish):

function mcrypt(variable, content, key){
  phery.remote('mcrypt_encrypt', {'var': variable, 'content': content, 'key':key || false});
}

//would use it like (you may keep the key on the server, safer, unless it's encrypted for the user)
window.variable = '';
mcrypt('variable', 'This must be encoded and put inside variable', 'my key');

and in the server

Phery::instance()->set(array(
  'mcrypt_encrypt' => function($data){
     $r = new PheryResponse;

     $iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB);
     $iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
     $encrypted = mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $data['key'] ? : 'my key', $data['content'], MCRYPT_MODE_ECB, $iv);
     return $r->set_var($data['variable'], $encrypted);
     // or call a callback with the data, $r->call($data['callback'], $encrypted);
  }
))->process();

Now the variable will have the encrypted data.

Extension methods must be defined in a non-generic static class

Try changing

public class LinqHelper

to

 public static class LinqHelper

Postgresql: password authentication failed for user "postgres"

If you are trying to login postgres shell as postgres user, then you can use following commands.

switch to postgres user

# su - postgres

login to psql

# psql

Hope that helps

LINQ Contains Case Insensitive

Using C# 6.0 (which allows expression bodied functions and null propagation), for LINQ to Objects, it can be done in a single line like this (also checking for null):

public static bool ContainsInsensitive(this string str, string value) => str?.IndexOf(value, StringComparison.OrdinalIgnoreCase) >= 0;

How to Insert Double or Single Quotes

Assuming your data is in column A, add a formula to column B

="'" & A1 & "'" 

and copy the formula down. If you now save to CSV, you should get the quoted values. If you need to keep it in Excel format, copy column B then paste value to get rid of the formula.

Disable Tensorflow debugging information

Usual python3 log manager works for me with tensorflow==1.11.0:

import logging
logging.getLogger('tensorflow').setLevel(logging.INFO)

java.sql.SQLException: Fail to convert to internal representation

I had the same problem and this is my solution. I had the following code:

se.GiftDescription = rs.getString(1);
se.GiftAmount = rs.getInt(2);

And I changed it to:

se.GiftDescription = rs.getString("DESCRIPTION");
se.GiftAmount = rs.getInt("AMOUNT");

And the problem was, after I restarted my PC, the column positions changed. That's why I got this error.

iPhone X / 8 / 8 Plus CSS media queries

iPhone X

@media only screen 
    and (device-width : 375px) 
    and (device-height : 812px) 
    and (-webkit-device-pixel-ratio : 3) { }

iPhone 8

@media only screen 
    and (device-width : 375px) 
    and (device-height : 667px) 
    and (-webkit-device-pixel-ratio : 2) { }

iPhone 8 Plus

@media only screen 
    and (device-width : 414px) 
    and (device-height : 736px) 
    and (-webkit-device-pixel-ratio : 3) { }


iPhone 6+/6s+/7+/8+ share the same sizes, while the iPhone 7/8 also do.


Looking for a specific orientation ?

Portrait

Add the following rule:

    and (orientation : portrait) 

Landscape

Add the following rule:

    and (orientation : landscape) 



References:

How to insert text into the textarea at the current cursor position?

 /**
 * Usage "foo baz".insertInside(4, 0, "bar ") ==> "foo bar baz"
 */
String.prototype.insertInside = function(start, delCount, newSubStr) {
    return this.slice(0, start) + newSubStr + this.slice(start + Math.abs(delCount));
};


 $('textarea').bind("keydown keypress", function (event) {
   var val = $(this).val();
   var indexOf = $(this).prop('selectionStart');
   if(event.which === 13) {
       val = val.insertInside(indexOf, 0,  "<br>\n");
       $(this).val(val);
       $(this).focus();
    }
})

is there a 'block until condition becomes true' function in java?

Similar to EboMike's answer you can use a mechanism similar to wait/notify/notifyAll but geared up for using a Lock.

For example,

public void doSomething() throws InterruptedException {
    lock.lock();
    try {
        condition.await(); // releases lock and waits until doSomethingElse is called
    } finally {
        lock.unlock();
    }
}

public void doSomethingElse() {
    lock.lock();
    try {
        condition.signal();
    } finally {
        lock.unlock();
    }
}

Where you'll wait for some condition which is notified by another thread (in this case calling doSomethingElse), at that point, the first thread will continue...

Using Locks over intrinsic synchronisation has lots of advantages but I just prefer having an explicit Condition object to represent the condition (you can have more than one which is a nice touch for things like producer-consumer).

Also, I can't help but notice how you deal with the interrupted exception in your example. You probably shouldn't consume the exception like this, instead reset the interrupt status flag using Thread.currentThread().interrupt.

This because if the exception is thrown, the interrupt status flag will have been reset (it's saying "I no longer remember being interrupted, I won't be able to tell anyone else that I have been if they ask") and another process may rely on this question. The example being that something else has implemented an interruption policy based on this... phew. A further example might be that your interruption policy, rather that while(true) might have been implemented as while(!Thread.currentThread().isInterrupted() (which will also make your code be more... socially considerate).

So, in summary, using Condition is rougly equivalent to using wait/notify/notifyAll when you want to use a Lock, logging is evil and swallowing InterruptedException is naughty ;)

HTTP Error 401.2 - Unauthorized You are not authorized to view this page due to invalid authentication headers

Old question but anyway !

Same thing happen to me this morning, everything was working fine for weeks before...... yes guess what ... I change my windows PC user account password yesterday night !!!!! (how stupid was I !!!)

So easy fix : IIS -> authentication -> Anonymous authentication -> edit and set the user and new PASSWORD !!!!!

How to use Git for Unity3D source control?

We now have seamless integration to unity with Github to Unity extension... https://unity.github.com/

The new GitHub for Unity extension brings the GitHub workflow and more to Unity, providing support for large files with Git LFS and file locking.

At the time of writing the project is in alpha, but is still usable for personal projects.

How do I get the last word in each line with bash

Another way of doing this in plain bash is making use of the rev command like this:

cat file | rev | cut -d" " -f1 | rev | tr -d "." | tr "\n" ","

Basically, you reverse the lines of the file, then split them with cut using space as the delimiter, take the first field that cut produces and then you reverse the token again, use tr -d to delete unwanted chars and tr again to replace newline chars with ,

Also, you can avoid the first cat by doing:

rev < file | cut -d" " -f1 | rev | tr -d "." | tr "\n" ","

CSS two div width 50% in one line with line break in file

basically inline-table is for element table, I guess what you really need here is inline-block, if you have to use inline-table anyway, try it this way:

<div style="width:50%; display:inline-table;">A</div><!--
--><div style="width:50%; display:inline-table;">B</div>

MySql ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: NO)

If you need to skip the password prompt for some reason, you can input the password in the command (Dangerous)

mysql -u root --password=secret

How to make a JSON call to a url?

A standard http GET request should do it. Then you can use JSON.parse() to make it into a json object.

function Get(yourUrl){
    var Httpreq = new XMLHttpRequest(); // a new request
    Httpreq.open("GET",yourUrl,false);
    Httpreq.send(null);
    return Httpreq.responseText;          
}

then

var json_obj = JSON.parse(Get(yourUrl));
console.log("this is the author name: "+json_obj.author_name);

that's basically it

Keep getting No 'Access-Control-Allow-Origin' error with XMLHttpRequest

Your server's response allows the request to include three specific non-simple headers:

Access-Control-Allow-Headers:origin, x-requested-with, content-type

but your request has a header not allowed by the server's response:

Access-Control-Request-Headers:access-control-allow-origin, content-type

All non-simple headers sent in a CORS request must be explicitly allowed by the Access-Control-Allow-Headers response header. The unnecessary Access-Control-Allow-Origin header sent in your request is not allowed by the server's CORS response. This is exactly what the "...not allowed by Access-Control-Allow-Headers" error message was trying to tell you.

There is no reason for the request to have this header: it does nothing, because Access-Control-Allow-Origin is a response header, not a request header.

Solution: Remove the setRequestHeader call that adds a Access-Control-Allow-Origin header to your request.

How to secure RESTful web services?

There's another, very secure method. It's client certificates. Know how servers present an SSL Cert when you contact them on https? Well servers can request a cert from a client so they know the client is who they say they are. Clients generate certs and give them to you over a secure channel (like coming into your office with a USB key - preferably a non-trojaned USB key).

You load the public key of the cert client certificates (and their signer's certificate(s), if necessary) into your web server, and the web server won't accept connections from anyone except the people who have the corresponding private keys for the certs it knows about. It runs on the HTTPS layer, so you may even be able to completely skip application-level authentication like OAuth (depending on your requirements). You can abstract a layer away and create a local Certificate Authority and sign Cert Requests from clients, allowing you to skip the 'make them come into the office' and 'load certs onto the server' steps.

Pain the neck? Absolutely. Good for everything? Nope. Very secure? Yup.

It does rely on clients keeping their certificates safe however (they can't post their private keys online), and it's usually used when you sell a service to clients rather then letting anyone register and connect.

Anyway, it may not be the solution you're looking for (it probably isn't to be honest), but it's another option.

What is the difference between find(), findOrFail(), first(), firstOrFail(), get(), list(), toArray()

  1. find($id) takes an id and returns a single model. If no matching model exist, it returns null.

  2. findOrFail($id) takes an id and returns a single model. If no matching model exist, it throws an error1.

  3. first() returns the first record found in the database. If no matching model exist, it returns null.

  4. firstOrFail() returns the first record found in the database. If no matching model exist, it throws an error1.

  5. get() returns a collection of models matching the query.

  6. pluck($column) returns a collection of just the values in the given column. In previous versions of Laravel this method was called lists.

  7. toArray() converts the model/collection into a simple PHP array.


Note: a collection is a beefed up array. It functions similarly to an array, but has a lot of added functionality, as you can see in the docs.

Unfortunately, PHP doesn't let you use a collection object everywhere you can use an array. For example, using a collection in a foreach loop is ok, put passing it to array_map is not. Similarly, if you type-hint an argument as array, PHP won't let you pass it a collection. Starting in PHP 7.1, there is the iterable typehint, which can be used to accept both arrays and collections.

If you ever want to get a plain array from a collection, call its all() method.


1 The error thrown by the findOrFail and firstOrFail methods is a ModelNotFoundException. If you don't catch this exception yourself, Laravel will respond with a 404, which is what you want most of the time.

What's "this" in JavaScript onclick?

The value of event handler attributes such as onclick should just be JavaScript, without any "javascript:" prefix. The javascript: pseudo-protocol is used in a URL, for example:

<a href="javascript:func(this)">here</a>

You should use the onclick="func(this)" form in preference to this though. Also note that in my example above using the javascript: pseudo-protocol "this" will refer to the window object rather than the <a> element.

What is a correct MIME type for .docx, .pptx, etc.?

In case anyone wants the answer of Dirk Vollmar in a C# switch statement:

case "doc": return "application/msword";
case "dot": return "application/msword";
case "docx": return "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
case "dotx": return "application/vnd.openxmlformats-officedocument.wordprocessingml.template";
case "docm": return "application/vnd.ms-word.document.macroEnabled.12";
case "dotm": return "application/vnd.ms-word.template.macroEnabled.12";
case "xls": return "application/vnd.ms-excel";
case "xlt": return "application/vnd.ms-excel";
case "xla": return "application/vnd.ms-excel";
case "xlsx": return "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
case "xltx": return "application/vnd.openxmlformats-officedocument.spreadsheetml.template";
case "xlsm": return "application/vnd.ms-excel.sheet.macroEnabled.12";
case "xltm": return "application/vnd.ms-excel.template.macroEnabled.12";
case "xlam": return "application/vnd.ms-excel.addin.macroEnabled.12";
case "xlsb": return "application/vnd.ms-excel.sheet.binary.macroEnabled.12";
case "ppt": return "application/vnd.ms-powerpoint";
case "pot": return "application/vnd.ms-powerpoint";
case "pps": return "application/vnd.ms-powerpoint";
case "ppa": return "application/vnd.ms-powerpoint";
case "pptx": return "application/vnd.openxmlformats-officedocument.presentationml.presentation";
case "potx": return "application/vnd.openxmlformats-officedocument.presentationml.template";
case "ppsx": return "application/vnd.openxmlformats-officedocument.presentationml.slideshow";
case "ppam": return "application/vnd.ms-powerpoint.addin.macroEnabled.12";
case "pptm": return "application/vnd.ms-powerpoint.presentation.macroEnabled.12";
case "potm": return "application/vnd.ms-powerpoint.template.macroEnabled.12";
case "ppsm": return "application/vnd.ms-powerpoint.slideshow.macroEnabled.12";
case "mdb": return "application/vnd.ms-access";

Error type 3 Error: Activity class {} does not exist

My solution is: close the "instant run" of android studio.

"instant run" can be found with the following steps: Preferences -> Build,Execution,Deployment -> Instant Run

and then uncheck the checkbox "Enable Instant Run to hot swap...."

Parse json string using JSON.NET

I did not test the following snippet... hopefully it will point you towards the right direction:

    var jsreader = new JsonTextReader(new StringReader(stringData));
    var json = (JObject)new JsonSerializer().Deserialize(jsreader);
    var tableRows = from p in json["items"]
                 select new
                 {
                     Name = (string)p["Name"],
                     Age = (int)p["Age"],
                     Job = (string)p["Job"]
                 };

HTML <sup /> tag affecting line height, how to make it consistent?

Specially use this on newsletter -

<sup style="font-size:9px; line-height:8px;">&reg;</sup>

ParseError: not well-formed (invalid token) using cElementTree

The only thing that worked for me is I had to add mode and encoding while opening the file like below:

with open(filenames[0], mode='r',encoding='utf-8') as f:
     readFile()

Otherwise it was failing every time with invalid token error if I simply do this:

 f = open(filenames[0], 'r')
 readFile()

Truncating long strings with CSS: feasible yet?

Another solution to the problem could be the following set of CSS rules:

.ellipsis{
 white-space:nowrap;
 overflow:hidden;
}

.ellipsis:after{
  content:'...';
}

The only drawback with the above CSS is that it would add the "..." irrespective of whether the text-overflows the container or not. Still, if you have a case where you have a bunch of elements and are sure that content will overflow, this one would be a simpler set of rules.

My two cents. Hats off to the original technique by Justin Maxwell

How do I prompt for Yes/No/Cancel input in a Linux shell script?

inquire ()  {
  echo  -n "$1 [y/n]? "
  read answer
  finish="-1"
  while [ "$finish" = '-1' ]
  do
    finish="1"
    if [ "$answer" = '' ];
    then
      answer=""
    else
      case $answer in
        y | Y | yes | YES ) answer="y";;
        n | N | no | NO ) answer="n";;
        *) finish="-1";
           echo -n 'Invalid response -- please reenter:';
           read answer;;
       esac
    fi
  done
}

... other stuff

inquire "Install now?"

...

How do I convert a numpy array to (and display) an image?

import numpy as np
from keras.preprocessing.image import array_to_img
img = np.zeros([525,525,3], np.uint8)
b=array_to_img(img)
b

How to read barcodes with the camera on Android?

Here is a sample code: my app uses ZXing Barcode Scanner.

  1. You need these 2 classes: IntentIntegrator and IntentResult

  2. Call scanner (e.g. OnClickListener, OnMenuItemSelected...), "PRODUCT_MODE" - it scans standard 1D barcodes (you can add more).:

    IntentIntegrator.initiateScan(this, 
               "Warning", 
               "ZXing Barcode Scanner is not installed, download?",
               "Yes", "No",
               "PRODUCT_MODE");
    
  3. Get barcode as a result:

    public void onActivityResult(int requestCode, int resultCode, Intent intent) {  
      switch (requestCode) {
      case IntentIntegrator.REQUEST_CODE:
         if (resultCode == Activity.RESULT_OK) {
    
            IntentResult intentResult = 
               IntentIntegrator.parseActivityResult(requestCode, resultCode, intent);
    
            if (intentResult != null) {
    
               String contents = intentResult.getContents();
               String format = intentResult.getFormatName();
    
               this.elemQuery.setText(contents);
               this.resume = false;
               Log.d("SEARCH_EAN", "OK, EAN: " + contents + ", FORMAT: " + format);
            } else {
               Log.e("SEARCH_EAN", "IntentResult je NULL!");
            }
         } else if (resultCode == Activity.RESULT_CANCELED) {
            Log.e("SEARCH_EAN", "CANCEL");
         }
      }
    }
    

contents holds barcode number

Google maps responsive resize

Move your map variable into a scope where the event listener can use it. You are creating the map inside your initialize() function and nothing else can use it when created that way.

var map; //<-- This is now available to both event listeners and the initialize() function
function initialize() {
  var mapOptions = {
   center: new google.maps.LatLng(40.5472,12.282715),
   zoom: 6,
   mapTypeId: google.maps.MapTypeId.ROADMAP
  };
  map = new google.maps.Map(document.getElementById("map-canvas"),
            mapOptions);
}
google.maps.event.addDomListener(window, 'load', initialize);
google.maps.event.addDomListener(window, "resize", function() {
 var center = map.getCenter();
 google.maps.event.trigger(map, "resize");
 map.setCenter(center); 
});

JS: Uncaught TypeError: object is not a function (onclick)

I was able to figure it out by following the answer in this thread: https://stackoverflow.com/a/8968495/1543447

Basically, I renamed all values, function names, and element names to different values so they wouldn't conflict - and it worked!

Git mergetool generates unwanted .orig files

git config --global mergetool.keepBackup false

This should work for Beyond Compare (as mergetool) too

ScrollTo function in AngularJS

What about angular-scroll, it's actively maintained and there is no dependency to jQuery..

How to check the version of GitLab?

If you are using a self-hosted version of GitLab then you may consider running this command.

grep gitlab /opt/gitlab/version-manifest.txt

Read pdf files with php

Not exactly php, but you could exec a program from php to convert the pdf to a temporary html file and then parse the resulting file with php. I've done something similar for a project of mine and this is the program I used:

PdfToHtml

The resulting HTML wraps text elements in < div > tags with absolute position coordinates. It seems like this is exactly what you are trying to do.

How to convert AAR to JAR

The AAR file consists of a JAR file and some resource files (it is basically a standard zip file with a custom file extension). Here are the steps to convert:

  1. Extract the AAR file using standard zip extract (rename it to *.zip to make it easier)
  2. Find the classes.jar file in the extracted files
  3. Rename it as you like and use that jar file in your project

what is the use of "response.setContentType("text/html")" in servlet

You have to tell the browser what you are sending back so that the browser can take appropriate action like launching a PDF viewer if its a PDF that is being received or launching a video player to play video file ,rendering the HTML if the content type is simple html response, save the bytes of the response as a downloaded file, etc.

some common MIME types are text/html,application/pdf,video/quicktime,application/java,image/jpeg,application/jar etc

In your case since you are sending HTML response to client you will have to set the content type as text/html

How to make HTML code inactive with comments

Reason of comments:

  1. Comment out elements temporarily rather than removing them, especially if they've been left unfinished.
  2. Write notes or reminders to yourself inside your actual HTML documents.
  3. Create notes for other scripting languages like JavaScript which requires them

HTML Comments

<!-- Everything is invisible  -->

how to fetch array keys with jQuery?

console.log( Object.keys( {'a':1,'b':2} ) );

What is the best way to delete a value from an array in Perl?

Use splice if you already know the index of the element you want to delete.

Grep works if you are searching.

If you need to do a lot of these, you will get much better performance if you keep your array in sorted order, since you can then do binary search to find the necessary index.

If it makes sense in your context, you may want to consider using a "magic value" for deleted records, rather then deleting them, to save on data movement -- set deleted elements to undef, for example. Naturally, this has its own issues (if you need to know the number of "live" elements, you need to keep track of it separately, etc), but may be worth the trouble depending on your application.

Edit Actually now that I take a second look -- don't use the grep code above. It would be more efficient to find the index of the element you want to delete, then use splice to delete it (the code you have accumulates all the non-matching results..)

my $index = 0;
$index++ until $arr[$index] eq 'foo';
splice(@arr, $index, 1);

That will delete the first occurrence. Deleting all occurrences is very similar, except you will want to get all indexes in one pass:

my @del_indexes = grep { $arr[$_] eq 'foo' } 0..$#arr;

The rest is left as an excercise for the reader -- remember that the array changes as you splice it!

Edit2 John Siracusa correctly pointed out I had a bug in my example.. fixed, sorry about that.

How to print float to n decimal places including trailing 0s?

The cleanest way in modern Python >=3.6, is to use an f-string with string formatting:

>>> var = 1.6
>>> f"{var:.15f}"
'1.600000000000000'

Detecting iOS / Android Operating system

Using the cordova-device-plugin, you can detect

device.platform

will be "Android" for android, and "windows" for windows. Works on device, and when simulating on browser. Here is a toast that will display the device values:

    window.plugins.toast.showLongTop(
    'Cordova:     ' + device.cordova + '\n' +
    'Model:       ' + device.model + '\n' +
    'Platform:    ' + device.platform + '\n' +
    'UUID:        ' + '\n' +
                      device.uuid + '\n' +
    'Version:     ' + device.version + '\n' +
    'Manufacturer ' + device.manufacturer + '\n' +
    'isVirtual    ' + device.isVirtual + '\n' +
    'Serial       ' + device.serial);

jQuery: set selected value of dropdown list?

You need to select jQuery in the dropdown on the left and you have a syntax error because the $(document).ready should end with }); not )}; Check this link.

How can I generate Javadoc comments in Eclipse?

For me the /**<NEWLINE> or Shift-Alt-J (or ?-?-J on a Mac) approach works best.

I dislike seeing Javadoc comments in source code that have been auto-generated and have not been updated with real content. As far as I am concerned, such javadocs are nothing more than a waste of screen space.

IMO, it is much much better to generate the Javadoc comment skeletons one by one as you are about to fill in the details.

System.Data.OracleClient requires Oracle client software version 8.1.7

Update 1: It is possible for different users to have different path. But its not the likely problem here. There is more chance that the user that the iwam user doesn't have permission to the oracle client directory.

Update 0: Its suppose to work. Check for environment variable ( That are needed to find the oracle client and tnsnames.ora ). Also, Maybe you have a 32/64 bit issues. Also, consider using the Oracle Data Provider for .NET ( search for odp.net)

slideToggle JQuery right to left

Try this:

$(this).hide("slide", { direction: "left" }, 1000);

$(this).show("slide", { direction: "left" }, 1000);

How to select some rows with specific rownames from a dataframe?

Assuming that you have a data frame called students, you can select individual rows or columns using the bracket syntax, like this:

  • students[1,2] would select row 1 and column 2, the result here would be a single cell.
  • students[1,] would select all of row 1, students[,2] would select all of column 2.

If you'd like to select multiple rows or columns, use a list of values, like this:

  • students[c(1,3,4),] would select rows 1, 3 and 4,
  • students[c("stu1", "stu2"),] would select rows named stu1 and stu2.

Hope I could help.

align divs to the bottom of their container

You can cheat! Say your div is 20px high, place the div at the top of the next container and set

position: absolute;
top: -20px;

It may not be semantically clean but does scale with responsive designs

Anaconda vs. miniconda

Anaconda or Miniconda?

Choose Anaconda if you:

  1. Are new to conda or Python.

  2. Like the convenience of having Python and over 1,500 scientific packages automatically installed at once.

  3. Have the time and disk space---a few minutes and 3 GB.

  4. Do not want to individually install each of the packages you want to use.

Choose Miniconda if you:

  1. Do not mind installing each of the packages you want to use individually.

  2. Do not have time or disk space to install over 1,500 packages at once.

  3. Want fast access to Python and the conda commands and you wish to sort out the other programs later.

Source

How can a windows service programmatically restart itself?

The better approach may be to utilize the NT Service as a wrapper for your application. When the NT Service is started, your application can start in an "idle" mode waiting for the command to start (or be configured to start automatically).

Think of a car, when it's started it begins in an idle state, waiting for your command to go forward or reverse. This also allows for other benefits, such as better remote administration as you can choose how to expose your application.

Best Practice to Organize Javascript Library & CSS Folder Structure

 root/
   assets/
      lib/-------------------------libraries--------------------
          bootstrap/--------------Libraries can have js/css/images------------
              css/
              js/
              images/  
          jquery/
              js/
          font-awesome/
              css/
              images/
     common/--------------------common section will have application level resources             
          css/
          js/
          img/

 index.html

This is how I organized my application's static resources.

How to quickly drop a user with existing privileges

How about

DROP USER <username>

This is actually an alias for DROP ROLE.

You have to explicity drop any privileges associated with that user, also to move its ownership to other roles (or drop the object).

This is best achieved by

REASSIGN OWNED BY <olduser> TO <newuser>

and

DROP OWNED BY <olduser>

The latter will remove any privileges granted to the user.

See the postgres docs for DROP ROLE and the more detailed description of this.


Addition:

Apparently, trying to drop a user by using the commands mentioned here will only work if you are executing them while being connected to the same database that the original GRANTS were made from, as discussed here:

https://www.postgresql.org/message-id/83894A1821034948BA27FE4DAA47427928F7C29922%40apde03.APD.Satcom.Local

ORA-01017 Invalid Username/Password when connecting to 11g database from 9i client

I had a similar problem recently with Oracle 12c. I created a new user with a lower case password and was able to login fine from the database server but all clients failed with an ORA-01017. The fix turned out to be simple in the end (reset the password to upper case) but took a lot of frustrating effort to get there.

How to get a list of sub-folders and their files, ordered by folder-names

Hej man, why are you using this ?

dir /s/b/o:gn > f.txt (wrong one)

Don't you know what is that 'g' in '/o' ??

Check this out: http://www.computerhope.com/dirhlp.htm or dir /? for dir help

You should be using this instead:

dir /s/b/o:n > f.txt (right one)

How can I perform a reverse string search in Excel without using VBA?

Imagine the string could be reversed. Then it is really easy. Instead of working on the string:

"My little cat" (1)

you work with

"tac elttil yM" (2)

With =LEFT(A1;FIND(" ";A1)-1) in A2 you get "My" with (1) and "tac" with (2), which is reversed "cat", the last word in (1).

There are a few VBAs around to reverse a string. I prefer the public VBA function ReverseString.

Install the above as described. Then with your string in A1, e.g., "My little cat" and this function in A2:

=ReverseString(LEFT(ReverseString(A1);IF(ISERROR(FIND(" ";A1));
  LEN(A1);(FIND(" ";ReverseString(A1))-1))))

you'll see "cat" in A2.

The method above assumes that words are separated by blanks. The IF clause is for cells containing single words = no blanks in cell. Note: TRIM and CLEAN the original string are useful as well. In principle it reverses the whole string from A1 and simply finds the first blank in the reversed string which is next to the last (reversed) word (i.e., "tac "). LEFT picks this word and another string reversal reconstitutes the original order of the word (" cat"). The -1 at the end of the FIND statement removes the blank.

The idea is that it is easy to extract the first(!) word in a string with LEFT and FINDing the first blank. However, for the last(!) word the RIGHT function is the wrong choice when you try to do that because unfortunately FIND does not have a flag for the direction you want to analyse your string.

Therefore the whole string is simply reversed. LEFT and FIND work as normal but the extracted string is reversed. But his is no big deal once you know how to reverse a string. The first ReverseString statement in the formula does this job.

How to use makefiles in Visual Studio?

The Microsoft Program Maintenance Utility (NMAKE.EXE) is a tool that builds projects based on commands contained in a description file.

NMAKE Reference

How can I clear or empty a StringBuilder?

If performance is the main concern then the irony, in my opinion, is the Java constructs to format the text that goes into the buffer, will be far more time consuming on the CPU than the allocation/reallocation/garbage collection ... well, possibly not the GC (garbage collection) depending on how many builders you create and discard.

But simply appending a compound string ("Hello World of " + 6E9 + " earthlings.") to the buffer is likely to make the whole matter inconsequential.

And, really, if an instance of StringBuilder is involved, then the content is complex and/or longer than a simple String str = "Hi"; (never mind that Java probably uses a builder in the background anyway).

Personally, I try not to abuse the GC. So if it's something that's going to be used a lot in a rapid fire scenario - like, say, writing debug output messages - I just assume declare it elsewhere and zero it out for reuse.

class MyLogger {
    StringBuilder strBldr = new StringBuilder(256);

    public void logMsg( String stuff, SomeLogWriterClass log ) {

        // zero out strBldr's internal index count, not every
        // index in strBldr's internal buffer
        strBldr.setLength(0);

        // ... append status level
        strBldr.append("Info");

        // ... append ' ' followed by timestamp
        // assuming getTimestamp() returns a String
        strBldr.append(' ').append(getTimestamp());

        // ... append ':' followed by user message
        strBldr.append(':').append(msg);

        log.write(strBldr.toString());
    }
}

What is the command to truncate a SQL Server log file?

Since the answer for me was buried in the comments. For SQL Server 2012 and beyond, you can use the following:

BACKUP LOG Database TO DISK='NUL:'
DBCC SHRINKFILE (Database_Log, 1)

Convert an image (selected by path) to base64 string

You can use Server.Map path to give relative path and then you can either create image using base64 conversion or you can just add base64 string to image src.

byte[] imageArray = System.IO.File.ReadAllBytes(Server.MapPath("~/Images/Upload_Image.png"));

string base64ImageRepresentation = Convert.ToBase64String(imageArray);

"import datetime" v.s. "from datetime import datetime"

datetime is a module which contains a type that is also called datetime. You appear to want to use both, but you're trying to use the same name to refer to both. The type and the module are two different things and you can't refer to both of them with the name datetime in your program.

If you need to use anything from the module besides the datetime type (as you apparently do), then you need to import the module with import datetime. You can then refer to the "date" type as datetime.date and the datetime type as datetime.datetime.

You could also do this:

from datetime import datetime, date
today_date = date.today()
date_time = datetime.strp(date_time_string, '%Y-%m-%d %H:%M')

Here you import only the names you need (the datetime and date types) and import them directly so you don't need to refer to the module itself at all.

Ultimately you have to decide what names from the module you need to use, and how best to use them. If you are only using one or two things from the module (e.g., just the date and datetime types), it may be okay to import those names directly. If you're using many things, it's probably better to import the module and access the things inside it using dot syntax, to avoid cluttering your global namespace with date-specific names.

Note also that, if you do import the module name itself, you can shorten the name to ease typing:

import datetime as dt
today_date = dt.date.today()
date_time = dt.datetime.strp(date_time_string, '%Y-%m-%d %H:%M')

Get file name from URL

andy's answer redone using split():

Url u= ...;
String[] pathparts= u.getPath().split("\\/");
String filename= pathparts[pathparts.length-1].split("\\.", 1)[0];

Pretty-print a Map in Java

When I have org.json.JSONObject in the classpath, I do:

Map<String, Object> stats = ...;
System.out.println(new JSONObject(stats).toString(2));

(this beautifully indents lists, sets and maps which may be nested)

Git, fatal: The remote end hung up unexpectedly

If using GitHub, in the repo's directory, run this command to set http.postBuffer to what appears to be its maximum allowable value for GitHub:

git config http.postBuffer 2147483648

If cloning a repo instead using git clone, it can be cloned with the same option:

git clone -c http.postBuffer=2147483648 [email protected]:myuser/myrepo.git /path/to/myrepo

In both cases, the number above is equivalent to 2 GiB. It is however possible that you will need up to this amount of free memory to be able to use this value.

Ensure that each push to GitHub has commits that don't add more than this size of changes. In fact I would keep the commit push size under 1.8 GiB to be safe. This can require dividing a large commit into smaller commits and pushes.

Why this value?

This specific value is used because at least as of the year 2018, this value was documented (archive link) as the push size limit of GitHub:

we don’t allow pushes over 2GB

Why not set lower?

Some prior answers say to set it to 524288000 (500 MiB), but this number seems arbitrary and without merit. Any lower value should work as long as your push size is not larger than the set value.

Why not set higher?

If instead you set the value to higher than 2 GiB, and if your attempted push size is also higher, you can expect the documented error with GitHub:

remote: fatal: pack exceeds maximum allowed size

text-align: right on <select> or <option>

The best solution for me was to make

select {
    direction: rtl;
}

and then

option {
    direction: ltr;
}

again. So there is no change in how the text is read in a screen reader or and no formatting-problem.

How do I scroll to an element within an overflowed Div?

This is my own plugin (will position the element in top of the the list. Specially for overflow-y : auto. May not work with overflow-x!):

NOTE: elem is the HTML selector of an element which the page will be scrolled to. Anything supported by jQuery, like: #myid, div.myclass, $(jquery object), [dom object], etc.

jQuery.fn.scrollTo = function(elem, speed) { 
    $(this).animate({
        scrollTop:  $(this).scrollTop() - $(this).offset().top + $(elem).offset().top 
    }, speed == undefined ? 1000 : speed); 
    return this; 
};

If you don't need it to be animated, then use:

jQuery.fn.scrollTo = function(elem) { 
    $(this).scrollTop($(this).scrollTop() - $(this).offset().top + $(elem).offset().top); 
    return this; 
};

How to use:

$("#overflow_div").scrollTo("#innerItem");
$("#overflow_div").scrollTo("#innerItem", 2000); //custom animation speed 

Note: #innerItem can be anywhere inside #overflow_div. It doesn't really have to be a direct child.

Tested in Firefox (23) and Chrome (28).

If you want to scroll the whole page, check this question.

'Access denied for user 'root'@'localhost' (using password: NO)'

1) You can set root password by invoking MySQL console. It is located in

C:\wamp\bin\mysql\mysql5.1.53\bin by default.

Get to the directory and type MySQL. then set the password as follows..

    > SET PASSWORD FOR root@localhost = PASSWORD('new-password');

2) You can configure wamp's phpmyadmin application for root user by editing

C:\wamp\apps\phpmyadmin3.3.9\config.inc.php 

Note :- if you are using xampp then , file will be located at

C:\xampp\phpMyadmin\config.inc.php

It looks like this:

        $cfg['Servers'][$i]['verbose'] = 'localhost';
        $cfg['Servers'][$i]['host'] = 'localhost';
        $cfg['Servers'][$i]['port'] = '';
        $cfg['Servers'][$i]['socket'] = '';
        $cfg['Servers'][$i]['connect_type'] = 'tcp';
        $cfg['Servers'][$i]['extension'] = 'mysqli';
        $cfg['Servers'][$i]['auth_type'] = 'config';
        $cfg['Servers'][$i]['user'] = 'root';
        $cfg['Servers'][$i]['password'] = 'YOURPASSWORD';
        $cfg['Servers'][$i]['AllowNoPassword'] = false;

The error "Access denied for user 'root@localhost' (using password:NO)" will be resolved when you set $cfg['Servers'][$i]['AllowNoPassword'] to false

If you priviously changed the password for 'root@localhost', then you have to do 2 things to solve the error "Access denided for user 'root@localhost'":

  1. if ['password'] have a empty quotes like ' ' then put your password between quotes.
  2. change the (using password:NO) to (using password:YES)

This will resolve the error.

Note: phpmyadmin is a separate tool which comes with wamp. It just provide a interface to MySQL. if you change my sql root's password, then you should change the phpmyadmin configurations. Usually phpmyadmin is configured to root user.

How can I backup a remote SQL Server database to a local drive?

yone way you could take a backup from a remote SQL Server instance to your local drive, given the following condition is met:

  1. You have a shared folder on your local drive.
  2. the shared folder is accessible from the SQL Server box.

Now when specifying the backup command, use the shared folder path when specifying the disk option.

How to check if $_GET is empty?

Here are 3 different methods to check this

<?php
//Method 1
if(!empty($_GET))
echo "exist";
else
echo "do not exist";
//Method 2
echo "<br>";
if($_GET)
echo "exist";
else
echo "do not exist";
//Method 3
if(count($_GET))
echo "exist";
else
echo "do not exist";
?>

Getting PEAR to work on XAMPP (Apache/MySQL stack on Windows)

AS per point 1, your PEAR path is c:\xampplite\php\pear\

However, your path is pointing to \xampplite\php\pear\PEAR

Putting the two one above the other you can clearly see one is too long:

c:\xampplite\php\pear\

\xampplite\php\pear\PEAR

Your include path is set to go one PEAR too deep into the pear tree. The PEAR subfolder of the pear folder includes the PEAR component. You need to adjust your include path up one level.

(you don't need the c: by the way, your path is fine as is, just too deep)

How to increase font size in NeatBeans IDE?

When i modify the font size in Tools-> Options->Fonts & Colors->Syntaxto 14, the Editor font change fine, but Netbeans doesn´t take any change in fontsize IDE (icons, menus, ...) until i Add the --fontsize XX option in the file ...\NetBeans x.x\etc\netbeans.conf at the end of line netbeans_default_options AND set to true the already added option -J-Dsun.java2d.dpiaware, But i had to increase the font size Editor to 24. Thats works for me.

:: (double colon) operator in Java 8

Yes, that is true. The :: operator is used for method referencing. So, one can extract static methods from classes by using it or methods from objects. The same operator can be used even for constructors. All cases mentioned here are exemplified in the code sample below.

The official documentation from Oracle can be found here.

You can have a better overview of the JDK 8 changes in this article. In the Method/Constructor referencing section a code example is also provided:

interface ConstructorReference {
    T constructor();
}

interface  MethodReference {
   void anotherMethod(String input);
}

public class ConstructorClass {
    String value;

   public ConstructorClass() {
       value = "default";
   }

   public static void method(String input) {
      System.out.println(input);
   }

   public void nextMethod(String input) {
       // operations
   }

   public static void main(String... args) {
       // constructor reference
       ConstructorReference reference = ConstructorClass::new;
       ConstructorClass cc = reference.constructor();

       // static method reference
       MethodReference mr = cc::method;

       // object method reference
       MethodReference mr2 = cc::nextMethod;

       System.out.println(cc.value);
   }
}

Convert binary to ASCII and vice versa

For ASCII characters in the range [ -~] on Python 2:

>>> import binascii
>>> bin(int(binascii.hexlify('hello'), 16))
'0b110100001100101011011000110110001101111'

In reverse:

>>> n = int('0b110100001100101011011000110110001101111', 2)
>>> binascii.unhexlify('%x' % n)
'hello'

In Python 3.2+:

>>> bin(int.from_bytes('hello'.encode(), 'big'))
'0b110100001100101011011000110110001101111'

In reverse:

>>> n = int('0b110100001100101011011000110110001101111', 2)
>>> n.to_bytes((n.bit_length() + 7) // 8, 'big').decode()
'hello'

To support all Unicode characters in Python 3:

def text_to_bits(text, encoding='utf-8', errors='surrogatepass'):
    bits = bin(int.from_bytes(text.encode(encoding, errors), 'big'))[2:]
    return bits.zfill(8 * ((len(bits) + 7) // 8))

def text_from_bits(bits, encoding='utf-8', errors='surrogatepass'):
    n = int(bits, 2)
    return n.to_bytes((n.bit_length() + 7) // 8, 'big').decode(encoding, errors) or '\0'

Here's single-source Python 2/3 compatible version:

import binascii

def text_to_bits(text, encoding='utf-8', errors='surrogatepass'):
    bits = bin(int(binascii.hexlify(text.encode(encoding, errors)), 16))[2:]
    return bits.zfill(8 * ((len(bits) + 7) // 8))

def text_from_bits(bits, encoding='utf-8', errors='surrogatepass'):
    n = int(bits, 2)
    return int2bytes(n).decode(encoding, errors)

def int2bytes(i):
    hex_string = '%x' % i
    n = len(hex_string)
    return binascii.unhexlify(hex_string.zfill(n + (n & 1)))

Example

>>> text_to_bits('hello')
'0110100001100101011011000110110001101111'
>>> text_from_bits('110100001100101011011000110110001101111') == u'hello'
True

Use ffmpeg to add text subtitles

ffmpeg -i infile.mp4 -i infile.srt -c copy -c:s mov_text outfile.mp4

-vf subtitles=infile.srt will not work with -c copy


The order of -c copy -c:s mov_text is important. You are telling FFmpeg:

  1. Video: copy, Audio: copy, Subtitle: copy
  2. Subtitle: mov_text

If you reverse them, you are telling FFmpeg:

  1. Subtitle: mov_text
  2. Video: copy, Audio: copy, Subtitle: copy

Alternatively you could just use -c:v copy -c:a copy -c:s mov_text in any order.

Setting up PostgreSQL ODBC on Windows

As I see PostgreSQL installer doesn't include 64 bit version of ODBC driver, which is necessary in your case. Download psqlodbc_09_00_0310-x64.zip and install it instead. I checked that on Win 7 64 bit and PostgreSQL 9.0.4 64 bit and it looks ok:

enter image description here

Test connection:

enter image description here

The OLE DB provider "Microsoft.ACE.OLEDB.12.0" for linked server "(null)"

In my case this problem was occuring because i was accessing the file from shared folder by using computerName. OPENROWSET(''Microsoft.Jet.OLEDB.4.0'',''Excel 8.0;Database='\ntpc0100\MysharedFolder\KPI_tempData\VariablePayoutDetails.xls';IMEX=1;'','.....) Insted of using computerName ntpc0100(whatever your machine name) you should specify IPaddress of your machine. for example:- OPENROWSET(''Microsoft.Jet.OLEDB.4.0'',''Excel 8.0; Database='\193.34.23.200\MysharedFolder\KPI_tempData\KPIVariablePayoutDetails.xls'....);

SonarQube not picking up Unit Test Coverage

The presence of argLine configurations in either of surefire and jacoco plugins stops the jacoco report generation. The argLine should be defined in properties

<properties>
  <argLine>your jvm options here</argLine>
</properties>

Dictionary with list of strings as value

To do this manually, you'd need something like:

List<string> existing;
if (!myDic.TryGetValue(key, out existing)) {
    existing = new List<string>();
    myDic[key] = existing;
}
// At this point we know that "existing" refers to the relevant list in the 
// dictionary, one way or another.
existing.Add(extraValue);

However, in many cases LINQ can make this trivial using ToLookup. For example, consider a List<Person> which you want to transform into a dictionary of "surname" to "first names for that surname". You could use:

var namesBySurname = people.ToLookup(person => person.Surname,
                                     person => person.FirstName);

Combining two sorted lists in Python

def merge_sort(a,b):

    pa = 0
    pb = 0
    result = []

    while pa < len(a) and pb < len(b):
        if a[pa] <= b[pb]:
            result.append(a[pa])
            pa += 1
        else:
            result.append(b[pb])
            pb += 1

    remained = a[pa:] + b[pb:]
    result.extend(remained)


return result

Difference between classification and clustering in data mining?

enter image description here

Classification- A data-set can have different groups/ classes. red, green and black. Classification will try to find rules that divides them in different classes.

Custering- if a data-set is not having any class and you want to put them in some class/grouping, you do clustering. The purple circles above.

If classification rules are not good, you will have mis-classification in testing or ur rules are not correct enough.
if clustering is not good, you will have lot of outliers ie. data points not able to fall in any cluster.

PuTTY scripting to log onto host

For me it works this way:

putty -ssh [email protected] 22 -pw password

putty, protocol, user name @ ip address port and password. To connect in less than a second.

How to fix System.NullReferenceException: Object reference not set to an instance of an object

I was getting this same error, but for me this was due to a method in a base class (in Project A) having the output type changed from a non-void type to void. A child class existed in Project B (which I didn't want used and had marked obsolete) that I missed when performing this update and hence started throwing this error.

1>CSC : error CS8104: An error occurred while writing the output file: System.NullReferenceException: Object reference not set to an instance of an object.

Original Code:

[Obsolete("Calling this method will throw an error")]
public override CompletionStatus Run()
{
    throw new CustomException("Run process not supported.");
}

Revised Code:

[Obsolete("Calling this method will throw an error")]
public override void Run()
{
    throw new CustomException("Run process not supported.");
}

How to auto adjust table td width from the content

Remove all widths set using CSS and set white-space to nowrap like so:

.content-loader tr td {
    white-space: nowrap;
}

I would also remove the fixed width from the container (or add overflow-x: scroll to the container) if you want the fields to display in their entirety without it looking odd...

See more here: http://www.w3schools.com/cssref/pr_text_white-space.asp

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

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

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

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

on my system this returns:

i
i

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

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

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

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

This one is due to:

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

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

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

the good code should be:

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

How to scanf only integer?

If you're set on using scanf, you can do something like the following:

int val;
char follow;  
int read = scanf( "%d%c", &val, &follow );

if ( read == 2 )
{
  if ( isspace( follow ) )
  {
    // input is an integer followed by whitespace, accept
  }
  else
  {
    // input is an integer followed by non-whitespace, reject
  }
}
else if ( read == 1 )
{
  // input is an integer followed by EOF, accept
}
else
{
  // input is not an integer, reject
}

Write to CSV file and export it?

Here is a CSV action result I wrote that takes a DataTable and converts it into CSV. You can return this from your view and it will prompt the user to download the file. You should be able to convert this easily into a List compatible form or even just put your list into a DataTable.

using System;
using System.Text;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Data;

namespace Detectent.Analyze.ActionResults
{
    public class CSVResult : ActionResult
    {
        /// <summary>
        /// Converts the columns and rows from a data table into an Microsoft Excel compatible CSV file.
        /// </summary>
        /// <param name="dataTable"></param>
        /// <param name="fileName">The full file name including the extension.</param>
        public CSVResult(DataTable dataTable, string fileName)
        {
            Table = dataTable;
            FileName = fileName;
        }

        public string FileName { get; protected set; }
        public DataTable Table { get; protected set; }




        public override void ExecuteResult(ControllerContext context)
        {
            StringBuilder csv = new StringBuilder(10 * Table.Rows.Count * Table.Columns.Count);

            for (int c = 0; c < Table.Columns.Count; c++)
            {
                if (c > 0)
                    csv.Append(",");
                DataColumn dc = Table.Columns[c];
                string columnTitleCleaned = CleanCSVString(dc.ColumnName);
                csv.Append(columnTitleCleaned);
            }
            csv.Append(Environment.NewLine);
            foreach (DataRow dr in Table.Rows)
            {
                StringBuilder csvRow = new StringBuilder();
                for(int c = 0; c < Table.Columns.Count; c++)
                {
                    if(c != 0)
                        csvRow.Append(",");

                    object columnValue = dr[c];
                    if (columnValue == null)
                        csvRow.Append("");
                    else
                    {
                        string columnStringValue = columnValue.ToString();


                        string cleanedColumnValue = CleanCSVString(columnStringValue);

                        if (columnValue.GetType() == typeof(string) && !columnStringValue.Contains(","))
                        {
                            cleanedColumnValue = "=" + cleanedColumnValue; // Prevents a number stored in a string from being shown as 8888E+24 in Excel. Example use is the AccountNum field in CI that looks like a number but is really a string.
                        }
                        csvRow.Append(cleanedColumnValue);
                    }
                }
                csv.AppendLine(csvRow.ToString());
            }

            HttpResponseBase response = context.HttpContext.Response;
            response.ContentType = "text/csv";
            response.AppendHeader("Content-Disposition", "attachment;filename=" + this.FileName);
            response.Write(csv.ToString());
        }

        protected string CleanCSVString(string input)
        {
            string output = "\"" + input.Replace("\"", "\"\"").Replace("\r\n", " ").Replace("\r", " ").Replace("\n", "") + "\"";
            return output;
        }
    }
}

Return rows in random order

This is the simplest solution:

SELECT quote FROM quotes ORDER BY RAND() 

Although it is not the most efficient. This one is a better solution.

Generating a PNG with matplotlib when DISPLAY is undefined

When signing into the server to execute the code use this instead:

ssh -X username@servername

the -X will get rid of the no display name and no $DISPLAY environment variable error

:)

What does -XX:MaxPermSize do?

The permanent space is where the classes, methods, internalized strings, and similar objects used by the VM are stored and never deallocated (hence the name).

This Oracle article succinctly presents the working and parameterization of the HotSpot GC and advises you to augment this space if you load many classes (this is typically the case for application servers and some IDE like Eclipse) :

The permanent generation does not have a noticeable impact on garbage collector performance for most applications. However, some applications dynamically generate and load many classes; for example, some implementations of JavaServer Pages (JSP) pages. These applications may need a larger permanent generation to hold the additional classes. If so, the maximum permanent generation size can be increased with the command-line option -XX:MaxPermSize=.

Note that this other Oracle documentation lists the other HotSpot arguments.

Update : Starting with Java 8, both the permgen space and this setting are gone. The memory model used for loaded classes and methods is different and isn't limited (with default settings). You should not see this error any more.

How to sort a data frame by alphabetic order of a character variable in R?

The arrange function in the plyr package makes it easy to sort by multiple columns. For example, to sort DF by ID first and then decreasing by num, you can write

plyr::arrange(DF, ID, desc(num))

how to play video from url

please check this link : http://developer.android.com/guide/appendix/media-formats.html

videoview can't support some codec .

i suggested you to use mediaplayer , when get "sorry , can't play video"

jQuery DatePicker with today as maxDate

If you're using bootstrap 3 date time picker, try this:

$('.selector').datetimepicker({ maxDate: $.now() });

Javascript, Time and Date: Getting the current minute, hour, day, week, month, year of a given millisecond time

Additionally, how do I retrieve the number of days of a given month?

Aside from calculating it yourself (and consequently having to get leap years right), you can use a Date calculation to do it:

var y= 2010, m= 11;            // December 2010 - trap: months are 0-based in JS

var next= Date.UTC(y, m+1);    // timestamp of beginning of following month
var end= new Date(next-1);     // date for last second of this month
var lastday= end.getUTCDate(); // 31

In general for timestamp/date calculations I'd recommend using the UTC-based methods of Date, like getUTCSeconds instead of getSeconds(), and Date.UTC to get a timestamp from a UTC date, rather than new Date(y, m), so you don't have to worry about the possibility of weird time discontinuities where timezone rules change.

Not able to install Python packages [SSL: TLSV1_ALERT_PROTOCOL_VERSION]

I also hit this problem on my windows10 and tried all the answers but didn't solve my problem.

C:\python367\Scripts>pip install Flask

Collecting Flask Could not find a version that satisfies the requirement Flask (from versions: ) No matching distribution found for Flask

After that, I find the pip configuration file had been modified. So, I set the pip.ini as the original default configuration, re-run the pip command and it works for me!

In summary of the solution of mine:

  1. Check the pip.ini (usually under the path C:\ProgramData\pip) had been modified;

  2. If yes in step1, try to reset it to a default configuration.

Easier way to debug a Windows service

You can also start the service through the command prompt (sc.exe).

Personally, I'd run the code as a stand-alone program in the debugging phase, and when most bugs are ironed out, change to running as service.

How to solve munmap_chunk(): invalid pointer error in C++

This happens when the pointer passed to free() is not valid or has been modified somehow. I don't really know the details here. The bottom line is that the pointer passed to free() must be the same as returned by malloc(), realloc() and their friends. It's not always easy to spot what the problem is for a novice in their own code or even deeper in a library. In my case, it was a simple case of an undefined (uninitialized) pointer related to branching.

The free() function frees the memory space pointed to by ptr, which must have been returned by a previous call to malloc(), calloc() or realloc(). Otherwise, or if free(ptr) has already been called before, undefined behavior occurs. If ptr is NULL, no operation is performed. GNU 2012-05-10 MALLOC(3)

char *words; // setting this to NULL would have prevented the issue

if (condition) {
    words = malloc( 512 );

    /* calling free sometime later works here */

    free(words)
} else {

    /* do not allocate words in this branch */
}

/* free(words);  -- error here --
*** glibc detected *** ./bin: munmap_chunk(): invalid pointer: 0xb________ ***/

There are many similar questions here about the related free() and rellocate() functions. Some notable answers providing more details:

*** glibc detected *** free(): invalid next size (normal): 0x0a03c978 ***
*** glibc detected *** sendip: free(): invalid next size (normal): 0x09da25e8 ***
glibc detected, realloc(): invalid pointer


IMHO running everything in a debugger (Valgrind) is not the best option because errors like this are often caused by inept or novice programmers. It's more productive to figure out the issue manually and learn how to avoid it in the future.

@UniqueConstraint annotation in Java

Way1 :

@Entity

@Table(name = "table_name", uniqueConstraints={@UniqueConstraint(columnNames = "column1"),@UniqueConstraint(columnNames = "column2")})

-- Here both Column1 and Column2 acts as unique constraints separately. Ex : if any time either the value of column1 or column2 value matches then you will get UNIQUE_CONSTRAINT Error.

Way2 :

@Entity

@Table(name = "table_name", uniqueConstraints={@UniqueConstraint(columnNames ={"column1","column2"})})

-- Here both column1 and column2 combined values acts as unique constraints

java.lang.ClassNotFoundException: org.springframework.boot.SpringApplication Maven

Mine was caused by a corrupt Maven repository.

I deleted everything under C:\Users\<me>\.m2\repository.

Then did an Eclipse Maven Update, and it worked first time.

So it was simply spring-boot.jar got corrupted.

Command line: search and replace in all filenames matched by grep

Do you mean search and replace a string in all files matched by grep?

perl -p -i -e 's/oldstring/newstring/g' `grep -ril searchpattern *`

Edit

Since this seems to be a fairly popular question thought I'd update.

Nowadays I mostly use ack-grep as it's more user-friendly. So the above command would be:

perl -p -i -e 's/old/new/g' `ack -l searchpattern`

To handle whitespace in file names you can run:

ack --print0 -l searchpattern | xargs -0 perl -p -i -e 's/old/new/g'

you can do more with ack-grep. Say you want to restrict the search to HTML files only:

ack --print0 --html -l searchpattern | xargs -0 perl -p -i -e 's/old/new/g'

And if white space is not an issue it's even shorter:

perl -p -i -e 's/old/new/g' `ack -l --html searchpattern`
perl -p -i -e 's/old/new/g' `ack -f --html` # will match all html files

Filter dataframe rows if value in column is in a set list of values

You can also directly query your DataFrame for this information.

rpt.query('STK_ID in (600809,600141,600329)')

Or similarly search for ranges:

rpt.query('60000 < STK_ID < 70000')

Reading in double values with scanf in c

Format specifier in printf should be %f for doubl datatypes since float datatyles eventually convert to double datatypes inside printf.

There is no provision to print float data. Please find the discussion here : Correct format specifier for double in printf

Twitter Bootstrap alert message close and open again

There's a very simple way to do this using JQuery

If you delete data-dismiss="alert" from the alert div, you can just hide the alert using the x button, by adding a click events and interacting with the display css attribute of the alert.

$(".close").click(function(){
   $(this).parent().css("display", "none");
});

Then, whenever you need it again, you can toggle the display attribute again.

Full Example:

<div class="alert alert-danger" role="alert" id="my_alert" style="display: none;">
   Uh Oh... Something went wrong
  <button type="button" class="close" aria-label="Close">
     <span aria-hidden="true">&times;</span>
  </button>
</div>

<script>
   $(".close").click(function(){
      $(this).parent().css("display", "none");
   });

   //Use whatever event you like
   $("#show_alert").click(function(){
      $("#my_alert).css("display", "inherit");
   });
<script>

How to include files outside of Docker's build context?

As is described in this GitHub issue the build actually happens in /tmp/docker-12345, so a relative path like ../relative-add/some-file is relative to /tmp/docker-12345. It would thus search for /tmp/relative-add/some-file, which is also shown in the error message.*

It is not allowed to include files from outside the build directory, so this results in the "Forbidden path" message."

In Python How can I declare a Dynamic Array

In Python, a list is a dynamic array. You can create one like this:

lst = [] # Declares an empty list named lst

Or you can fill it with items:

lst = [1,2,3]

You can add items using "append":

lst.append('a')

You can iterate over elements of the list using the for loop:

for item in lst:
    # Do something with item

Or, if you'd like to keep track of the current index:

for idx, item in enumerate(lst):
    # idx is the current idx, while item is lst[idx]

To remove elements, you can use the del command or the remove function as in:

del lst[0] # Deletes the first item
lst.remove(x) # Removes the first occurence of x in the list

Note, though, that one cannot iterate over the list and modify it at the same time; to do that, you should instead iterate over a slice of the list (which is basically a copy of the list). As in:

 for item in lst[:]: # Notice the [:] which makes a slice
       # Now we can modify lst, since we are iterating over a copy of it

How to change options of <select> with jQuery?

If for example your html code contain this code:

<select id="selectId"><option>Test1</option><option>Test2</option></select>

In order to change the list of option inside your select, you can use this code bellow. when your name select named selectId.

var option = $('<option></option>').attr("value", "option value").text("Text");
$("#selectId").html(option);

in this example above i change the old list of option by only one new option.

Spring Boot yaml configuration for a list of strings

Ahmet's answer provides on how to assign the comma separated values to String array.

To use the above configuration in different classes you might need to create getters/setters for this.. But if you would like to load this configuration once and keep using this as a bean with Autowired annotation, here is the how I accomplished:

In ConfigProvider.java

@Bean (name = "ignoreFileNames")
@ConfigurationProperties ( prefix = "ignore.filenames" )
public List<String> ignoreFileNames(){
    return new ArrayList<String>();
}

In outside classes:

@Autowired
@Qualifier("ignoreFileNames")
private List<String> ignoreFileNames;

you can use the same list everywhere else by autowiring.

How to customize <input type="file">?

Bootstrap example

<label className="btn btn-info btn-lg">
  Upload
  <input type="file" style="display: none" />
</label>

What is the reason and how to avoid the [FIN, ACK] , [RST] and [RST, ACK]

Here is a rough explanation of the concepts.

[ACK] is the acknowledgement that the previously sent data packet was received.

[FIN] is sent by a host when it wants to terminate the connection; the TCP protocol requires both endpoints to send the termination request (i.e. FIN).

So, suppose

  • host A sends a data packet to host B
  • and then host B wants to close the connection.
  • Host B (depending on timing) can respond with [FIN,ACK] indicating that it received the sent packet and wants to close the session.
  • Host A should then respond with a [FIN,ACK] indicating that it received the termination request (the ACK part) and that it too will close the connection (the FIN part).

However, if host A wants to close the session after sending the packet, it would only send a [FIN] packet (nothing to acknowledge) but host B would respond with [FIN,ACK] (acknowledges the request and responds with FIN).

Finally, some TCP stacks perform half-duplex termination, meaning that they can send [RST] instead of the usual [FIN,ACK]. This happens when the host actively closes the session without processing all the data that was sent to it. Linux is one operating system which does just this.

You can find a more detailed and comprehensive explanation here.

SQL RANK() over PARTITION on joined tables

SELECT a.C_ID,a.QRY_ID,a.RES_ID,b.SCORE,ROW_NUMBER() OVER (ORDER BY SCORE DESC) AS [RANK]
FROM CONTACTS a JOIN RSLTS b ON a.QRY_ID=b.QRY_ID AND a.RES_ID=b.RES_ID
ORDER BY a.C_ID

python paramiko ssh

There is extensive paramiko API documentation you can find at: http://docs.paramiko.org/en/stable/index.html

I use the following method to execute commands on a password protected client:

import paramiko

nbytes = 4096
hostname = 'hostname'
port = 22
username = 'username' 
password = 'password'
command = 'ls'

client = paramiko.Transport((hostname, port))
client.connect(username=username, password=password)

stdout_data = []
stderr_data = []
session = client.open_channel(kind='session')
session.exec_command(command)
while True:
    if session.recv_ready():
        stdout_data.append(session.recv(nbytes))
    if session.recv_stderr_ready():
        stderr_data.append(session.recv_stderr(nbytes))
    if session.exit_status_ready():
        break

print 'exit status: ', session.recv_exit_status()
print ''.join(stdout_data)
print ''.join(stderr_data)

session.close()
client.close()

Find integer index of rows with NaN in pandas dataframe

in the case you have datetime index and you want to have the values:

df.loc[pd.isnull(df).any(1), :].index.values

File opens instead of downloading in internet explorer in a href link

This is not a code issue. It is your default IE settings

To change the "always open" setting:

  1. In Windows Explorer, click on the "Tools" menu, choose "Folder options"
  2. In the window that appears, click on the "File Types" tab, and scroll through the list until you find the file extension you want to change (they're in alphabetical order). For example, if Internet Explorer always tries to open .zip files, scroll through the list until you find the entry for "zip".
  3. Click on the file type, then the "Advanced" button.
  4. Check the "Confirm after download" box, then click OK > Close.

EDIT: If you ask me , instead of making any changes in the code i would add the following text "Internet Explorer users: To download file, "Rightclick" the link and hit "Save target as" to download the file."

EDIT 2: THIS solution will work perfectly for you. Its a solution i just copied from the other answer. Im not trying to pass it off as my own

Content-Type: application/octet-stream
Content-Disposition: attachment;filename=\"filename.xxx\"

However you must make sure that you specify the type of file(s) you allow. You have mentioned in your post that you want this for any type of file. This will be an issue.

For ex. If your site has images and if the end user clicks these images then they will be downloaded on his computer instead of opening in a new page. Got the point. So you need to specify the file extensions.

PostgreSQL delete with inner join

Another form that works with Postgres 9.1+ is combining a Common Table Expression with the USING statement for the join.

WITH prod AS (select m_product_id, upc from m_product where upc='7094')
DELETE FROM m_productprice B
USING prod C
WHERE B.m_product_id = C.m_product_id 
AND B.m_pricelist_version_id = '1000020';

How do I force Maven to use my local repository rather than going out to remote repos to retrieve artifacts?

The dependency has a snapshot version. For snapshots, Maven will check the local repository and if the artifact found in the local repository is too old, it will attempt to find an updated one in the remote repositories. That is probably what you are seeing.

Note that this behavior is controlled by the updatePolicy directive in the repository configuration (which is daily by default for snapshot repositories).

Java: Retrieving an element from a HashSet

You can HashMap<MyHashObject,MyHashObject> instead of HashSet<MyHashObject>.

Calling ContainsKey() on your "reconstructed" MyHashObject will first hashCode()-check the collection, and if a duplicate hashcode is hit, finally equals()-check your "reconstructed" against the original, at which you can retrieve the original using get()

This is O(1) but the downside is you will likely have to override both equals() and hashCode() methods.

Relative paths in Python

From what suggest others and from pathlib documentation, a simple and clear solution is the following (suppose the file we need to refer to: Test/data/users.csv:

# This file location: Tests/src/long/module/subdir/some_script.py
from pathlib import Path

# back to Tests/
PROJECT_ROOT = Path(__file__).parents[4]
# then down to Test/data/users.csv
CSV_USERS_PATH = PROJECT_ROOT / 'data' / 'users.csv'  

with CSV_USERS_PATH.open() as users:
    print(users.read())

Now this looks a bit odd to me, because if you move some_script.py around, the path to the root of our project may change (we would need to modify parents[4]). On the other hand I found a solution that I prefer based on the same idea.

Suppose we have the following directory structure:

Tests
+-- data
¦  +-- users.csv
+-- src
   +-- long
   ¦  +-- module
   ¦     +-- subdir
   ¦        +-- some_script.py
   +-- main.py
   +-- paths.py

The paths.py file will be responsible for storing the root location of our projet:

from pathlib import Path

PROJECT_ROOT = Path(__file__).parents[1]

All scripts can now use paths.PROJECT_ROOT to express absolute paths from the root of the project. For example in src/long/module/subdir/some_script.py we could have:

from paths import PROJECT_ROOT

CSV_USERS_PATH = PROJECT_ROOT / 'data' / 'users.csv'

def hello():
    with CSV_USERS_PATH.open() as f:
        print(f.read())

And everything goes as expected:

~/Tests/src/$ python main.py

/Users/cglacet/Tests/data/users.csv
hello, user

~/Tests/$ python src/main.py

/Users/cglacet/Tests/data/users.csv
hello, user

The main.py script simply is:

from long.module.subdir import some_script

some_script.hello()

Drop all tables whose names begin with a certain string

You may need to modify the query to include the owner if there's more than one in the database.

DECLARE @cmd varchar(4000)
DECLARE cmds CURSOR FOR
SELECT 'drop table [' + Table_Name + ']'
FROM INFORMATION_SCHEMA.TABLES
WHERE Table_Name LIKE 'prefix%'

OPEN cmds
WHILE 1 = 1
BEGIN
    FETCH cmds INTO @cmd
    IF @@fetch_status != 0 BREAK
    EXEC(@cmd)
END
CLOSE cmds;
DEALLOCATE cmds

This is cleaner than using a two-step approach of generate script plus run. But one advantage of the script generation is that it gives you the chance to review the entirety of what's going to be run before it's actually run.

I know that if I were going to do this against a production database, I'd be as careful as possible.

Edit Code sample fixed.

How do I change the owner of a SQL Server database?

Here is a way to change the owner on ALL DBS (excluding System)

EXEC sp_msforeachdb'
USE [?]
IF ''?'' <> ''master'' AND ''?'' <> ''model'' AND ''?'' <> ''msdb'' AND ''?'' <> ''tempdb''
BEGIN
 exec sp_changedbowner ''sa''
END
'

How to read the value of a private field from a different class in Java?

In order to access private fields, you need to get them from the class's declared fields and then make them accessible:

Field f = obj.getClass().getDeclaredField("stuffIWant"); //NoSuchFieldException
f.setAccessible(true);
Hashtable iWantThis = (Hashtable) f.get(obj); //IllegalAccessException

EDIT: as has been commented by aperkins, both accessing the field, setting it as accessible and retrieving the value can throw Exceptions, although the only checked exceptions you need to be mindful of are commented above.

The NoSuchFieldException would be thrown if you asked for a field by a name which did not correspond to a declared field.

obj.getClass().getDeclaredField("misspelled"); //will throw NoSuchFieldException

The IllegalAccessException would be thrown if the field was not accessible (for example, if it is private and has not been made accessible via missing out the f.setAccessible(true) line.

The RuntimeExceptions which may be thrown are either SecurityExceptions (if the JVM's SecurityManager will not allow you to change a field's accessibility), or IllegalArgumentExceptions, if you try and access the field on an object not of the field's class's type:

f.get("BOB"); //will throw IllegalArgumentException, as String is of the wrong type

What are the differences between a multidimensional array and an array of arrays in C#?

I am parsing .il files generated by ildasm to build a database of assemnblies, classes, methods, and stored procedures for use doing a conversion. I came across the following, which broke my parsing.

.method private hidebysig instance uint32[0...,0...] 
        GenerateWorkingKey(uint8[] key,
                           bool forEncryption) cil managed

The book Expert .NET 2.0 IL Assembler, by Serge Lidin, Apress, published 2006, Chapter 8, Primitive Types and Signatures, pp. 149-150 explains.

<type>[] is termed a Vector of <type>,

<type>[<bounds> [<bounds>**] ] is termed an array of <type>

** means may be repeated, [ ] means optional.

Examples: Let <type> = int32.

1) int32[...,...] is a two-dimensional array of undefined lower bounds and sizes

2) int32[2...5] is a one-dimensional array of lower bound 2 and size 4.

3) int32[0...,0...] is a two-dimensional array of lower bounds 0 and undefined size.

Tom

Where can I view Tomcat log files in Eclipse?

Double click and open the server. Go to 'Arguments'. -Dcatalina.base= .. something. Go to that something. Your logs are there.

How can I add a box-shadow on one side of an element?

Ok, here is one try more. Using pseudo elements and aplying the shadow-box porperty over them.

html:

<div class="no-relevant-box">
  <div class="div-to-shadow-1"></div>
  <div class="div-to-shadow-2"></div>
</div>

sass:

.div-to-shadow-1, .div-to-shadow-2
  height: 150px
  width: 150px
  overflow: hidden
  transition: all 0.3s ease-in-out
  &::after
    display: block
    content: ''
    position: relative
    top: 0
    left: 100%
    height: 100%
    width: 10px
    border: 1px solid mediumeagreen
    box-shadow:  0px 7px 12px rgba(0,0,0,0.3)
  &:hover
    border: 1px solid dodgerblue
    overflow: visible

https://codepen.io/alex3o0/pen/PrMyNQ

How to put a jar in classpath in Eclipse?

Right click on the project in which you want to put jar file. A window will open like this

enter image description here

Click on the AddExternal Jars there you can give the path to that jar file

How to know if .keyup() is a character key (jQuery)

Note: In hindsight this was a quick and dirty answer, and may not work in all situations. To have a reliable solution, see Tim Down's answer (copy pasting that here as this answer is still getting views and upvotes):

You can't do this reliably with the keyup event. If you want to know something about the character that was typed, you have to use the keypress event instead.

The following example will work all the time in most browsers but there are some edge cases that you should be aware of. For what is in my view the definitive guide on this, see http://unixpapa.com/js/key.html.

$("input").keypress(function(e) {
    if (e.which !== 0) {
        alert("Character was typed. It was: " + String.fromCharCode(e.which));
    }
});

keyup and keydown give you information about the physical key that was pressed. On standard US/UK keyboards in their standard layouts, it looks like there is a correlation between the keyCode property of these events and the character they represent. However, this is not reliable: different keyboard layouts will have different mappings.


The following was the original answer, but is not correct and may not work reliably in all situations.

To match the keycode with a word character (eg., a would match. space would not)

$("input").keyup(function(event)
{ 
    var c= String.fromCharCode(event.keyCode);
    var isWordcharacter = c.match(/\w/);
}); 

Ok, that was a quick answer. The approach is the same, but beware of keycode issues, see this article in quirksmode.

Open a workbook using FileDialog and manipulate it in Excel VBA

Unless I misunderstand your question, you can just open a file read only. Here is a simply example, without any checks.

To get the file path from the user use this function:

Private Function get_user_specified_filepath() As String
    'or use the other code example here.
    Dim fd As Office.FileDialog
    Set fd = Application.FileDialog(msoFileDialogFilePicker)
    fd.AllowMultiSelect = False
    fd.Title = "Please select the file."
    get_user_specified_filepath = fd.SelectedItems(1)
End Function

Then just open the file read only and assign it to a variable:

dim wb as workbook
set wb = Workbooks.Open(get_user_specified_filepath(), ReadOnly:=True)

delete map[key] in go?

delete(sessions, "anykey")

These days, nothing will crash.

Creating a Pandas DataFrame from a Numpy array: How do I specify the index column and column headers?

This can be done simply by using from_records of pandas DataFrame

import numpy as np
import pandas as pd
# Creating a numpy array
x = np.arange(1,10,1).reshape(-1,1)
dataframe = pd.DataFrame.from_records(x)

Java IOException "Too many open files"

Although in most general cases the error is quite clearly that file handles have not been closed, I just encountered an instance with JDK7 on Linux that well... is sufficiently ****ed up to explain here.

The program opened a FileOutputStream (fos), a BufferedOutputStream (bos) and a DataOutputStream (dos). After writing to the dataoutputstream, the dos was closed and I thought everything went fine.

Internally however, the dos, tried to flush the bos, which returned a Disk Full error. That exception was eaten by the DataOutputStream, and as a consequence the underlying bos was not closed, hence the fos was still open.

At a later stage that file was then renamed from (something with a .tmp) to its real name. Thereby, the java file descriptor trackers lost track of the original .tmp, yet it was still open !

To solve this, I had to first flush the DataOutputStream myself, retrieve the IOException and close the FileOutputStream myself.

I hope this helps someone.

AngularJS : Difference between the $observe and $watch methods

Why is $observe different than $watch?

The watchExpression is evaluated and compared to the previous value each digest() cycle, if there's a change in the watchExpression value, the watch function is called.

$observe is specific to watching for interpolated values. If a directive's attribute value is interpolated, eg dir-attr="{{ scopeVar }}", the observe function will only be called when the interpolated value is set (and therefore when $digest has already determined updates need to be made). Basically there's already a watcher for the interpolation, and the $observe function piggybacks off that.

See $observe & $set in compile.js

Removing all line breaks and adding them after certain text

You can also try this in Notepad++

  • Highlight the lines you want to join (ctrl + a to select all)
  • Choose Edit -> Line Operations -> Join Lines

What is the actual use of Class.forName("oracle.jdbc.driver.OracleDriver") while connecting to a database?

An alternative would to use the jdbc.drivers System property to specify your required drivers(s) on the command line when you start the JVM.

Use table row coloring for cells in Bootstrap

You can override the default css rules with this:

.table tbody tr > td.success {
  background-color: #dff0d8 !important;
}

.table tbody tr > td.error {
  background-color: #f2dede !important;
}

.table tbody tr > td.warning {
  background-color: #fcf8e3 !important;
}

.table tbody tr > td.info {
  background-color: #d9edf7 !important;
}

.table-hover tbody tr:hover > td.success {
  background-color: #d0e9c6 !important;
}

.table-hover tbody tr:hover > td.error {
  background-color: #ebcccc !important;
}

.table-hover tbody tr:hover > td.warning {
  background-color: #faf2cc !important;
}

.table-hover tbody tr:hover > td.info {
  background-color: #c4e3f3 !important;
}

!important is needed as bootstrap actually colours the cells individually (afaik it's not possible to just apply background-color to a tr). I couldn't find any colour variables in my version of bootstrap but that's the basic idea anyway.

How to declare string constants in JavaScript?

Many browsers' implementations (and Node) have constants, used with const.

const SOME_VALUE = "Your string";

This const means that you can't reassign it to any other value.

Check the compatibility notes to see if your targeted browsers are supported.

Alternatively, you could also modify the first example, using defineProperty() or its friends and make the writable property false. This will mean the variable's contents can not be changed, like a constant.

Get value of c# dynamic property via string

The easiest method for obtaining both a setter and a getter for a property which works for any type including dynamic and ExpandoObject is to use FastMember which also happens to be the fastest method around (it uses Emit).

You can either get a TypeAccessor based on a given type or an ObjectAccessor based of an instance of a given type.

Example:

var staticData = new Test { Id = 1, Name = "France" };
var objAccessor = ObjectAccessor.Create(staticData);
objAccessor["Id"].Should().Be(1);
objAccessor["Name"].Should().Be("France");

var anonymous = new { Id = 2, Name = "Hilton" };
objAccessor = ObjectAccessor.Create(anonymous);
objAccessor["Id"].Should().Be(2);
objAccessor["Name"].Should().Be("Hilton");

dynamic expando = new ExpandoObject();
expando.Id = 3;
expando.Name = "Monica";
objAccessor = ObjectAccessor.Create(expando);
objAccessor["Id"].Should().Be(3);
objAccessor["Name"].Should().Be("Monica");

var typeAccessor = TypeAccessor.Create(staticData.GetType());
typeAccessor[staticData, "Id"].Should().Be(1);
typeAccessor[staticData, "Name"].Should().Be("France");

typeAccessor = TypeAccessor.Create(anonymous.GetType());
typeAccessor[anonymous, "Id"].Should().Be(2);
typeAccessor[anonymous, "Name"].Should().Be("Hilton");

typeAccessor = TypeAccessor.Create(expando.GetType());
((int)typeAccessor[expando, "Id"]).Should().Be(3);
((string)typeAccessor[expando, "Name"]).Should().Be("Monica");

How do I write a backslash (\) in a string?

The previous answer is correct but in this specific case I would recommend using the System.IO.Path.Combine method.

You can find more details here: http://msdn.microsoft.com/en-us/library/fyy7a5kt.aspx

Warning: mysql_connect(): [2002] No such file or directory (trying to connect via unix:///tmp/mysql.sock) in

Since your might use MAMP, either change your Port to the default 3306 or use 127.0.0.1 in the database.php

$db['default'] = array(
    'dsn'   => '',
    'hostname' => 'localhost',// leave it for port 3306
    'username' => 'yourUserhere',
    'password' => 'yourPassword',
    'database' => 'yourDatabase',
    'dbdriver' => 'mysqli',
    'dbprefix' => '',
    'pconnect' => FALSE,
    'db_debug' => (ENVIRONMENT !== 'production'),
    'cache_on' => FALSE,
    'cachedir' => '',
    'char_set' => 'utf8',
    'dbcollat' => 'utf8_general_ci',
    'swap_pre' => '',
    'encrypt' => FALSE,
    'compress' => FALSE,
    'stricton' => FALSE,
    'failover' => array(),
    'save_queries' => TRUE
);

Or with the default settings:

$db['default'] = array(
        'dsn'   => '',
        'hostname' => '127.0.0.1:8889',// leave it for port 8889
        'username' => 'yourUserhere',
        'password' => 'yourPassword',
        'database' => 'yourDatabase',
        'dbdriver' => 'mysqli',
        'dbprefix' => '',
        'pconnect' => FALSE,
        'db_debug' => (ENVIRONMENT !== 'production'),
        'cache_on' => FALSE,
        'cachedir' => '',
        'char_set' => 'utf8',
        'dbcollat' => 'utf8_general_ci',
        'swap_pre' => '',
        'encrypt' => FALSE,
        'compress' => FALSE,
        'stricton' => FALSE,
        'failover' => array(),
        'save_queries' => TRUE
    );