Programs & Examples On #Sp executesql

EXEC sp_executesql with multiple parameters

This also works....sometimes you may want to construct the definition of the parameters outside of the actual EXEC call.

DECLARE @Parmdef nvarchar (500)
DECLARE @SQL nvarchar (max)
DECLARE @xTxt1  nvarchar (100) = 'test1'
DECLARE @xTxt2  nvarchar (500) = 'test2' 
SET @parmdef = '@text1 nvarchar (100), @text2 nvarchar (500)'
SET @SQL = 'PRINT @text1 + '' '' + @text2'
EXEC sp_executeSQL @SQL, @Parmdef, @xTxt1, @xTxt2

ReactJS: Maximum update depth exceeded error

In this case , this code

{<td><span onClick={this.toggle()}>Details</span></td>}

causes toggle function to call immediately and re render it again and again thus making infinite calls.

so passing only the reference to that toggle method will solve the problem.

so ,

{<td><span onClick={this.toggle}>Details</span></td>}

will be the solution code.

If you want to use the () , you should use an arrow function like this

{<td><span onClick={()=> this.toggle()}>Details</span></td>}

In case you want to pass parameters you should choose the last option and you can pass parameters like this

{<td><span onClick={(arg)=>this.toggle(arg)}>Details</span></td>}

In the last case it doesn't call immediately and don't cause the re render of the function, hence avoiding infinite calls.

How do I UPDATE from a SELECT in SQL Server?

declare @tblStudent table (id int,name varchar(300))
declare @tblMarks table (std_id int,std_name varchar(300),subject varchar(50),marks int)

insert into @tblStudent Values (1,'Abdul')
insert into @tblStudent Values(2,'Rahim')

insert into @tblMarks Values(1,'','Math',50)
insert into @tblMarks Values(1,'','History',40)
insert into @tblMarks Values(2,'','Math',30)
insert into @tblMarks Values(2,'','history',80)

select * from @tblMarks

update m
 from @tblMarks as m
left join @tblStudent as s on

select * from @tblMarks

Read response headers from API response - Angular 5 + TypeScript

Try this simple code.

1. Components side code: to get both body and header property. Here there's a token in body and Authorization in the header.

loginUser() {
    subscribe(res => {
        let output1 = res;

2. Service side code: sending login data in the body and observe the response in Observable any which be subscribed in the component side.

loginTest(loginCred: LoginParams): Observable<any> {
    const header1= {'Content-Type':'application/json',};
    const body =  JSON.stringify(loginCred);
        headers: header1,
        observe: 'response',
        responseType: 'json'

How to reference Microsoft.Office.Interop.Excel dll?

Instead of early binding the reference, there's an open source project called NetOffice that abstracts this from your project, making life much easier. That way you don't have to rely on your users having a specific version of Office installed.

NetOffice Codeplex site.

A non well formed numeric value encountered

This error occurs when you perform calculations with variables that use letters combined with numbers (alphanumeric), for example 24kb, 886ab ...

I had the error in the following function

function get_config_bytes($val) {
    $val = trim($val);
    $last = strtolower($val[strlen($val)-1]);       
    switch($last) {
        case 'g':
            $val *= 1024;
        case 'm':
            $val *= 1024;
        case 'k':
            $val *= 1024;
    return $this->fix_integer_overflow($val);

The application uploads images but it didn't work, it showed the following warning:

enter image description here

Solution: The intval() function extracts the integer value of a variable with alphanumeric data and creates a new variable with the same value but converted to an integer with the intval() function. Here is the code:

function get_config_bytes($val) {
    $val = trim($val);
    $last = strtolower($val[strlen($val)-1]);
    $intval = intval(trim($val));
    switch($last) {
        case 'g':
            $intval *= 1024;
        case 'm':
            $intval *= 1024;
        case 'k':
            $intval *= 1024;
    return $this->fix_integer_overflow($intval);

How to check if a string in Python is in ASCII?

Ran into something like this recently - for future reference

import chardet

encoding = chardet.detect(string)
if encoding['encoding'] == 'ascii':
    print 'string is in ascii'

which you could use with:

string_ascii = string.decode(encoding['encoding']).encode('ascii')

How can you print multiple variables inside a string using printf?

printf("\nmaximum of %d and %d is = %d",a,b,c);

Text was truncated or one or more characters had no match in the target code page including the primary key in an unpivot

While an approach proposed above (@chookoos, here in this q&a convert to Excel workbook) and import resolves those kinds of issues, this solution this solution in another q&a is excellent because you can stay with your csv or tsv or txt file, and perfom the necessary fine tuning without creating a Microsoft product related solution enter image description here enter image description here

How to apply filters to *ngFor?

I'm not sure when it came in but they already made slice pipe that will do that. It's well documented too.

<p *ngFor="let feature of content?.keyFeatures | slice:1:5">
   {{ feature.description }}

Counter in foreach loop in C#

It depends what you mean by "it". The iterator knows what index it's reached, yes - in the case of a List<T> or an array. But there's no general index within IEnumerator<T>. Whether it's iterating over an indexed collection or not is up to the implementation. Plenty of collections don't support direct indexing.

(In fact, foreach doesn't always use an iterator at all. If the compile-time type of the collection is an array, the compiler will iterate over it using array[0], array[1] etc. Likewise the collection can have a method called GetEnumerator() which returns a type with the appropriate members, but without any implementation of IEnumerable/IEnumerator in sight.)

Options for maintaining an index:

  • Use a for loop
  • Use a separate variable
  • Use a projection which projects each item to an index/value pair, e.g.

     foreach (var x in list.Select((value, index) => new { value, index }))
         // Use x.value and x.index in here
  • Use my SmartEnumerable class which is a little bit like the previous option

All but the first of these options will work whether or not the collection is naturally indexed.

How to initialize a dict with keys from a list and empty value in Python?

In many workflows where you want to attach a default / initial value for arbitrary keys, you don't need to hash each key individually ahead of time. You can use collections.defaultdict. For example:

from collections import defaultdict

d = defaultdict(lambda: None)

print(d[1])  # None
print(d[2])  # None
print(d[3])  # None

This is more efficient, it saves having to hash all your keys at instantiation. Moreover, defaultdict is a subclass of dict, so there's usually no need to convert back to a regular dictionary.

For workflows where you require controls on permissible keys, you can use dict.fromkeys as per the accepted answer:

d = dict.fromkeys([1, 2, 3, 4])

How to display hexadecimal numbers in C?

You can use the following snippet code:

int main(int argc, char *argv[]){
    unsigned int i;
    printf("decimal  hexadecimal\n");
    for (i = 0; i <= 256; i+=16)
        printf("%04d     0x%04X\n", i, i);
    return 0;

It prints both decimal and hexadecimal numbers in 4 places with zero padding.

Printing with sed or awk a line following a matching pattern

Actually sed -n '/pattern/{n;p}' filename will fail if the pattern match continuous lines:

$ seq 15 |sed -n '/1/{n;p}'

The expected answers should be:


My solution is:

$ sed -n -r 'x;/_/{x;p;x};x;/pattern/!s/.*//;/pattern/s/.*/_/;h' filename

For example:

$ seq 15 |sed -n -r 'x;/_/{x;p;x};x;/1/!s/.*//;/1/s/.*/_/;h'


  1. x;: at the beginning of each line from input, use x command to exchange the contents in pattern space & hold space.
  2. /_/{x;p;x};: if pattern space, which is the hold space actually, contains _ (this is just a indicator indicating if last line matched the pattern or not), then use x to exchange the actual content of current line to pattern space, use p to print current line, and x to recover this operation.
  3. x: recover the contents in pattern space and hold space.
  4. /pattern/!s/.*//: if current line does NOT match pattern, which means we should NOT print the NEXT following line, then use s/.*// command to delete all contents in pattern space.
  5. /pattern/s/.*/_/: if current line matches pattern, which means we should print the NEXT following line, then we need to set a indicator to tell sed to print NEXT line, so use s/.*/_/ to substitute all contents in pattern space to a _(the second command will use it to judge if last line matched the pattern or not).
  6. h: overwrite the hold space with the contents in pattern space; then, the content in hold space is ^_$ which means current line matches the pattern, or ^$, which means current line does NOT match the pattern.
  7. the fifth step and sixth step can NOT exchange, because after s/.*/_/, the pattern space can NOT match /pattern/, so the s/.*// MUST be executed!

How to remove \xa0 from string in Python?

I ran into this same problem pulling some data from a sqlite3 database with python. The above answers didn't work for me (not sure why), but this did: line = line.decode('ascii', 'ignore') However, my goal was deleting the \xa0s, rather than replacing them with spaces.

I got this from this super-helpful unicode tutorial by Ned Batchelder.

Is there an XSLT name-of element?

<xsl:for-each select="person">
  <xsl:for-each select="*">
    <xsl:value-of select="local-name()"/> : <xsl:value-of select="."/>

PDF to image using Java

jPDFImages is not free but a commercial library which converts PDF pages to images in JPEG, TIFF or PNG format. The output image size is customizable.

What does a circled plus mean?

It's an exclusive or (XOR). If I remember correctly, when doing bitwise mathematics the dot (.) means AND and the plus (+) means OR. Putting a circle around the plus to mean XOR is consistent with the style used for OR.

Hex to ascii string conversion

Few characters like alphabets i-o couldn't be converted into respective ASCII chars . like in string '6631653064316f30723161' corresponds to fedora . but it gives fedra

Just modify hex_to_int() function a little and it will work for all characters. modified function is

int hex_to_int(char c)
    if (c >= 97)
        c = c - 32;
    int first = c / 16 - 3;
    int second = c % 16;
    int result = first * 10 + second;
    if (result > 9) result--;
    return result;

Now try it will work for all characters.

How do I use FileSystemObject in VBA?

After importing the scripting runtime as described above you have to make some slighty modification to get it working in Excel 2010 (my version). Into the following code I've also add the code used to the user to pick a file.

Dim intChoice As Integer
Dim strPath As String

' Select one file
Application.FileDialog(msoFileDialogOpen).AllowMultiSelect = False

' Show the selection window
intChoice = Application.FileDialog(msoFileDialogOpen).Show

' Get back the user option
If intChoice <> 0 Then
    strPath = Application.FileDialog(msoFileDialogOpen).SelectedItems(1)
    Exit Sub
End If

Dim FSO As New Scripting.FileSystemObject
Dim fsoStream As Scripting.TextStream
Dim strLine As String

Set fsoStream = FSO.OpenTextFile(strPath)

Do Until fsoStream.AtEndOfStream = True
    strLine = fsoStream.ReadLine
    ' ... do your work ...

Set FSO = Nothing

Hope it help!

Best regards


when I try to open an HTML file through `http://localhost/xampp/htdocs/index.html` it says unable to connect to localhost

I just put an index.html file in /htdocs and type in - and up comes the html.

Add a folder "named Forum" and type in

django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module: No module named MySQLdb

When I set up Django development environment for PyCharm in Mac OS X Mountain Lion with python, mysql, sequel pro application I got error same as owner of this thread. However, my answer for them who is running python-mysqldb under Mac OS Mountain Lion x86_x64 (MySql and Python also should be same architecture) and already tried everything like pip and etc. In order fix this problem do following steps:

  1. Download MySql for Python from here
  2. Untar downloaded file. In terminal window do following: tar xvfz downloade.tar.
  3. cd /to untared directory
  4. Run sudo python install
  5. If you get error something like this: "Environment Error: /usr/local/bin/mysql_config not found" then try to add path ass follows: "export PATH=$PATH:/usr/local/mysql/bin". But id did not helped to me and I found another solution. In the end of command execution error output which looks like this:

    File "/path_to_file/MySQL-python-1.2.4b4/", line 25, in mysql_config raise EnvironmentError("%s not found" % (mysql_config.path,))

  6. Open with vim and go to line 25 (In your case it can be different unless if it is same version).

  7. Line 25 should look like this after your editing unless your mysql have symbolic link like follows '/usr/local/mysql/bin/':

    f = popen("%s --%s" % ('/usr/local/mysql/bin/mysql_config', what))

  8. After this I got another error as following:

    django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module: dlopen(/Library/Python/2.7/site-packages/MySQL_python-1.2.4b4-py2.7-macosx-10.8-intel.egg/, 2): Library not loaded: libmysqlclient.18.dylib Referenced from: /Library/Python/2.7/site-packages/MySQL_python-1.2.4b4-py2.7-macosx-10.8-intel.egg/ Reason: image not found

  9. Finally I did following in console:

    sudo ln -s /usr/local/mysql/lib/libmysqlclient.18.dylib /usr/lib/libmysqlclient.18.dylib

Currently everything works fine. So I hope it will be helpful for somebody who uses Mac. :)

Java - Including variables within strings?

This is called string interpolation; it doesn't exist as such in Java.

One approach is to use String.format:

String string = String.format("A string %s", aVariable);

Another approach is to use a templating library such as Velocity or FreeMarker.

Create a git patch from the uncommitted changes in the current working directory

I like:

git format-patch HEAD~<N>

where <N> is number of last commits to save as patches.

The details how to use the command are in the DOC

Here you can find how to apply them then.

UPD For those who did not get the idea of format-patch
Add alias:

git config --global alias.make-patch '!bash -c "cd ${GIT_PREFIX};git add .;git commit -m ''uncommited''; git format-patch HEAD~1; git reset HEAD~1"'

Then at any directory of your project repository run:

git make-patch

This command will create 0001-uncommited.patch at your current directory. Patch will contain all the changes and untracked files that are visible to next command:

git status .

How to include js file in another js file?

You need to write a document.write object:

document.write('<script type="text/javascript" src="file.js" ></script>');

and place it in your main javascript file

Edit line thickness of CSS 'underline' attribute

My Solution :

    display: inline-block;
    border-bottom: 1px solid;
    padding-bottom: 0;
    line-height: 70%;

You can adjust underline position with line-height value, underline thickness and style with border-bottom.

Beware to disable default underline behavior if you want to underline an href.

Getting the difference between two Dates (months/days/hours/minutes/seconds) in Swift

import Foundation

extension DateComponents {

    func dateComponentsToTimeString() -> String {

        var hour = "\(self.hour!)"
        var minute = "\(self.minute!)"
        var second = "\(self.second!)"

        if self.hour! < 10 { hour = "0" + hour }
        if self.minute! < 10 { minute = "0" + minute }
        if self.second! < 10 { second = "0" + second }

        let str = "\(hour):\(minute):\(second)"
        return str


extension Date {

    func offset(from date: Date)-> DateComponents {
        let components = Set<Calendar.Component>([.second, .minute, .hour, .day, .month, .year])
        let differenceOfDate = Calendar.current.dateComponents(components, from: date, to: self)
        return differenceOfDate


var durationString: String {
        return self.endTime.offset(from: self.startTime).dateComponentsToTimeString()

Return multiple values from a function, sub or type?

you can return 2 or more values to a function in VBA or any other visual basic stuff but you need to use the pointer method called Byref. See my example below. I will make a function to add and subtract 2 values say 5,6

sub Macro1
    ' now you call the function this way
    dim o1 as integer, o2 as integer
    AddSubtract 5, 6, o1, o2
    msgbox o2
    msgbox o1
end sub

function AddSubtract(a as integer, b as integer, ByRef sum as integer, ByRef dif as integer)
    sum = a + b
    dif = b - 1
end function

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

This is the technique I've used with great success:

=TRIM(RIGHT(SUBSTITUTE(A1, " ", REPT(" ", 100)), 100))

To get the first word in a string, just change from RIGHT to LEFT

=TRIM(LEFT(SUBSTITUTE(A1, " ", REPT(" ", 100)), 100))

Also, replace A1 by the cell holding the text.

What does "exec sp_reset_connection" mean in Sql Server Profiler?

Like the other answers said, sp_reset_connection indicates that connection pool is being reused. Be aware of one particular consequence!

Jimmy Mays' MSDN Blog said:

sp_reset_connection does NOT reset the transaction isolation level to the server default from the previous connection's setting.

UPDATE: Starting with SQL 2014, for client drivers with TDS version 7.3 or higher, the transaction isolation levels will be reset back to the default.

ref: SQL Server: Isolation level leaks across pooled connections

Here is some additional information:

What does sp_reset_connection do?

Data access API's layers like ODBC, OLE-DB and System.Data.SqlClient all call the (internal) stored procedure sp_reset_connection when re-using a connection from a connection pool. It does this to reset the state of the connection before it gets re-used, however nowhere is documented what things get reset. This article tries to document the parts of the connection that get reset.

sp_reset_connection resets the following aspects of a connection:

  • All error states and numbers (like @@error)

  • Stops all EC's (execution contexts) that are child threads of a parent EC executing a parallel query

  • Waits for any outstanding I/O operations that is outstanding

  • Frees any held buffers on the server by the connection

  • Unlocks any buffer resources that are used by the connection

  • Releases all allocated memory owned by the connection

  • Clears any work or temporary tables that are created by the connection

  • Kills all global cursors owned by the connection

  • Closes any open SQL-XML handles that are open

  • Deletes any open SQL-XML related work tables

  • Closes all system tables

  • Closes all user tables

  • Drops all temporary objects

  • Aborts open transactions

  • Defects from a distributed transaction when enlisted

  • Decrements the reference count for users in current database which releases shared database locks

  • Frees acquired locks

  • Releases any acquired handles

  • Resets all SET options to the default values

  • Resets the @@rowcount value

  • Resets the @@identity value

  • Resets any session level trace options using dbcc traceon()

  • Resets CONTEXT_INFO to NULL in SQL Server 2005 and newer [ not part of the original article ]

sp_reset_connection will NOT reset:

  • Security context, which is why connection pooling matches connections based on the exact connection string

  • Application roles entered using sp_setapprole, since application roles could not be reverted at all prior to SQL Server 2005. Starting in SQL Server 2005, app roles can be reverted, but only with additional information that is not part of the session. Before closing the connection, application roles need to be manually reverted via sp_unsetapprole using a "cookie" value that is captured when sp_setapprole is executed.

Note: I am including the list here as I do not want it to be lost in the ever transient web.

How can I increase a scrollbar's width using CSS?

This sets the scrollbar width:

::-webkit-scrollbar {
  width: 8px;   // for vertical scroll bar
  height: 8px;  // for horizontal scroll bar

// for Firefox add this class as well
  scrollbar-width: thin; // auto | thin | none | <length>;

How can I check the extension of a file?


import shutil, os

source = ['test_sound.flac','ts.mp3']

for files in source:
  fileName,fileExtension = os.path.splitext(files)

  if fileExtension==".flac" :
    print 'This file is flac file %s' %files
  elif  fileExtension==".mp3":
    print 'This file is mp3 file %s' %files
    print 'Format is not valid'

How can I save multiple documents concurrently in Mongoose/Node.js?

Add a file called mongoHelper.js

var MongoClient = require('mongodb').MongoClient;

MongoClient.saveAny = function(data, collection, callback)
    if(data instanceof Array)
        saveRecords(data,collection, callback);
        saveRecord(data,collection, callback);

function saveRecord(data, collection, callback)
        function(err, result)
                throw new Error(err);
function saveRecords(data, collection, callback)
function save(data, collection, callback)
        function(err, result)
                throw new Error(err);
            if(data.length > 0)
                save(data, collection, callback);

module.exports = MongoClient;

Then in your code change you requires to

var MongoClient = require("./mongoHelper.js");

Then when it is time to save call (after you have connected and retrieved the collection)

MongoClient.saveAny(data, collection, function(){db.close();});

You can change the error handling to suit your needs, pass back the error in the callback etc.

Kill detached screen session

List screens:

screen -list


There is a screen on:
23536.pts-0.wdzee       (10/04/2012 08:40:45 AM)        (Detached)
1 Socket in /var/run/screen/S-root.

Kill screen session:

screen -S 23536 -X quit

How can I access localhost from another computer in the same network?

localhost is a special hostname that almost always resolves to If you ask someone else to connect to http://localhost they'll be connecting to their computer instead or yours.

To share your web server with someone else you'll need to find your IP address or your hostname and provide that to them instead. On windows you can find this with ipconfig /all on a command line.

You'll also need to make sure any firewalls you may have configured allow traffic on port 80 to connect to the WAMP server.

How to use JavaScript to change div backgroundColor

var div = document.getElementById( 'div_id' );
div.onmouseover = function() { = 'green';
  var h2s = this.getElementsByTagName( 'h2' );
  h2s[0].style.backgroundColor = 'blue';
div.onmouseout = function() { = 'transparent';
  var h2s = this.getElementsByTagName( 'h2' );
  h2s[0].style.backgroundColor = 'transparent';

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

Here is an extension method that will convert an object to a ViewDataDictionary.

public static ViewDataDictionary ToViewDataDictionary(this object values)
    var dictionary = new ViewDataDictionary();
    foreach (PropertyDescriptor property in TypeDescriptor.GetProperties(values))
        dictionary.Add(property.Name, property.GetValue(values));
    return dictionary;

You can then use it in your view like so:

@Html.Partial("_MyPartial", new
    Property1 = "Value1",
    Property2 = "Value2"

Which is much nicer than the new ViewDataDictionary { { "Property1", "Value1" } , { "Property2", "Value2" }} syntax.

Then in your partial view, you can use ViewBag to access the properties from a dynamic object rather than indexed properties, e.g.


transform object to array with lodash

Object to Array

Of all the answers I think this one is the best:

let arr = Object.entries(obj).map(([key, val]) => ({ key, ...val }))

that transforms:

  a: { p: 1, q: 2},
  b: { p: 3, q: 4}


  { key: 'a', p: 1, q: 2 }, 
  { key: 'b', p: 3, q: 4 }

Array to Object

To transform back:

let obj = arr.reduce((obj, { key, ...val }) => { obj[key] = { ...val }; return obj; }, {})

To transform back keeping the key in the value:

let obj = arr.reduce((obj, { key, ...val }) => { obj[key] = { key, ...val }; return obj; }, {})

Will give:

  a: { key: 'a', p: 1, q: 2 },
  b: { key: 'b', p: 3, q: 4 }

For the last example you can also use lodash _.keyBy(arr, 'key') or _.keyBy(arr, i => i.key).

"Uncaught Error: [$injector:unpr]" with angular after deployment

This problem occurs when the controller or directive are not specified as a array of dependencies and function. For example

angular.module("appName").directive('directiveName', function () {
    return {
        restrict: 'AE',
        templateUrl: 'calender.html',
        controller: function ($scope) {
            $scope.selectThisOption = function () {
                // some code

When minified The '$scope' passed to the controller function is replaced by a single letter variable name . This will render angular clueless of the dependency . To avoid this pass the dependency name along with the function as a array.

angular.module("appName").directive('directiveName', function () {
    return {
        restrict: 'AE',
        templateUrl: 'calender.html'
        controller: ['$scope', function ($scope) { //<-- difference
            $scope.selectThisOption = function () {
                // some code

Angular 2 TypeScript how to find element in Array

Use this code in your service:

return this.getReports(accessToken)
        .then(reports => reports.filter(report => === id)[0]);

Using Python's list index() method on a list of tuples or objects?

You can do this with a list comprehension and index()

tuple_list = [("pineapple", 5), ("cherry", 7), ("kumquat", 3), ("plum", 11)]
[x[0] for x in tuple_list].index("kumquat")
[x[1] for x in tuple_list].index(7)

react-native - Fit Image in containing View, not the whole screen size

I could not get the example working using the resizeMode properties of Image, but because the images will all be square there is a way to do it using the Dimensions of the window along with flexbox.

Set flexDirection: 'row', and flexWrap: 'wrap', then they will all line up as long as they are all the same dimensions.

I set it up here

"use strict";

var React = require("react-native");
var {
} = React;

var deviceWidth = Dimensions.get("window").width;
var temp = "";
var SampleApp = React.createClass({
  render: function() {
    var images = [];

    for (var i = 0; i < 10; i++) {
        <TouchableOpacity key={i} activeOpacity={0.75} style={styles.item}>
          <Image style={styles.image} source={{ uri: temp }} />

    return (
      <ScrollView style={{ flex: 1 }}>
        <View style={styles.container}>

"elseif" syntax in JavaScript

Actually, technically when indented properly, it would be:

if (condition) {
} else {
    if (condition) {
    } else {

There is no else if, strictly speaking.

(Update: Of course, as pointed out, the above is not considered good style.)

How can I debug what is causing a connection refused or a connection time out?

The problem

The problem is in the network layer. Here are the status codes explained:

  • Connection refused: The peer is not listening on the respective network port you're trying to connect to. This usually means that either a firewall is actively denying the connection or the respective service is not started on the other site or is overloaded.

  • Connection timed out: During the attempt to establish the TCP connection, no response came from the other side within a given time limit. In the context of urllib this may also mean that the HTTP response did not arrive in time. This is sometimes also caused by firewalls, sometimes by network congestion or heavy load on the remote (or even local) site.

In context

That said, it is probably not a problem in your script, but on the remote site. If it's occuring occasionally, it indicates that the other site has load problems or the network path to the other site is unreliable.

Also, as it is a problem with the network, you cannot tell what happened on the other side. It is possible that the packets travel fine in the one direction but get dropped (or misrouted) in the other.

It is also not a (direct) DNS problem, that would cause another error (Name or service not known or something similar). It could however be the case that the DNS is configured to return different IP addresses on each request, which would connect you (DNS caching left aside) to different addresses hosts on each connection attempt. It could in turn be the case that some of these hosts are misconfigured or overloaded and thus cause the aforementioned problems.

Debugging this

As suggested in the another answer, using a packet analyzer can help to debug the issue. You won't see much however except the packets reflecting exactly what the error message says.

To rule out network congestion as a problem you could use a tool like mtr or traceroute or even ping to see if packets get lost to the remote site. Note that, if you see loss in mtr (and any traceroute tool for that matter), you must always consider the first host where loss occurs (in the route from yours to remote) as the one dropping packets, due to the way ICMP works. If the packets get lost only at the last hop over a long time (say, 100 packets), that host definetly has an issue. If you see that this behaviour is persistent (over several days), you might want to contact the administrator.

Loss in a middle of the route usually corresponds to network congestion (possibly due to maintenance), and there's nothing you could do about it (except whining at the ISP about missing redundance).

If network congestion is not a problem (i.e. not more than, say, 5% of the packets get lost), you should contact the remote server administrator to figure out what's wrong. He may be able to see relevant infos in system logs. Running a packet analyzer on the remote site might also be more revealing than on the local site. Checking whether the port is open using netstat -tlp is definetly recommended then.

HTML Best Practices: Should I use &rsquo; or the special keyboard shortcut?

If your text will be consumed by non-browsers then it's safer to type the character with the keyboard-combo option shift right bracket because &rsquo; will not be transformed into an apostrophe by a regular XML or JSON parser. (e.g. if you are serving this content to native Android/iOS apps).

Matplotlib connect scatterplot points with line - Python

For red lines an points

plt.plot(dates, values, '.r-') 

or for x markers and blue lines

plt.plot(dates, values, 'xb-')

Convert string to List<string> in one line?

I prefer this because it prevents a single item list with an empty item if your source string is empty:

  IEnumerable<string> namesList = 
      !string.isNullOrEmpty(names) ? names.Split(',') : Enumerable.Empty<string>();

Oracle SQL Developer and PostgreSQL

I got the list of databases to populate by putting my username in the Username field (no password) and clicking "Choose Database". Doesn't work with a blank Username field, I can only connect to my user database that way.

(This was with SQL Developer,, and postgresql-9.3-1100.jdbc41.jar, FWIW.)

angularjs - using {{}} binding inside ng-src but ng-src doesn't load

Changing the ng-src value is actually very simple. Like this:

<html ng-app>
<script src=""></script>
<img ng-src="{{img_url}}">
<button ng-click="img_url = ''">Click</button>

Here is a jsFiddle of a working example:

Set default option in mat-select

Using Form Model (Reactive Forms)

--- Html code--
<form [formGroup]="patientCategory">
<mat-form-field class="full-width">
    <mat-select placeholder="Category" formControlName="patientCategory">
        <mat-option *ngFor="let category of patientCategories" [value]="category">

----ts code ---

ngOnInit() {

        this.patientCategory ={
            patientCategory: [null, Validators.required]

      const toSelect = "Your Default Value";

With out form Model

--- html code --
  <mat-label>Select an option</mat-label>
  <mat-select [(value)]="selected">
    <mat-option value="option1">Option 1</mat-option>
    <mat-option value="option2">Option 2</mat-option>
    <mat-option value="option3">Option 3</mat-option>

---- ts code -- selected = 'option1'; Here take care about type of the value assigning

Cannot attach the file *.mdf as database

I recently ran into the same problem. Here is one thing to check. in visual studio there are three place we should check and remove the database.

1. Solution Explorer's App_Data folder
2. Server Explorer's Data Connection menu
3. SQL Server Object Explorer

When I delete database from the first two point, the error still occurs. So, I needed to delete the database from the SQL Server Object Explorer as well. Then I could easily run the 'update-database' command without error. Hope this helps.

How to change context root of a dynamic web project in Eclipse?

Setting the path to nothing in the Eclipse web modules edit dialog enabled me to access the project without any path component in the URL (i.e. ROOT)

You can reach the web modules edit dialog by pressing F3 if you select Tomcat in the "Servers" view or by double clicking on it.

Some screenshots:

Windows command to convert Unix line endings?

Late to the party, but there is still no correct answer using a FOR /F loop.
(But you don't need a FOR loop at all, the solution from @TampaHaze works too and is much simpler)

The answer from @IR relevant has some drawbacks.
It drops the exclamation marks and can also drop carets.

@echo off
    setlocal Disabledelayedexpansion
    for /f "tokens=* delims=" %%L in ('findstr /n "^" "%~1"') do (
        set "line=%%L"
        setlocal enabledelayedexpansion
        set "line=!line:*:=!"
) > file.dos

The trick is to use findstr /n to prefix each line with <line number>:, this avoids skipping of empty lines or lines beginning with ;.
To remove the <number>: the FOR "tokens=1,* delims=:" option can't be used, because this would remove all leading colons in a line, too.

Therefore the line number is removed by set "line=!line:*:=!", this requires EnableDelayedExpansion.
But with EnableDelayedExpansion the line set "line=%%L" would drop all exclamation marks and also carets (only when exclams are in the line).

That's why I disable the delayed expansion before and only enable it for the two lines, where it is required.

The (echo(!line!) looks strange, but has the advantage, that echo( can display any content in !line! and the outer parenthesis avoids accidentials whitespaces at the line end.

JavaScript: filter() for Objects

First of all, it's considered bad practice to extend Object.prototype. Instead, provide your feature as utility function on Object, just like there already are Object.keys, Object.assign,, ...etc.

I provide here several solutions:

  1. Using reduce and Object.keys
  2. As (1), in combination with Object.assign
  3. Using map and spread syntax instead of reduce
  4. Using Object.entries and Object.fromEntries

1. Using reduce and Object.keys

With reduce and Object.keys to implement the desired filter (using ES6 arrow syntax):

Object.filter = (obj, predicate) => _x000D_
          .filter( key => predicate(obj[key]) )_x000D_
          .reduce( (res, key) => (res[key] = obj[key], res), {} );_x000D_
// Example use:_x000D_
var scores = {_x000D_
    John: 2, Sarah: 3, Janet: 1_x000D_
var filtered = Object.filter(scores, score => score > 1); _x000D_

Note that in the above code predicate must be an inclusion condition (contrary to the exclusion condition the OP used), so that it is in line with how Array.prototype.filter works.

2. As (1), in combination with Object.assign

In the above solution the comma operator is used in the reduce part to return the mutated res object. This could of course be written as two statements instead of one expression, but the latter is more concise. To do it without the comma operator, you could use Object.assign instead, which does return the mutated object:

Object.filter = (obj, predicate) => _x000D_
          .filter( key => predicate(obj[key]) )_x000D_
          .reduce( (res, key) => Object.assign(res, { [key]: obj[key] }), {} );_x000D_
// Example use:_x000D_
var scores = {_x000D_
    John: 2, Sarah: 3, Janet: 1_x000D_
var filtered = Object.filter(scores, score => score > 1); _x000D_

3. Using map and spread syntax instead of reduce

Here we move the Object.assign call out of the loop, so it is only made once, and pass it the individual keys as separate arguments (using the spread syntax):

Object.filter = (obj, predicate) => _x000D_
                    .filter( key => predicate(obj[key]) )_x000D_
                    .map( key => ({ [key]: obj[key] }) ) );_x000D_
// Example use:_x000D_
var scores = {_x000D_
    John: 2, Sarah: 3, Janet: 1_x000D_
var filtered = Object.filter(scores, score => score > 1); _x000D_

4. Using Object.entries and Object.fromEntries

As the solution translates the object to an intermediate array and then converts that back to a plain object, it would be useful to make use of Object.entries (ES2017) and the opposite (i.e. create an object from an array of key/value pairs) with Object.fromEntries (ES2019).

It leads to this "one-liner" method on Object:

Object.filter = (obj, predicate) => _x000D_
// Example use:_x000D_
var scores = {_x000D_
    John: 2, Sarah: 3, Janet: 1_x000D_
var filtered = Object.filter(scores, ([name, score]) => score > 1); _x000D_

The predicate function gets a key/value pair as argument here, which is a bit different, but allows for more possibilities in the predicate function's logic.

error: invalid type argument of ‘unary *’ (have ‘int’)

Since c is holding the address of an integer pointer, its type should be int**:

int **c;
c = &a;

The entire program becomes:

#include <stdio.h>                                                              
int main(){
    int b=10;
    int *a;
    int **c;
    printf("%d",(**c));   //successfully prints 10
    return 0;

pandas DataFrame: replace nan values with average of columns

Directly use df.fillna(df.mean()) to fill all the null value with mean

If you want to fill null value with mean of that column then you can use this

suppose x=df['Item_Weight'] here Item_Weight is column name

here we are assigning (fill null values of x with mean of x into x)

df['Item_Weight'] = df['Item_Weight'].fillna((df['Item_Weight'].mean()))

If you want to fill null value with some string then use

here Outlet_size is column name

df.Outlet_Size = df.Outlet_Size.fillna('Missing')

How to get row number in dataframe in Pandas?

df.loc[df.LastName == 'Smith']

will return the row

    ClientID    LastName
1   67          Smith


df.loc[df.LastName == 'Smith'].index

will return the index

Int64Index([1], dtype='int64')

NOTE: Column names 'LastName' and 'Last Name' or even 'lastname' are three unique names. The best practice would be to first check the exact name using df.columns. If you really need to strip the column names of all the white spaces, you can first do

df.columns = [x.strip().replace(' ', '') for x in df.columns]

Eclipse - Unable to install breakpoint due to missing line number attributes

I had the same error in my Eclipse IDE. But it seems it is an ignorable error. I pressed Ok on the error dialogue box & continued. My breakpoints were reached & i was able to debug further.

How to get current time in milliseconds in PHP?

Use microtime. This function returns a string separated by a space. The first part is the fractional part of seconds, the second part is the integral part. Pass in true to get as a number:

var_dump(microtime());       // string(21) "0.89115400 1283846202"
var_dump(microtime(true));   // float(1283846202.89)

Beware of precision loss if you use microtime(true).

There is also gettimeofday that returns the microseconds part as an integer.

array(4) {

Finding the source code for built-in Python functions?

The iPython shell makes this easy: function? will give you the documentation. function?? shows also the code. BUT this only works for pure python functions.

Then you can always download the source code for the (c)Python.

If you're interested in pythonic implementations of core functionality have a look at PyPy source.

How to select the first, second, or third element with a given class name?

use nth-child(item number) EX

<div class="parent_class">
    <div class="myclass">my text1</div>
    some other code+containers...

    <div class="myclass">my text2</div>
    some other code+containers...

    <div class="myclass">my text3</div>
    some other code+containers...
.parent_class:nth-child(1) { };
.parent_class:nth-child(2) { };
.parent_class:nth-child(3) { };


:nth-of-type(item number) same your code

.myclass:nth-of-type(1) { };
.myclass:nth-of-type(2) { };
.myclass:nth-of-type(3) { };

read file from assets

Here is a way to get an InputStream for a file in the assets folder without a Context, Activity, Fragment or Application. How you get the data from that InputStream is up to you. There are plenty of suggestions for that in other answers here.


val inputStream ="assets/your_file.ext")


InputStream inputStream = ClassLoader.class.getClassLoader().getResourceAsStream("assets/your_file.ext");

All bets are off if a custom ClassLoader is in play.


You are correct. You did exactly the right thing, checking the query plan rather than trying to second-guess the optimiser. :-)

jQuery Cross Domain Ajax

Unfortunately it seems that this web service returns JSON which contains another JSON - parsing contents of the inner JSON is successful. The solution is ugly but works for me. JSON.parse(...) tries to convert the entire string and fails. Assuming that you always get the answer starting with {"AuthenticateUserResult": and interesting data is after this, try:

    type: 'GET',
    dataType: "text",
    crossDomain: true,
    url: "",
    success: function (responseData, textStatus, jqXHR) {
        var authResult = JSON.parse(
                '{"AuthenticateUserResult":"', ''
            ).replace('}"}', '}')
    error: function (responseData, textStatus, errorThrown) {
        alert('POST failed.');

It is very important that dataType must be text to prevent auto-parsing of malformed JSON you are receiving from web service.

Basically, I'm wiping out the outer JSON by removing topmost braces and key AuthenticateUserResult along with leading and trailing quotation marks. The result is a well formed JSON, ready for parsing.

How do I get the SharedPreferences from a PreferenceActivity in Android?

If you don't have access to getDefaultSharedPreferenes(), you can use getSharedPreferences(name, mode) instead, you just have to pass in the right name.

Android creates this name (possibly based on the package name of your project?). You can get it by putting the following code in a SettingsActivity onCreate(), and seeing what preferencesName is.

String preferencesName = this.getPreferenceManager().getSharedPreferencesName();

The string should be something like com.example.projectname_preferences. Hard code that somewhere in your project, and pass it in to getSharedPreferences() and you should be good to go.

Zookeeper connection error

I was able to start with zookeeper and kafka having 2 nodes each. I got the error because i had started zookeeper with ./ instead of the kafka wrapper bin/ config/

Java generics - ArrayList initialization

The key lies in the differences between references and instances and what the reference can promise and what the instance can really do.

ArrayList<A> a = new ArrayList<A>();

Here a is a reference to an instance of a specific type - exactly an array list of As. More explicitly, a is a reference to an array list that will accept As and will produce As. new ArrayList<A>() is an instance of an array list of As, that is, an array list that will accept As and will produce As.

ArrayList<Integer> a = new ArrayList<Number>(); 

Here, a is a reference to exactly an array list of Integers, i.e. exactly an array list that can accept Integers and will produce Integers. It cannot point to an array list of Numbers. That array list of Numbers can not meet all the promises of ArrayList<Integer> a (i.e. an array list of Numbers may produce objects that are not Integers, even though its empty right then).

ArrayList<Number> a = new ArrayList<Integer>(); 

Here, declaration of a says that a will refer to exactly an array list of Numbers, that is, exactly an array list that will accept Numbers and will produce Numbers. It cannot point to an array list of Integers, because the type declaration of a says that a can accept any Number, but that array list of Integers cannot accept just any Number, it can only accept Integers.

ArrayList<? extends Object> a= new ArrayList<Object>();

Here a is a (generic) reference to a family of types rather than a reference to a specific type. It can point to any list that is member of that family. However, the trade-off for this nice flexible reference is that they cannot promise all of the functionality that it could if it were a type-specific reference (e.g. non-generic). In this case, a is a reference to an array list that will produce Objects. But, unlike a type-specific list reference, this a reference cannot accept any Object. (i.e. not every member of the family of types that a can point to can accept any Object, e.g. an array list of Integers can only accept Integers.)

ArrayList<? super Integer> a = new ArrayList<Number>();

Again, a is a reference to a family of types (rather than a single specific type). Since the wildcard uses super, this list reference can accept Integers, but it cannot produce Integers. Said another way, we know that any and every member of the family of types that a can point to can accept an Integer. However, not every member of that family can produce Integers.

PECS - Producer extends, Consumer super - This mnemonic helps you remember that using extends means the generic type can produce the specific type (but cannot accept it). Using super means the generic type can consume (accept) the specific type (but cannot produce it).

ArrayList<ArrayList<?>> a

An array list that holds references to any list that is a member of a family of array lists types.

= new ArrayList<ArrayList<?>>(); // correct

An instance of an array list that holds references to any list that is a member of a family of array lists types.

ArrayList<?> a

An reference to any array list (a member of the family of array list types).

= new ArrayList<?>()

ArrayList<?> refers to any type from a family of array list types, but you can only instantiate a specific type.

See also How can I add to List<? extends Number> data structures?

sudo: port: command not found

On my machine, port is in /opt/local/bin/port - try typing that into a terminal on its own.

Django datetime issues (

Instead of using you should be really using from django.utils.timezone import now


so go for something like this:

from django.utils.timezone import now

created_date = models.DateTimeField(default=now, editable=False)

append option to select menu?


<select id="mySelect">
    <option value="volvo">Volvo</option>
    <option value="saab">Saab</option>
    <option value="mercedes">Mercedes</option>
    <option value="audi">Audi</option>


 var mySelect = document.getElementById('mySelect'),
    newOption = document.createElement('option');

newOption.value = 'bmw';

// Not all browsers support textContent (W3C-compliant)
// When available, textContent is faster (see
if (typeof newOption.textContent === 'undefined')
    newOption.innerText = 'BMW';
    newOption.textContent = 'BMW';


Demo →

Changing SQL Server collation to case insensitive from case sensitive?

You can do that but the changes will affect for new data that is inserted on the database. On the long run follow as suggested above.

Also there are certain tricks you can override the collation, such as parameters for stored procedures or functions, alias data types, and variables are assigned the default collation of the database. To change the collation of an alias type, you must drop the alias and re-create it.

You can override the default collation of a literal string by using the COLLATE clause. If you do not specify a collation, the literal is assigned the database default collation. You can use DATABASEPROPERTYEX to find the current collation of the database.

You can override the server, database, or column collation by specifying a collation in the ORDER BY clause of a SELECT statement.

Multiple conditions with CASE statements

Another way based on amadan:

    SELECT * FROM [Purchasing].[Vendor] WHERE  

      ( (@url IS null OR @url = '' OR @url = 'ALL') and   PurchasingWebServiceURL LIKE '%')

       ( @url = 'blank' and  PurchasingWebServiceURL = '')
        (@url = 'fail' and  PurchasingWebServiceURL NOT LIKE '%treyresearch%')
    or( (@url not in ('fail','blank','','ALL') and @url is not null and 
          PurchasingWebServiceUrl Like '%'+@ur+'%') 

HTML: Select multiple as dropdown

It's quite unpractical to make multiple select with size 1. think about it. I made a fiddle here:

<select name="test" multiple>

Try to explore other options such as using checkboxes to achieve your goal.

Deleting elements from std::set while iterating

I think using the STL method 'remove_if' from could help to prevent some weird issue when trying to attempt to delete the object that is wrapped by the iterator.

This solution may be less efficient.

Let's say we have some kind of container, like vector or a list called m_bullets:

Bullet::Ptr is a shared_pr<Bullet>

'it' is the iterator that 'remove_if' returns, the third argument is a lambda function that is executed on every element of the container. Because the container contains Bullet::Ptr, the lambda function needs to get that type(or a reference to that type) passed as an argument.

 auto it = std::remove_if(m_bullets.begin(), m_bullets.end(), [](Bullet::Ptr bullet){
    // dead bullets need to be removed from the container
    if (!bullet->isAlive()) {
        // lambda function returns true, thus this element is 'removed'
        return true;
        // in the other case, that the bullet is still alive and we can do
        // stuff with it, like rendering and what not.
        bullet->render(); // while checking, we do render work at the same time
        // then we could either do another check or directly say that we don't
        // want the bullet to be removed.
        return false;
// The interesting part is, that all of those objects were not really
// completely removed, as the space of the deleted objects does still 
// exist and needs to be removed if you do not want to manually fill it later 
// on with any other objects.
// erase dead bullets
m_bullets.erase(it, m_bullets.end());

'remove_if' removes the container where the lambda function returned true and shifts that content to the beginning of the container. The 'it' points to an undefined object that can be considered garbage. Objects from 'it' to m_bullets.end() can be erased, as they occupy memory, but contain garbage, thus the 'erase' method is called on that range.

How to open a specific port such as 9090 in Google Compute Engine

Creating firewall rules

Please review the firewall rule components [1] if you are unfamiliar with firewall rules in GCP. Firewall rules are defined at the network level, and only apply to the network where they are created; however, the name you choose for each of them must be unique to the project.

For Cloud Console:

  1. Go to the Firewall rules page in the Google Cloud Platform Console.
  2. Click Create firewall rule.
  3. Enter a Name for the firewall rule. This name must be unique for the project.
  4. Specify the Network where the firewall rule will be implemented.
  5. Specify the Priority of the rule. The lower the number, the higher the priority.
  6. For the Direction of traffic, choose ingress or egress.
  7. For the Action on match, choose allow or deny.
  8. Specify the Targets of the rule.

    • If you want the rule to apply to all instances in the network, choose All instances in the network.
    • If you want the rule to apply to select instances by network (target) tags, choose Specified target tags, then type the tags to which the rule should apply into the Target tags field.
    • If you want the rule to apply to select instances by associated service account, choose Specified service account, indicate whether the service account is in the current project or another one under Service account scope, and choose or type the service account name in the Target service account field.
  9. For an ingress rule, specify the Source filter:

    • Choose IP ranges and type the CIDR blocks into the Source IP ranges field to define the source for incoming traffic by IP address ranges. Use for a source from any network.
    • Choose Subnets then mark the ones you need from the Subnets pop-up button to define the source for incoming traffic by subnet name.
    • To limit source by network tag, choose Source tags, then type the network tags in to the Source tags field. For the limit on the number of source tags, see VPC Quotas and Limits. Filtering by source tag is only available if the target is not specified by service account. For more information, see filtering by service account tag.
    • To limit source by service account, choose Service account, indicate whether the service account is in the current project or another one under Service account scope, and choose or type the service account name in the Source service account field. Filtering by source service account is only available if the target is not specified by network tag. For more information, see filtering by service account vs. network tag.
    • Specify a Second source filter if desired. Secondary source filters cannot use the same filter criteria as the primary one.
  10. For an egress rule, specify the Destination filter:

    • Choose IP ranges and type the CIDR blocks into the Destination IP ranges field to define the destination for outgoing traffic by IP address ranges. Use to mean everywhere.
    • Choose Subnets then mark the ones you need from the Subnets pop-up button to define the destination for outgoing traffic by subnet name.
  11. Define the Protocols and ports to which the rule will apply:

    • Select Allow all or Deny all, depending on the action, to have the rule apply to all protocols and ports.

    • Define specific protocols and ports:

      • Select tcp to include the TCP protocol and ports. Enter all or a comma delimited list of ports, such as 20-22, 80, 8080.
      • Select udp to include the UDP protocol and ports. Enter all or a comma delimited list of ports, such as 67-69, 123.
      • Select Other protocols to include protocols such as icmp or sctp.
  12. (Optional) You can create the firewall rule but not enforce it by setting its enforcement state to disabled. Click Disable rule, then select Disabled.

  13. (Optional) You can enable firewall rules logging:

    • Click Logs > On.
    • Click Turn on.
  14. Click Create.

Link: [1]

Add a properties file to IntelliJ's classpath

For those of you who migrate from Eclipse to IntelliJ or the other way around here is a tip when working with property files or other resource files.

Its maddening (cost my a whole evening to find out) but both IDE's work quite different when it comes to looking for resource/propertty files when you want to run locally from your IDE or during debugging. (Packaging to a .jar is also quite different, but thats documented better.)

Suppose you have a relative path referral like this in your code:

new FileInputStream("");

(which is convenient if you work with env specific .properties files which you don't want to package along with your JAR)


(I use 13.1 , but could be valid for more versions)

The file needs to be at the PARENT dir of the project ROOT in order to be picked up at runtime like this in IntelliJ. (The project ROOT is where the /src folder resides in)


Eclipse is just happy when the file is at the project ROOT itself.

So IntelliJ expects .properties file to be 1 level higher then Eclipse when it is referenced like this !!

This also affects the way you have to execute your code when you have this same line of code ( new FileInputStream(""); ) in your exported .jar. When you want to be agile and don't want to package the .properties file with your jar you'll have to execute the jar like below in order to reference the .properties file correctly from the command line:


java -cp "/path/to_properties_file/:/path/to_jar/some.jar" com.bla.blabla.ClassContainingMainMethod


java -jar some.jar

where the Eclipse exported executable jar will just expect the referenced .properties file to be on the same location as where the .jar file is

How to fix org.hibernate.LazyInitializationException - could not initialize proxy - no Session

This means you are using JPA or hibernate in your code and performing modifying operation on DB without making the business logic transaction. So simple solution for this is mark your piece of code @Transactional

SyntaxError: Cannot use import statement outside a module

I had this issue when I was running migration

Its es5 vs es6 issue

Here is how I solved it

I run

npm install @babel/register

and add


at the top of my .sequelizerc file my

and go ahead to run my sequelize migrate. This is applicable to other things apart from sequelize

babel does the transpiling

How to rename uploaded file before saving it into a directory?

You can simply change the name of the file by changing the name of the file in the second parameter of move_uploaded_file.

Instead of

move_uploaded_file($_FILES["file"]["tmp_name"], "../img/imageDirectory/" . $_FILES["file"]["name"]);


$temp = explode(".", $_FILES["file"]["name"]);
$newfilename = round(microtime(true)) . '.' . end($temp);
move_uploaded_file($_FILES["file"]["tmp_name"], "../img/imageDirectory/" . $newfilename);

Changed to reflect your question, will product a random number based on the current time and append the extension from the originally uploaded file.

Is there a way to reduce the size of the git folder?

Don't know if it will shrink it, but after I run git clean, I often do git repack -ad as well, which reduces the number of pack files.

How can I get the source directory of a Bash script from within the script itself?

Here's an excerpt from my answer to shell script: check directory name and convert to lowercase in which I demonstrate not only how to solve this problem with very basic POSIX-specified utilities, I also address how to very simply store the function's results in a returned variable...

...Well, as you can see, with some help, I hit upon a pretty simple and very powerful solution:

I can pass the function a sort of messenger variable and dereference any explicit use of the resulting function's argument's $1 name with eval as necessary, and, upon the function routine's completion, I use eval and a backslashed quoting trick to assign my messenger variable the value I desire without ever having to know its name.

In full disclosure, ... (I found the messenger variable portion of this) and at Rich's sh tricks and I have also excerpted the relevant portion of his page below my own answer's excerpt.

... EXCERPT: ...

Though not strictly POSIX yet, realpath is a GNU core application since 2012. Full disclosure: never heard of it before I noticed it in the info coreutils TOC and immediately thought of [the linked] question, but using the following function as demonstrated should reliably, (soon POSIXLY?), and, I hope, efficiently provide its caller with an absolutely sourced $0:

% _abs_0() {
> o1="${1%%/*}"; ${o1:="${1}"}; ${o1:=`realpath -s "${1}"`}; eval "$1=\${o1}";
> }
% _abs_0 ${abs0:="${0}"} ; printf %s\\n "${abs0}"

It may be worth highlighting that this solution uses POSIX parameter expansion to first check if the path actually needs expanding and resolving at all before attempting to do so. This should return an absolutely sourced $0via a messenger variable (with the notable exception that it will preserve symlinks) as efficiently as I could imagine it could be done whether or not the path is already absolute. ...

(minor edit: before finding realpath in the docs, I had at least pared down my version of (the version below) not to depend on the time field (as it does in the first ps command), but, fair warning, after testing some I'm less convinced ps is fully reliable in its command path expansion capacity)

On the other hand, you could do this:

ps ww -fp $$ | grep -Eo '/[^:]*'"${0#*/}"

eval "abs0=${`ps ww -fp $$ | grep -Eo ' /'`#?}"

... And from Rich's sh tricks: ...

Returning strings from a shell function

As can be seen from the above pitfall of command substitution, standard output is not a good avenue for shell functions to return strings to their caller, unless the output is in a format where trailing newlines are insignificant. Certainly such practice is not acceptable for functions meant to deal with arbitrary strings. So, what can be done?

Try this:

func () {
body here
eval "$1=\${foo}"

Of course, ${foo} could be replaced by any sort of substitution. The key trick here is the eval line and the use of escaping. The “$1” is expanded when the argument to eval is constructed by the main command parser. But the “${foo}” is not expanded at this stage, because the “$” has been quoted. Instead, it’s expanded when eval evaluates its argument. If it’s not clear why this is important, consider how the following would be bad:

foo='hello ; rm -rf /'
eval "$dest=$foo"

But of course the following version is perfectly safe:

foo='hello ; rm -rf /'
eval "$dest=\$foo"

Note that in the original example, “$1” was used to allow the caller to pass the destination variable name as an argument the function. If your function needs to use the shift command, for instance to handle the remaining arguments as “$@”, then it may be useful to save the value of “$1” in a temporary variable at the beginning of the function.

Does C++ support 'finally' blocks? (And what's this 'RAII' I keep hearing about?)

I came up with a finally macro that can be used almost like¹ the finally keyword in Java; it makes use of std::exception_ptr and friends, lambda functions and std::promise, so it requires C++11 or above; it also makes use of the compound statement expression GCC extension, which is also supported by clang.

WARNING: an earlier version of this answer used a different implementation of the concept with many more limitations.

First, let's define a helper class.

#include <future>

template <typename Fun>
class FinallyHelper {
    template <typename T> struct TypeWrapper {};
    using Return = typename std::result_of<Fun()>::type;

    FinallyHelper(Fun body) {
        try {
            execute(TypeWrapper<Return>(), body);
        catch(...) {

    Return get() {
        return m_promise.get_future().get();

    template <typename T>
    void execute(T, Fun body) {

    void execute(TypeWrapper<void>, Fun body) {

    std::promise<Return> m_promise;

template <typename Fun>
FinallyHelper<Fun> make_finally_helper(Fun body) {
    return FinallyHelper<Fun>(body);

Then there's the actual macro.

#define try_with_finally for(auto __finally_helper = make_finally_helper([&] { try 
#define finally });                         \
        true;                               \
        ({return __finally_helper.get();})) \

It can be used like this:

void test() {
    try_with_finally {

    catch(const my_exception1&) {

    catch(const my_exception2&) {

    finally {

The use of std::promise makes it very easy to implement, but it probably also introduces quite a bit of unneeded overhead which could be avoided by reimplementing only the needed functionalities from std::promise.

¹ CAVEAT: there are a few things that don't work quite like the java version of finally. Off the top of my head:

  1. it's not possible to break from an outer loop with the break statement from within the try and catch()'s blocks, since they live within a lambda function;
  2. there must be at least one catch() block after the try: it's a C++ requirement;
  3. if the function has a return value other than void but there's no return within the try and catch()'s blocks, compilation will fail because the finally macro will expand to code that will want to return a void. This could be, err, avoided by having a finally_noreturn macro of sorts.

All in all, I don't know if I'd ever use this stuff myself, but it was fun playing with it. :)

Why are only a few video games written in Java?

I'm playing the Sims 3, and I did some poking around. The graphics engine is C++, while the scripting and behavior engine is C#/Mono. So while C++ is there for time critical bits, other stuff like .interaction, game logic, AI is in an object oriented managed language.

How to set -source 1.7 in Android Studio and Gradle

Always use latest SDK version to build:

compileSdkVersion 23

It does not affect runtime behavior, but give you latest programming features.

How to upload a file using Java HttpClient library working with PHP

There is my working solution for sending image with post, using apache http libraries (very important here is boundary add It won't work without it in my connection):

            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
            byte[] imageBytes = baos.toByteArray();

            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(StaticData.AMBAJE_SERVER_URL + StaticData.AMBAJE_ADD_AMBAJ_TO_GROUP);

            String boundary = "-------------" + System.currentTimeMillis();

            httpPost.setHeader("Content-type", "multipart/form-data; boundary="+boundary);

            ByteArrayBody bab = new ByteArrayBody(imageBytes, "pic.png");
            StringBody sbOwner = new StringBody(StaticData.loggedUserId, ContentType.TEXT_PLAIN);
            StringBody sbGroup = new StringBody("group", ContentType.TEXT_PLAIN);

            HttpEntity entity = MultipartEntityBuilder.create()
                    .addPart("group", sbGroup)
                    .addPart("owner", sbOwner)
                    .addPart("image", bab)


            try {
                HttpResponse response = httpclient.execute(httpPost);
                ...then reading response

Javascript onclick hide div

If you want to close it you can either hide it or remove it from the page. To hide it you would do some javascript like: = 'none';

To remove it you use removeChild


If you had a library like jQuery included then hiding or removing the div would be slightly easier:


One other thing, as your img is in an anchor the onclick event on the anchor is going to fire as well. As the href is set to # then the page will scroll back to the top of the page. Generally it is good practice that if you want a link to do something other than go to its href you should set the onclick event to return false;

How to convert a string variable containing time to time_t type in c++?

This should work:

int hh, mm, ss;
struct tm when = {0};

sscanf_s(date, "%d:%d:%d", &hh, &mm, &ss);

when.tm_hour = hh;
when.tm_min = mm;
when.tm_sec = ss;

time_t converted;
converted = mktime(&when);

Modify as needed.

Set up Python 3 build system with Sublime Text 3

Steps for configuring Sublime Text Editor3 for Python3 :-

  1. Go to preferences in the toolbar.
  2. Select Package Control.
  3. A pop up will open.
  4. Type/Select Package Control:Install Package.
  5. Wait for a minute till repositories are loading.
  6. Another Pop up will open.
  7. Search for Python 3.
  8. Now sublime text is set for Python3.
  9. Now go to Tools-> Build System.
  10. Select Python3.

Enjoy Coding.

TypeError: module.__init__() takes at most 2 arguments (3 given)

from Object import Object


From Class_Name import Class_name

If Object is a .py file.

How to fully delete a git repository created with init?

Git keeps all of its files in the .git directory. Just remove that one and init again.

If you can't find it, it's because it is hidden.

  • In Windows 7, you need to go to your folder, click on Organize on the top left, then click on Folder and search options, then click on the View tab and click on the Show hidden files, folders and drives radio button.

  • On a Mac OS:

    • Open a Terminal (via Spotlight: press CMD + SPACE, type terminal and press Enter) and run:

      defaults write AppleShowAllFiles 1 && killall Finder

      Note: The keyboard shortcut to show hidden files in Finder is CMD + SHIFT + . so it is no longer necessary to modify the finder config this way

    • You could also type cd (the space is important), drag and drop your git repo folder from Finder to the terminal window, press return, then type rm -fr .git, then return again.

  • On Ubuntu, use shortcut Ctrl + H.

Canvas width and height in HTML5

A canvas has 2 sizes, the dimension of the pixels in the canvas (it's backingstore or drawingBuffer) and the display size. The number of pixels is set using the the canvas attributes. In HTML

<canvas width="400" height="300"></canvas>

Or in JavaScript

someCanvasElement.width = 400;
someCanvasElement.height = 300;

Separate from that are the canvas's CSS style width and height


canvas {  /* or some other selector */
   width: 500px;
   height: 400px;

Or in JavaScript = "500px"; = "400px";

The arguably best way to make a canvas 1x1 pixels is to ALWAYS USE CSS to choose the size then write a tiny bit of JavaScript to make the number of pixels match that size.

function resizeCanvasToDisplaySize(canvas) {
   // look up the size the canvas is being displayed
   const width = canvas.clientWidth;
   const height = canvas.clientHeight;

   // If it's resolution does not match change it
   if (canvas.width !== width || canvas.height !== height) {
     canvas.width = width;
     canvas.height = height;
     return true;

   return false;

Why is this the best way? Because it works in most cases without having to change any code.

Here's a full window canvas:

const ctx = document.querySelector("#c").getContext("2d");_x000D_
function render(time) {_x000D_
  time *= 0.001;_x000D_
  ctx.fillStyle = "#DDE";_x000D_
  ctx.fillRect(0, 0, ctx.canvas.width, ctx.canvas.height);_x000D_;_x000D_
  const spacing = 64;_x000D_
  const size = 48;_x000D_
  const across = ctx.canvas.width / spacing + 1;_x000D_
  const down = ctx.canvas.height / spacing + 1;_x000D_
  const s = Math.sin(time);_x000D_
  const c = Math.cos(time);_x000D_
  for (let y = 0; y < down; ++y) {_x000D_
    for (let x = 0; x < across; ++x) {_x000D_
      ctx.setTransform(c, -s, s, c, x * spacing, y * spacing);_x000D_
      ctx.strokeRect(-size / 2, -size / 2, size, size);_x000D_
function resizeCanvasToDisplaySize(canvas) {_x000D_
   // look up the size the canvas is being displayed_x000D_
   const width = canvas.clientWidth;_x000D_
   const height = canvas.clientHeight;_x000D_
   // If it's resolution does not match change it_x000D_
   if (canvas.width !== width || canvas.height !== height) {_x000D_
     canvas.width = width;_x000D_
     canvas.height = height;_x000D_
     return true;_x000D_
   return false;_x000D_
body { margin: 0; }_x000D_
canvas { display: block; width: 100vw; height: 100vh; }
<canvas id="c"></canvas>

And Here's a canvas as a float in a paragraph

const ctx = document.querySelector("#c").getContext("2d");_x000D_
function render(time) {_x000D_
  time *= 0.001;_x000D_
  ctx.fillStyle = "#DDE";_x000D_
  ctx.fillRect(0, 0, ctx.canvas.width, ctx.canvas.height);_x000D_;_x000D_
  const spacing = 64;_x000D_
  const size = 48;_x000D_
  const across = ctx.canvas.width  / spacing + 1;_x000D_
  const down   = ctx.canvas.height / spacing + 1;_x000D_
  const s = Math.sin(time);_x000D_
  const c = Math.cos(time);_x000D_
  for (let y = 0; y <= down; ++y) {_x000D_
    for (let x = 0; x <= across; ++x) {_x000D_
      ctx.setTransform(c, -s, s, c, x * spacing, y * spacing);_x000D_
      ctx.strokeRect(-size / 2, -size / 2, size, size);_x000D_
function resizeCanvasToDisplaySize(canvas) {_x000D_
   // look up the size the canvas is being displayed_x000D_
   const width = canvas.clientWidth;_x000D_
   const height = canvas.clientHeight;_x000D_
   // If it's resolution does not match change it_x000D_
   if (canvas.width !== width || canvas.height !== height) {_x000D_
     canvas.width = width;_x000D_
     canvas.height = height;_x000D_
     return true;_x000D_
   return false;_x000D_
span { _x000D_
   width: 250px; _x000D_
   height: 100px; _x000D_
   float: left; _x000D_
   padding: 1em 1em 1em 0;_x000D_
   display: inline-block;_x000D_
canvas {_x000D_
   width: 100%;_x000D_
   height: 100%;_x000D_
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Praesent cursus venenatis metus. Mauris ac nibh at odio scelerisque scelerisque. Donec ut enim <span class="diagram"><canvas id="c"></canvas></span>_x000D_
vel urna gravida imperdiet id ac odio. Aenean congue hendrerit eros id facilisis. In vitae leo ullamcorper, aliquet leo a, vehicula magna. Proin sollicitudin vestibulum aliquet. Sed et varius justo._x000D_
Quisque tempor metus in porttitor placerat. Nulla vehicula sem nec ipsum commodo, at tincidunt orci porttitor. Duis porttitor egestas dui eu viverra. Sed et ipsum eget odio pharetra semper. Integer tempor orci quam, eget aliquet velit consectetur sit amet. Maecenas maximus placerat arcu in varius. Morbi semper, quam a ullamcorper interdum, augue nisl sagittis urna, sed pharetra lectus ex nec elit. Nullam viverra lacinia tellus, bibendum maximus nisl dictum id. Phasellus mauris quam, rutrum ut congue non, hendrerit sollicitudin urna._x000D_

Here's a canvas in a sizable control panel

const ctx = document.querySelector("#c").getContext("2d");_x000D_
function render(time) {_x000D_
  time *= 0.001;_x000D_
  ctx.fillStyle = "#DDE";_x000D_
  ctx.fillRect(0, 0, ctx.canvas.width, ctx.canvas.height);_x000D_;_x000D_
  const spacing = 64;_x000D_
  const size = 48;_x000D_
  const across = ctx.canvas.width / spacing + 1;_x000D_
  const down = ctx.canvas.height / spacing + 1;_x000D_
  const s = Math.sin(time);_x000D_
  const c = Math.cos(time);_x000D_
  for (let y = 0; y < down; ++y) {_x000D_
    for (let x = 0; x < across; ++x) {_x000D_
      ctx.setTransform(c, -s, s, c, x * spacing, y * spacing);_x000D_
      ctx.strokeRect(-size / 2, -size / 2, size, size);_x000D_
function resizeCanvasToDisplaySize(canvas) {_x000D_
   // look up the size the canvas is being displayed_x000D_
   const width = canvas.clientWidth;_x000D_
   const height = canvas.clientHeight;_x000D_
   // If it's resolution does not match change it_x000D_
   if (canvas.width !== width || canvas.height !== height) {_x000D_
     canvas.width = width;_x000D_
     canvas.height = height;_x000D_
     return true;_x000D_
   return false;_x000D_
// ----- the code above related to the canvas does not change ----_x000D_
// ---- the code below is related to the slider ----_x000D_
const $ = document.querySelector.bind(document);_x000D_
const left = $(".left");_x000D_
const slider = $(".slider");_x000D_
let dragging;_x000D_
let lastX;_x000D_
let startWidth;_x000D_
slider.addEventListener('mousedown', e => {_x000D_
 lastX = e.pageX;_x000D_
 dragging = true;_x000D_
window.addEventListener('mouseup', e => {_x000D_
 dragging = false;_x000D_
window.addEventListener('mousemove', e => {_x000D_
  if (dragging) {_x000D_
    const deltaX = e.pageX - lastX;_x000D_ = left.clientWidth + deltaX + "px";_x000D_
    lastX = e.pageX;_x000D_
body { _x000D_
  margin: 0;_x000D_
.frame {_x000D_
  display: flex;_x000D_
  align-items: space-between;_x000D_
  height: 100vh;_x000D_
.left {_x000D_
  width: 70%;_x000D_
  left: 0;_x000D_
  top: 0;_x000D_
  right: 0;_x000D_
  bottom: 0;_x000D_
}  _x000D_
canvas {_x000D_
  width: 100%;_x000D_
  height: 100%;_x000D_
pre {_x000D_
  padding: 1em;_x000D_
.slider {_x000D_
  width: 10px;_x000D_
  background: #000;_x000D_
.right {_x000D_
  flex 1 1 auto;_x000D_
<div class="frame">_x000D_
  <div class="left">_x000D_
     <canvas id="c"></canvas>_x000D_
  <div class="slider">_x000D_
  <div class="right">_x000D_
* controls_x000D_
* go _x000D_
* here_x000D_
&lt;- drag this_x000D_

here's a canvas as a background

const ctx = document.querySelector("#c").getContext("2d");_x000D_
function render(time) {_x000D_
  time *= 0.001;_x000D_
  ctx.fillStyle = "#DDE";_x000D_
  ctx.fillRect(0, 0, ctx.canvas.width, ctx.canvas.height);_x000D_;_x000D_
  const spacing = 64;_x000D_
  const size = 48;_x000D_
  const across = ctx.canvas.width / spacing + 1;_x000D_
  const down = ctx.canvas.height / spacing + 1;_x000D_
  const s = Math.sin(time);_x000D_
  const c = Math.cos(time);_x000D_
  for (let y = 0; y < down; ++y) {_x000D_
    for (let x = 0; x < across; ++x) {_x000D_
      ctx.setTransform(c, -s, s, c, x * spacing, y * spacing);_x000D_
      ctx.strokeRect(-size / 2, -size / 2, size, size);_x000D_
function resizeCanvasToDisplaySize(canvas) {_x000D_
   // look up the size the canvas is being displayed_x000D_
   const width = canvas.clientWidth;_x000D_
   const height = canvas.clientHeight;_x000D_
   // If it's resolution does not match change it_x000D_
   if (canvas.width !== width || canvas.height !== height) {_x000D_
     canvas.width = width;_x000D_
     canvas.height = height;_x000D_
     return true;_x000D_
   return false;_x000D_
body { margin: 0; }_x000D_
canvas { _x000D_
  display: block; _x000D_
  width: 100vw; _x000D_
  height: 100vh;  _x000D_
  position: fixed;_x000D_
#content {_x000D_
  position: absolute;_x000D_
  margin: 0 1em;_x000D_
  font-size: xx-large;_x000D_
  font-family: sans-serif;_x000D_
  font-weight: bold;_x000D_
  text-shadow: 2px  2px 0 #FFF, _x000D_
              -2px -2px 0 #FFF,_x000D_
              -2px  2px 0 #FFF,_x000D_
               2px -2px 0 #FFF;_x000D_
<canvas id="c"></canvas>_x000D_
<div id="content">_x000D_
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Praesent cursus venenatis metus. Mauris ac nibh at odio scelerisque scelerisque. Donec ut enim vel urna gravida imperdiet id ac odio. Aenean congue hendrerit eros id facilisis. In vitae leo ullamcorper, aliquet leo a, vehicula magna. Proin sollicitudin vestibulum aliquet. Sed et varius justo._x000D_
Quisque tempor metus in porttitor placerat. Nulla vehicula sem nec ipsum commodo, at tincidunt orci porttitor. Duis porttitor egestas dui eu viverra. Sed et ipsum eget odio pharetra semper. Integer tempor orci quam, eget aliquet velit consectetur sit amet. Maecenas maximus placerat arcu in varius. Morbi semper, quam a ullamcorper interdum, augue nisl sagittis urna, sed pharetra lectus ex nec elit. Nullam viverra lacinia tellus, bibendum maximus nisl dictum id. Phasellus mauris quam, rutrum ut congue non, hendrerit sollicitudin urna._x000D_

Because I didn't set the attributes the only thing that changed in each sample is the CSS (as far as the canvas is concerned)


  • Don't put borders or padding on a canvas element. Computing the size to subtract from the number of dimensions of the element is troublesome

Height of an HTML select box (dropdown)

You can change the height of one. Don't use height="500"(Just an example number). Use the style. You can use <style>tag or just use this:

<!DOCTYPE html>
  <select id="option" style="height: 100px;">
    <option value="1">Option 1
    <option value="2">Option 2

I spotlight the change:

  <select id="option" style="height: 100px;">

And even better...

style="height: 100px;">

You see that?

Please up vote if it's helpful!

Taskkill /f doesn't kill a process

NirSoft's NirCmd did the job for me:

nircmd killprocess "process name.exe"

killprocess man page is here.

What is the difference between "JPG" / "JPEG" / "PNG" / "BMP" / "GIF" / "TIFF" Image?

Yes. They are different file formats (and their file extensions).

Wikipedia entries for each of the formats will give you quite a bit of information:

  • JPEG (or JPG, for the file extension; Joint Photographic Experts Group)
  • PNG (Portable Network Graphics)
  • BMP (Bitmap)
  • GIF (Graphics Interchange Format)
  • TIFF (or TIF, for the file extension; Tagged Image File Format)

Image formats can be separated into three broad categories:

  • lossy compression,
  • lossless compression,
  • uncompressed,

Uncompressed formats take up the most amount of data, but they are exact representations of the image. Bitmap formats such as BMP generally are uncompressed, although there also are compressed BMP files as well.

Lossy compression formats are generally suited for photographs. It is not suited for illustrations, drawings and text, as compression artifacts from compressing the image will standout. Lossy compression, as its name implies, does not encode all the information of the file, so when it is recovered into an image, it will not be an exact representation of the original. However, it is able to compress images very effectively compared to lossless formats, as it discards certain information. A prime example of a lossy compression format is JPEG.

Lossless compression formats are suited for illustrations, drawings, text and other material that would not look good when compressed with lossy compression. As the name implies, lossless compression will encode all the information from the original, so when the image is decompressed, it will be an exact representation of the original. As there is no loss of information in lossless compression, it is not able to achieve as high a compression as lossy compression, in most cases. Examples of lossless image compression is PNG and GIF. (GIF only allows 8-bit images.)

TIFF and BMP are both "wrapper" formats, as the data inside can depend upon the compression technique that is used. It can contain both compressed and uncompressed images.

When to use a certain image compression format really depends on what is being compressed.

Related question: Ruthlessly compressing large images for the web

REST / SOAP endpoints for a WCF service

We must define the behavior configuration to REST endpoint

  <behavior name="restfulBehavior">
   <webHttp defaultOutgoingResponseFormat="Json" defaultBodyStyle="Wrapped" automaticFormatSelectionEnabled="False" />

and also to a service

     <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true" />
      <serviceDebug includeExceptionDetailInFaults="false" />

After the behaviors, next step is the bindings. For example basicHttpBinding to SOAP endpoint and webHttpBinding to REST.

     <binding name="soapService" />
     <binding name="jsonp" crossDomainScriptAccessEnabled="true" />

Finally we must define the 2 endpoint in the service definition. Attention for the address="" of endpoint, where to REST service is not necessary nothing.

  <service name="ComposerWcf.ComposerService">
    <endpoint address="" behaviorConfiguration="restfulBehavior" binding="webHttpBinding" bindingConfiguration="jsonp" name="jsonService" contract="ComposerWcf.Interface.IComposerService" />
    <endpoint address="soap" binding="basicHttpBinding" name="soapService" contract="ComposerWcf.Interface.IComposerService" />
    <endpoint address="mex" binding="mexHttpBinding" name="metadata" contract="IMetadataExchange" />

In Interface of the service we define the operation with its attributes.

namespace ComposerWcf.Interface
    public interface IComposerService
        [WebInvoke(Method = "GET", UriTemplate = "/autenticationInfo/{app_id}/{access_token}", ResponseFormat = WebMessageFormat.Json,
            RequestFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Wrapped)]
        Task<UserCacheComplexType_RootObject> autenticationInfo(string app_id, string access_token);

Joining all parties, this will be our WCF system.serviceModel definition.


      <behavior name="restfulBehavior">
        <webHttp defaultOutgoingResponseFormat="Json" defaultBodyStyle="Wrapped" automaticFormatSelectionEnabled="False" />
        <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true" />
        <serviceDebug includeExceptionDetailInFaults="false" />

      <binding name="soapService" />
      <binding name="jsonp" crossDomainScriptAccessEnabled="true" />

    <add binding="basicHttpsBinding" scheme="https" />

  <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />

    <service name="ComposerWcf.ComposerService">
      <endpoint address="" behaviorConfiguration="restfulBehavior" binding="webHttpBinding" bindingConfiguration="jsonp" name="jsonService" contract="ComposerWcf.Interface.IComposerService" />
      <endpoint address="soap" binding="basicHttpBinding" name="soapService" contract="ComposerWcf.Interface.IComposerService" />
      <endpoint address="mex" binding="mexHttpBinding" name="metadata" contract="IMetadataExchange" />


To test the both endpoint, we can use WCFClient to SOAP and PostMan to REST.

How can I make visible an invisible control with jquery? (hide and show not work)

You can't do this with jQuery, visible="false" in means the control isn't rendered into the page. If you want the control to go to the client, you need to do style="display: none;" so it's actually in the HTML, otherwise there's literally nothing for the client to show, since the element wasn't in the HTML your server sent.

If you remove the visible attribute and add the style attribute you can then use jQuery to show it, like this:


Old Answer (before patrick's catch)

To change visibility, you need to use .css(), like this:

$("#elem").css('visibility', 'visible');

Unless you need to have the element occupy page space though, use display: none; instead of visibility: hidden; in your CSS, then just do:


The .show() and .hide() functions deal with display instead of visibility, like most of the jQuery functions :)

Search All Fields In All Tables For A Specific Value (Oracle)

I don't of a simple solution on the SQL promprt. Howeve there are quite a few tools like toad and PL/SQL Developer that have a GUI where a user can input the string to be searched and it will return the table/procedure/object where this is found.

HTTP Basic Authentication credentials passed in URL and encryption

Will the username and password be automatically SSL encrypted? Is the same true for GETs and POSTs

Yes, yes yes.

The entire communication (save for the DNS lookup if the IP for the hostname isn't already cached) is encrypted when SSL is in use.

Mismatch Detected for 'RuntimeLibrary'

I had this problem along with mismatch in ITERATOR_DEBUG_LEVEL. As a sunday-evening problem after all seemed ok and good to go, I was put out for some time. Working in de VS2017 IDE (Solution Explorer) I had recently added/copied a sourcefile reference to my project (ctrl-drag) from another project. Looking into properties->C/C++/Preprocessor - at source file level, not project level - I noticed that in a Release configuration _DEBUG was specified instead of NDEBUG for this source file. Which was all the change needed to get rid of the problem.

What does this mean? "Parse error: syntax error, unexpected T_PAAMAYIM_NEKUDOTAYIM"

T_PAAMAYIM_NEKUDOTAYIM is the double colon scope resolution thingy PHP uses - ::

Quick glance at your code, I think this line:

return $cnf::getConfig($key);

should be

return $cnf->getConfig($key);

The first is the way to call a method statically - this code would be valid if $cnf contained a string that was also a valid class. The -> syntax is for calling a method on an instance of a class/object.

Replace image src location using CSS

Here is another dirty hack :)

.application-title > img {
display: none;

.application-title::before {
content: url(path/example.jpg);

Pagination response payload from a RESTful API

I would recommend adding headers for the same. Moving metadata to headers helps in getting rid of envelops like result , data or records and response body only contains the data we need. You can use Link header if you generate pagination links too.

    HTTP/1.1 200
    Pagination-Count: 100
    Pagination-Page: 5
    Pagination-Limit: 20
    Content-Type: application/json

        "id": 10,
        "name": "shirt",
        "color": "red",
        "price": "$23"
        "id": 11,
        "name": "shirt",
        "color": "blue",
        "price": "$25"

For details refer to:

For swagger file:

Simple Android grid example using RecyclerView with GridLayoutManager (like the old GridView)

You should set your RecyclerView LayoutManager to Gridlayout mode. Just change your code when you want to set your RecyclerView LayoutManager:

recyclerView.setLayoutManager(new GridLayoutManager(getActivity(), numberOfColumns));

JavaScript TypeError: Cannot read property 'style' of null

I met the same problem, the situation is I need to download flash game by embed tag and H5 game by iframe, I need a loading box there, when the flash or H5 download done, let the loading box display none. well, the flash one work well but when things go to iframe, I cannot find the property 'style' of null , so I add a clock to it , and it works

let clock = setInterval(() => {
        clock = null
        document.getElementById('loading-box').style.display = 'none'
    }, 200)

The origin server did not find a current representation for the target resource or is not willing to disclose that one exists

Accessing webpages issues

I added yellow highlighted package and now my view page is accessible. in eclipse when we deploy our war it only deploy those stuff mention in the deployment assessment.

We set Deployment Assessment from right click on project --> Properties --> Apply and Close....

How to get current time and date in C++?

You can try the following cross-platform code to get current date/time:

#include <iostream>
#include <string>
#include <stdio.h>
#include <time.h>

// Get current date/time, format is YYYY-MM-DD.HH:mm:ss
const std::string currentDateTime() {
    time_t     now = time(0);
    struct tm  tstruct;
    char       buf[80];
    tstruct = *localtime(&now);
    // Visit
    // for more information about date/time format
    strftime(buf, sizeof(buf), "%Y-%m-%d.%X", &tstruct);

    return buf;

int main() {
    std::cout << "currentDateTime()=" << currentDateTime() << std::endl;
    getchar();  // wait for keyboard input



Please visit here for more information about date/time format

Python - Dimension of Data Frame

Summary of all ways to get info on dimensions of DataFrame or Series

There are a number of ways to get information on the attributes of your DataFrame or Series.

Create Sample DataFrame and Series

df = pd.DataFrame({'a':[5, 2, np.nan], 'b':[ 9, 2, 4]})

     a  b
0  5.0  9
1  2.0  2
2  NaN  4

s = df['a']

0    5.0
1    2.0
2    NaN
Name: a, dtype: float64

shape Attribute

The shape attribute returns a two-item tuple of the number of rows and the number of columns in the DataFrame. For a Series, it returns a one-item tuple.

(3, 2)


len function

To get the number of rows of a DataFrame or get the length of a Series, use the len function. An integer will be returned.



size attribute

To get the total number of elements in the DataFrame or Series, use the size attribute. For DataFrames, this is the product of the number of rows and the number of columns. For a Series, this will be equivalent to the len function:



ndim attribute

The ndim attribute returns the number of dimensions of your DataFrame or Series. It will always be 2 for DataFrames and 1 for Series:



The tricky count method

The count method can be used to return the number of non-missing values for each column/row of the DataFrame. This can be very confusing, because most people normally think of count as just the length of each row, which it is not. When called on a DataFrame, a Series is returned with the column names in the index and the number of non-missing values as the values.

df.count() # by default, get the count of each column

a    2
b    3
dtype: int64

df.count(axis='columns') # change direction to get count of each row

0    2
1    2
2    1
dtype: int64

For a Series, there is only one axis for computation and so it just returns a scalar:


Use the info method for retrieving metadata

The info method returns the number of non-missing values and data types of each column

<class 'pandas.core.frame.DataFrame'>
RangeIndex: 3 entries, 0 to 2
Data columns (total 2 columns):
a    2 non-null float64
b    3 non-null int64
dtypes: float64(1), int64(1)
memory usage: 128.0 bytes

With jQuery, how do I capitalize the first letter of a text field while the user is still editing that field?

CSS solution with "text-transform: capitalize;" is no good if you want to use the contents of the input in backend. You will still receive data as-is. JavaScript solves this issue.

JQuery plugin combined from some of the techniques mentioned earlier, plus it capitalizes words after hyphens, i.e.: "Tro Lo-Lo":

Add to your script:

jQuery.fn.capitalize = function() {
    $(this[0]).keyup(function(event) {
        var box =;
        var txt = $(this).val();
        var stringStart = box.selectionStart;
        var stringEnd = box.selectionEnd;
        $(this).val(txt.replace(/^(.)|(\s|\-)(.)/g, function($word) {
            return $word.toUpperCase();
        box.setSelectionRange(stringStart , stringEnd);

   return this;

Then just attach capitalize() to any selector:

$('#myform input').capitalize();

Is there a maximum number you can set Xmx to when trying to increase jvm memory?

I think a 32 bit JVM has a maximum of 2GB memory.This might be out of date though. If I understood correctly, you set the -Xmx on Eclipse launcher. If you want to increase the memory for the program you run from Eclipse, you should define -Xmx in the "Run->Run configurations..."(select your class and open the Arguments tab put it in the VM arguments area) menu, and NOT on Eclipse startup

Edit: details you asked for. in Eclipse 3.4

  1. Run->Run Configurations...

  2. if your class is not listed in the list on the left in the "Java Application" subtree, click on "New Launch configuration" in the upper left corner

  3. on the right, "Main" tab make sure the project and the class are the right ones

  4. select the "Arguments" tab on the right. this one has two text areas. one is for the program arguments that get in to the args[] array supplied to your main method. the other one is for the VM arguments. put into the one with the VM arguments(lower one iirc) the following:

    I think that 1024m should more than enough for what you need though!

  5. Click Apply, then Click Run

  6. Should work :)

Which to use <div class="name"> or <div id="name">?

The object itself will not change. The main difference between these 2 keyword is the use:

  • The ID is usually single in the page
  • The class can have one or many occurences

In the CSS or Javascript files:

  • The ID will be accessed by the character #
  • The class will be accessed by the character .

Embedding SVG into ReactJS

If you just have a static svg string you want to include, you can use dangerouslySetInnerHTML:

render: function() {
    return <span dangerouslySetInnerHTML={{__html: "<svg>...</svg>"}} />;

and React will include the markup directly without processing it at all.

Pushing an existing Git repository to SVN

If you want to keep on working with Git as your main repository and just need to "export" the revisions to SVN from time to time, you could use Tailor to keep the SVN repository in sync. It can copy revisions between different source control systems and would update the SVN with the changes you make in Git.

I haven't tried a Git-to-SVN conversion, but for a SVN -> SVN example see this answer.

mysql said: Cannot connect: invalid settings. xampp

Opsss. after I change user to 'admin', it doesn't have privelege to add database.. so I change back the user to 'root'.

Then I change the password from the browser.

  1. Go to http://localhost/security/ and then click on the link http://localhost/security/xamppsecurity.php . After that change pasword for superuser to 'root'.

  2. After that open your http://localhost/phpmyadmin/

    Now it works.

How to use the priority queue STL for objects?

We can define user defined comparator: .The code below can be helpful for you.

Code Snippet :

using namespace std;

struct man
  string name;
  int priority; 

class comparator
   bool operator()(const man& a, const man& b)
        return a.priority<b.priority;

int main()
   man arr[5];
   priority_queue<man, vector<man>, comparator> pq;

   for(int i=0; i<3; i++)

   while (!pq.empty())
     cout<<<<" "<<;
   return 0;

input :

batman 2
goku 9
mario 4


goku 9
mario 4
batman 2

Excel Define a range based on a cell value

Old post but this is exactly what I needed, simple question, how to change it to count column rather than Row. Thankyou in advance. Novice to Excel.


I.e My data is A1 B1 C1 D1 etc rather then A1 A2 A3 A4.

Good Linux (Ubuntu) SVN client

I'm very happy with kdesvn - integrates very well with konqueror, much like trortousesvn with windows explorer, and supports most of the functionality of tortoisesvn.

Of course, you'll benefit from this integration, if you use kubunto, and not ubuntu.

Cut Java String at a number of character

You can use String#substring()

if(str != null && str.length() > 8) {
    return str.substring(0, 8) + "...";
} else {
    return str;

You could however make a function where you pass the maximum number of characters that can be displayed. The ellipsis would then cut in only if the width specified isn't enough for the string.

public String getShortString(String input, int width) {
  if(str != null && str.length() > width) {
      return str.substring(0, width - 3) + "...";
  } else {
      return str;

// abcdefgh...
System.out.println(getShortString("abcdefghijklmnopqrstuvwxyz", 11));

// abcdefghijk
System.out.println(getShortString("abcdefghijk", 11)); // no need to trim

Get program path in VB.NET?

You can get path by this code

Dim CurDir as string = My.Application.Info.DirectoryPath

How to avoid precompiled headers

The .cpp file is configured to use precompiled header, therefore it must be included first (before iostream). For Visual Studio, it's name is usually "stdafx.h".

If there are no stdafx* files in your project, you need to go to this file's options and set it as “Not using precompiled headers”.

Android Studio and Gradle build error

I installed Android Studio on an old WinXP with only for me option. After install I did the new project wizard and when opening the new project a got some Gradle error with some failed path to my instalation dir. c:/Document"#¤!"#¤ and settins/...

The I uninstalled and did a new install with option for all users (C:/Programs/..) then I opend the previous created project with no errors.

So it might be a path problem. (Just spent 10 sec debugging, so I might be wrong but it solved my gradle error)

how to change default python version?

Old question, but alternatively:

virtualenv --python=python3.5 .venv
source .venv/bin/activate

SQL: How to properly check if a record exists

I'm using this way:

                FROM Users 
                WHERE FirstName = 'John'), 1, 0) AS DoesJohnExist

Reference jars inside a jar

Add the jar files to your library(if using netbeans) and modify your manifest's file classpath as follows:

Class-Path: lib/derby.jar lib/derbyclient.jar lib/derbynet.jar lib/derbytools.jar

a similar answer exists here

Can't install nuget package because of "Failed to initialize the PowerShell host"

This started happening with 6.0.4 recently for me, I don't think this is a very good solution but here is what helped me. Close Visual Studio

  1. Open a Windows PowerShell prompt as Administrator (very important) and run the following command:Set-ExecutionPolicy Bypass
  2. Open Visual Studio, open your solution and use Nuget to install JSON.Net (or whatever package included it as a dependency).
  3. Once everything is working, I recommend setting the powershell execution policy back to restricted with the following command: Set-ExecutionPolicy Restricted

Eslint: How to disable "unexpected console statement" in Node.js?

You should update eslint config file to fix this permanently. Else you can temporarily enable or disable eslint check for console like below

/* eslint-disable no-console */
/* eslint-enable no-console */

Calling class staticmethod within the class body?

What about injecting the class attribute after the class definition?

class Klass(object):

    @staticmethod  # use as decorator
    def stat_func():
        return 42

    def method(self):
        ret = Klass.stat_func()
        return ret

Klass._ANS = Klass.stat_func()  # inject the class attribute with static method value

PHP Redirect to another page after form submit

Whenever you want to redirect, send the headers:


Remember you cant send data to the client before that, though.

ssh remote host identification has changed

The other answers here are good and working, anyway, I solved the problem by deleting ~/.ssh/known_hosts. This certainly solves the problem, but it's probably not the best approach.

How to verify a method is called two times with mockito verify()

build gradle:

testImplementation "com.nhaarman.mockitokotlin2:mockito-kotlin:2.2.0"


interface MyCallback {
  fun someMethod(value: String)

class MyTestableManager(private val callback: MyCallback){
  fun perform(){


import com.nhaarman.mockitokotlin2.times
import com.nhaarman.mockitokotlin2.verify
import com.nhaarman.mockitokotlin2.mock
val callback: MyCallback = mock()
val manager = MyTestableManager(callback)

val captor: KArgumentCaptor<String> = com.nhaarman.mockitokotlin2.argumentCaptor<String>()

verify(callback, times(3)).someMethod(captor.capture())

assertTrue(captor.allValues[0] == "first")
assertTrue(captor.allValues[1] == "second")
assertTrue(captor.allValues[2] == "third")

Is there a way to use PhantomJS in Python?

The answer by @Pykler is great but the Node requirement is outdated. The comments in that answer suggest the simpler answer, which I've put here to save others time:

  1. Install PhantomJS

    As @Vivin-Paliath points out, it's a standalone project, not part of Node.


    brew install phantomjs


    sudo apt-get install phantomjs


  2. Set up a virtualenv (if you haven't already):

    virtualenv mypy  # doesn't have to be "mypy". Can be anything.
    . mypy/bin/activate

    If your machine has both Python 2 and 3 you may need run virtualenv-3.6 mypy or similar.

  3. Install selenium:

    pip install selenium
  4. Try a simple test, like this borrowed from the docs:

    from selenium import webdriver
    from selenium.webdriver.common.keys import Keys
    driver = webdriver.PhantomJS()
    assert "Python" in driver.title
    elem = driver.find_element_by_name("q")
    assert "No results found." not in driver.page_source

What does it mean if a Python object is "subscriptable" or not?

A scriptable object is an object that records the operations done to it and it can store them as a "script" which can be replayed.

For example, see: Application Scripting Framework

Now, if Alistair didn't know what he asked and really meant "subscriptable" objects (as edited by others), then (as mipadi also answered) this is the correct one:

A subscriptable object is any object that implements the __getitem__ special method (think lists, dictionaries).

How can I make a countdown with NSTimer?

Swift 3

private let NUMBER_COUNT_DOWN   = 3

var countDownLabel = UILabel()
var countDown = NUMBER_COUNT_DOWN
var timer:Timer?

private func countDown(time: Double)
    countDownLabel.frame = CGRect(x: 0, y: 0, width: 300, height: 300)
    countDownLabel.font = UIFont.systemFont(ofSize: 300)
    countDownLabel.textColor = .black = CGPoint(x: self.view.frame.width / 2, y: self.view.frame.height / 2)

    countDownLabel.textAlignment = .center
    view.bringSubview(toFront: countDownLabel)

    timer = Timer.scheduledTimer(timeInterval: time, target: self, selector: #selector(updateCountDown), userInfo: nil, repeats: true)

func updateCountDown() {
    if(countDown > 0) {
        countDownLabel.text = String(countDown)
        countDown = countDown - 1
    } else {

private func removeCountDownLable() {
    countDown = NUMBER_COUNT_DOWN
    countDownLabel.text = ""

    timer = nil

Why does the Visual Studio editor show dots in blank spaces?

In Visual Studio 2012
Go to
Edit -> Advanced -> View White Spaces
Press Ctrl+R, Ctrl+W

How to show one layout on top of the other programmatically in my case?

The answer, given by Alexandru is working quite nice. As he said, it is important that this "accessor"-view is added as the last element. Here is some code which did the trick for me:







<!-- place a FrameLayout (match_parent) as the last child -->


in Java:

final MaterialDialog materialDialog = (MaterialDialog) dialogInterface;

FrameLayout frameLayout = (FrameLayout) materialDialog

        new OnSwipeTouchListener(ShowCardActivity.this) {

How to check "hasRole" in Java Code with Spring Security?

User Roles can be checked using following ways:

  1. Using call static methods in SecurityContextHolder:

    Authentication auth = SecurityContextHolder.getContext().getAuthentication(); if (auth != null && auth.getAuthorities().stream().anyMatch(role -> role.getAuthority().equals("ROLE_NAME"))) { //do something}

  2. Using HttpServletRequest

public String getUsers(HttpServletRequest request) {
    if (request.isUserInRole("ROLE_NAME")) {

How can I find matching values in two arrays?

var array1  = [1, 2, 3, 4, 5, 6];
var array2 = [1, 2, 3, 4, 5, 6, 7, 8, 9];
var array3 = array2.filter(function(obj) { 
    return array1.indexOf(obj) == -1; 

How to change an input button image using CSS?

Perhaps you could just import a .js file as well and have the image replacement there, in JavaScript.

Convert PDF to clean SVG?

Here is the process that I ended up using. The main tool I used was Inkscape which was able to convert text alright.

  • used Adobe Acrobat Pro actions with JavaScript to split-up the PDF sheets
  • ran Inkscape Portable 0.48.5 from Windows Cmd to convert to SVG
  • made some manual edits to a particular SVG XML attribute I was having issues with by using Windows Cmd and Windows PowerShell

Separate Pages: Adobe Acrobat Pro with JavaScript

Using Adobe Acrobat Pro Actions (formerly Batch Processing) create a custom action to separate PDF pages into separate files. Alternatively you may be able to split up PDFs with GhostScript

Acrobat JavaScript Action to split pages

/* Extract Pages to Folder */

var re = /.*\/|\.pdf$/ig;
var filename = this.path.replace(re,"");

    for ( var i = 0;  i < this.numPages; i++ )
        nStart: i,
        nEnd: i,
        cPath : filename + "_s" + ("000000" + (i+1)).slice (-3) + ".pdf"

PDF to SVG Conversion: Inkscape with Windows CMD batch file

Using Windows Cmd created batch file to loop through all PDF files in a folder and convert them to SVG

Batch file to convert PDF to SVG in current folder

:: ===== SETUP =====
@echo off
echo Starting SVG conversion...

:: setup working directory (if different)
REM set "_work_dir=%~dp0"
set "_work_dir=%CD%"

:: setup counter
set "count=1"

:: setup file search and save string
set "_work_x1=pdf"
set "_work_x2=svg"
set "_work_file_str=*.%_work_x1%"

:: setup inkscape commands
set "_inkscape_path=D:\InkscapePortable\App\Inkscape\"
set "_inkscape_cmd=%_inkscape_path%inkscape.exe"

:: Output from DIR last element is single  carriage return character. 
:: Carriage return characters are directly removed after percent expansion, 
:: but not with delayed expansion.

pushd "%_work_dir%"
FOR /f "tokens=*" %%A IN ('DIR /A:-D /O:N /B %_work_file_str%') DO (
    CALL :subroutine "%%A"


IF NOT [%1]==[] (

    echo %count%:%1
    set /A count+=1

    start "" /D "%_work_dir%" /W "%_inkscape_cmd%" --without-gui --file="%~n1.%_work_x1%" --export-dpi=300 --export-plain-svg="%~n1.%_work_x2%"

) ELSE (
    echo End of output

GOTO :eof


:: print inkscape help
REM "%_inkscape_cmd%" --help > "%~dp0\inkscape_help.txt"
REM "%_inkscape_cmd%" --verb-list > "%~dp0\inkscape_verb_list.txt"

Cleanup attributes: Windows Cmd and PowerShell

I realize it is not best practice to manually brute force edit SVG or XML tags or attributes due to potential variations and should use an XML parser instead. However I had a simple issue where the stroke width on one drawing was very small, and on another the font family was being incorrectly identified, so I basically modified the previous Windows Cmd batch script to do a simple find and replace. The only changes were to the search string definitions and changing to call a PowerShell command. The PowerShell command will perform a find and replace and save the modified file with an added suffix. I did find some other references that could be better used to parse or modify the resultant SVG files if some other minor cleanup is needed to be performed.

Modifications to manually find and replace SVG XML data

:: setup file search and save string
set "_work_x1=svg"
set "_work_x2=svg"
set "_work_s2=_mod"
set "_work_file_str=*.%_work_x1%"

powershell -Command "(Get-Content '%~n1.%_work_x1%') | ForEach-Object {$_ -replace 'stroke-width:0.06', 'stroke-width:1'} | ForEach-Object {$_ -replace 'font-family:Times Roman','font-family:Times New Roman'} | Set-Content '%~n1%_work_s2%.%_work_x2%'"

Hope this might help someone


Adobe Acrobat Pro Actions and JavaScript references to Separate Pages

GhostScript references to Separate Pages

Inkscape Command Line references for PDF to SVG Conversion

Windows Cmd Batch File Script references

XML tag/attribute replacement research

How to implement a FSM - Finite State Machine in Java

The heart of a state machine is the transition table, which takes a state and a symbol (what you're calling an event) to a new state. That's just a two-index array of states. For sanity and type safety, declare the states and symbols as enumerations. I always add a "length" member in some way (language-specific) for checking array bounds. When I've hand-coded FSM's, I format the code in row and column format with whitespace fiddling. The other elements of a state machine are the initial state and the set of accepting states. The most direct implementation of the set of accepting states is an array of booleans indexed by the states. In Java, however, enumerations are classes, and you can specify an argument "accepting" in the declaration for each enumerated value and initialize it in the constructor for the enumeration.

For the machine type, you can write it as a generic class. It would take two type arguments, one for the states and one for the symbols, an array argument for the transition table, a single state for the initial. The only other detail (though it's critical) is that you have to call Enum.ordinal() to get an integer suitable for indexing the transition array, since you there's no syntax for directly declaring an array with a enumeration index (though there ought to be).

To preempt one issue, EnumMap won't work for the transition table, because the key required is a pair of enumeration values, not a single one.

enum State {
    Initial( false ),
    Final( true ),
    Error( false );
    static public final Integer length = 1 + Error.ordinal();

    final boolean accepting;

    State( boolean accepting ) {
        this.accepting = accepting;

enum Symbol {
    A, B, C;
    static public final Integer length = 1 + C.ordinal();

State transition[][] = {
    //  A               B               C
        State.Initial,  State.Final,    State.Error
    }, {
        State.Final,    State.Initial,  State.Error

"Can't find Project or Library" for standard VBA functions

I had the same problem. This worked for me:

  • In VB go to Tools » References
  • Uncheck the library "Crystal Analysis Common Controls 1.0". Or any library.
  • Just leave these 5 references:
    1. Visual Basic For Applications (This is the library that defines the VBA language.)
    2. Microsoft Excel Object Library (This defines all of the elements of Excel.)
    3. OLE Automation (This specifies the types for linking and embedding documents and for automation of other applications and the "plumbing" of the COM system that Excel uses to communicate with the outside world.)
    4. Microsoft Office (This defines things that are common to all Office programs such as Command Bars and Command Bar controls.)
    5. Microsoft Forms 2.0 This is required if you are using a User Form. This library defines things like the user form and the controls that you can place on a form.
  • Then Save.

How to check the value given is a positive or negative integer?

I know it's been some time, but there is a more elegant solution. From the mozilla docs:


It will give you -1 for negative, 0 for zero and 1 for positive.

Failed to enable constraints. One or more rows contain values violating non-null, unique, or foreign-key constraints

Short and easy Soloution:

Go to MSSQL Studio Sever ;

Run the query of the cause of this error : in my case i see that id value was null because i forget to set Identity specification increment by 1.

enter image description here

So entered 1 for the id field as its is autoincremane and modify dont allow NULLS in desing view

enter image description here

That was the error that caused my bindingsource and tabel adapter throwin error at this code:


Moment.js get day name from date

var mydate = "2017-06-28T00:00:00";
var weekDayName =  moment(mydate).format('ddd');

Result: Wed

var mydate = "2017-06-28T00:00:00";
var weekDayName =  moment(mydate).format('dddd');

Result: Wednesday

Ansible: deploy on multiple hosts in the same time

Check out this POC or MVP of running in parallel one-host-from-every-group (for all hosts)

you may get the inspiration

Angular2 use [(ngModel)] with [ngModelOptions]="{standalone: true}" to link to a reference to model's property

For me the code:

<form (submit)="addTodo()">_x000D_
  <input type="text" [(ngModel)]="text">_x000D_

throws error, but I added name attribute to input:

<form (submit)="addTodo()">_x000D_
  <input type="text" [(ngModel)]="text" name="text">_x000D_

and it started to work.

jQuery - Appending a div to body, the body is the object?

Using jQuery appendTo try this:

var holdyDiv = $('<div></div>').attr('id', 'holdy');

how to Call super constructor in Lombok

Lombok Issue #78 references this page with this lovely explanation:

public class Parent {   
     private String a; 

public class Child extends Parent {
  private String b;

  public Child(String a, String b){
    this.b = b;   

As a result you can then use the generated builder like this:


The official documentation explains this, but it doesn’t explicitly point out that you can facilitate it in this way.

I also found this works nicely with Spring Data JPA.

rotate image with css

The trouble looks like the image isn't square and the browser adjusts as such. After rotation ensure the dimensions are retained by changing the image margin.

.imagetest img {
  transform: rotate(270deg);
  margin: 10px 0px;

The amount will depend on the difference in height x width of the image. You may also need to add display:inline-block; or display:block to get it to recognize the margin parameter.

Convert NSArray to NSString in Objective-C

The way I know is easy.

var NSArray_variable = NSArray_Object[n]
var stringVarible = NSArray_variable as String

n is the inner position in the array This in SWIFT Language. It might work in Objective C

When to use Hadoop, HBase, Hive and Pig?

I believe this thread hasn't done in particular justice to HBase and Pig in particular. While I believe Hadoop is the choice of the distributed, resilient file-system for big-data lake implementations, the choice between HBase and Hive is in particular well-segregated.

As in, a lot of use-cases have a particular requirement of SQL like or No-SQL like interfaces. With Phoenix on top of HBase, though SQL like capabilities is certainly achievable, however, the performance, third-party integrations, dashboard update are a kind of painful experiences. However, it's an excellent choice for databases requiring horizontal scaling.

Pig is in particular excellent for non-recursive batch like computations or ETL pipelining (somewhere, where it outperforms Spark by a comfortable distance). Also, it's high-level dataflow implementations is an excellent choice for batch querying and scripting. The choice between Pig and Hive is also pivoted on the need of the client or server-side scripting, required file formats, etc. Pig supports Avro file format which is not true in the case of Hive. The choice for 'procedural dataflow language' vs 'declarative data flow language' is also a strong argument for the choice between pig and hive.

Using set_facts and with_items together in Ansible

As mentioned in other people's comments, the top solution given here was not working for me in Ansible 2.2, particularly when also using with_items.

It appears that OP's intended approach does work now with a slight change to the quoting of item.

- set_fact: something="{{ something + [ item ] }}"
    - one
    - two
    - three

And a longer example where I've handled the initial case of the list being undefined and added an optional when because that was also causing me grief:

- set_fact: something="{{ something|default([]) + [ item ] }}"
    - one
    - two
    - three
  when: in allowed_things.item_list

Squash the first two commits in Git?

There is an easier way to do this. Let's assume you're on the master branch

Create a new orphaned branch which will remove all commit history:

$ git checkout --orphan new_branch

Add your initial commit message:

$ git commit -a

Get rid of the old unmerged master branch:

$ git branch -D master

Rename your current branch new_branch to master:

$ git branch -m master

What's the best way to calculate the size of a directory in .NET?

I try to change the sample (Alexandre Pepin and hao's Answer)

As is

    private long GetDirectorySize(string dirPath)
        if (Directory.Exists(dirPath) == false)
            return 0;

        DirectoryInfo dirInfo = new DirectoryInfo(dirPath);

        long size = 0;

        // Add file sizes.
        FileInfo[] fis = dirInfo.GetFiles();
        foreach (FileInfo fi in fis)
            size += fi.Length;

        // Add subdirectory sizes.
        DirectoryInfo[] dis = dirInfo.GetDirectories();
        foreach (DirectoryInfo di in dis)
            size += GetDirectorySize(di.FullName);

        return size;

To be

    private long GetDirectorySize2(string dirPath)
        if (Directory.Exists(dirPath) == false)
            return 0;

        DirectoryInfo dirInfo = new DirectoryInfo(dirPath);

        long size = 0;

        // Add file sizes.
        IEnumerable<FileInfo> fis = dirInfo.EnumerateFiles("*.*", SearchOption.AllDirectories);
        foreach (FileInfo fi in fis)
            size += fi.Length;

        return size;

finally you can check the result

        // ---------------------------------------------
        // size of directory
        using System.IO;

        string log1Path = @"D:\SampleDirPath1";
        string log2Path = @"D:\SampleDirPath2";
        string log1DirName = Path.GetDirectoryName(log1Path);
        string log2DirName = Path.GetDirectoryName(log2Path);
        long log1Size = GetDirectorySize(log1Path);
        long log2Size = GetDirectorySize(log2Path);
        long log1Size2 = GetDirectorySize2(log1Path);
        long log2Size2 = GetDirectorySize2(log2Path);

        Console.WriteLine($@"{log1DirName} Size: {SizeSuffix(log1Size)}, {SizeSuffix(log1Size2)}
        {log2DirName} Size: {SizeSuffix(log2Size)}, {SizeSuffix(log2Size2)}");

and this is the SizeSuffix function

    private static readonly string[] SizeSuffixes =
               { "bytes", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB" };

    /// <summary>
    /// Size Display
    /// </summary>
    /// <param name="value">bytes ??</param>
    /// <param name="decimalPlaces">????</param>
    /// <returns></returns>
    public static string SizeSuffix(Int64 value, int decimalPlaces = 2)
        if (decimalPlaces < 0) { throw new ArgumentOutOfRangeException("decimalPlaces"); }
        if (value < 0) { return "-" + SizeSuffix(-value); }
        if (value == 0) { return string.Format("{0:n" + decimalPlaces + "} bytes", 0); }

        // mag is 0 for bytes, 1 for KB, 2, for MB, etc.
        int mag = (int)Math.Log(value, 1024);

        // 1L << (mag * 10) == 2 ^ (10 * mag) 
        // [i.e. the number of bytes in the unit corresponding to mag]
        decimal adjustedSize = (decimal)value / (1L << (mag * 10));

        // make adjustment when the value is large enough that
        // it would round up to 1000 or more
        if (Math.Round(adjustedSize, decimalPlaces) >= 1000)
            mag += 1;
            adjustedSize /= 1024;

        return string.Format("{0:n" + decimalPlaces + "} {1}",

Define make variable at rule execution time

Another possibility is to use separate lines to set up Make variables when a rule fires.

For example, here is a makefile with two rules. If a rule fires, it creates a temp dir and sets TMP to the temp dir name.

PHONY = ruleA ruleB display

all: ruleA

ruleA: TMP = $(shell mktemp -d testruleA_XXXX)
ruleA: display

ruleB: TMP = $(shell mktemp -d testruleB_XXXX)
ruleB: display

    echo ${TMP}

Running the code produces the expected result:

$ ls
$ make ruleB
echo testruleB_Y4Ow
$ ls
Makefile  testruleB_Y4Ow

How to find all duplicate from a List<string>?

and without the LINQ:

string[] ss = {"1","1","1"};

var myList = new List<string>();
var duplicates = new List<string>();

foreach (var s in ss)
   if (!myList.Contains(s))

// show list without duplicates 
foreach (var s in myList)

// show duplicates list
foreach (var s in duplicates)

How to pass object from one component to another in Angular 2?

From component

import { Component, OnInit, ViewChild} from '@angular/core';_x000D_
    import { HttpClient } from '@angular/common/http';_x000D_
    import { dataService } from "src/app/service/data.service";_x000D_
    @Component( {_x000D_
        selector: 'app-sideWidget',_x000D_
        templateUrl: './sideWidget.html',_x000D_
        styleUrls: ['./linked-widget.component.css']_x000D_
    } )_x000D_
    export class sideWidget{_x000D_
    TableColumnNames: object[];_x000D_
    SelectedtableName: string = "patient";_x000D_
    constructor( private LWTableColumnNames: dataService ) { _x000D_
    ngOnInit() {_x000D_ 'getColumns', this.SelectedtableName )_x000D_
            ( data: object[] ) => {_x000D_
                this.TableColumnNames = data;_x000D_
     this.LWTableColumnNames.refLWTableColumnNames = this.TableColumnNames; //this line of code will pass the value through data service_x000D_
            } );_x000D_
    }    _x000D_


import { Injectable } from '@angular/core';_x000D_
import { BehaviorSubject, Observable } from 'rxjs';_x000D_
export class dataService {_x000D_
    refLWTableColumnNames: object;//creating an object for the data_x000D_

To Component

import { Component, OnInit } from '@angular/core';_x000D_
import { dataService } from "src/app/service/data.service";_x000D_
@Component( {_x000D_
    selector: 'app-linked-widget',_x000D_
    templateUrl: './linked-widget.component.html',_x000D_
    styleUrls: ['./linked-widget.component.css']_x000D_
} )_x000D_
export class LinkedWidgetComponent implements OnInit {_x000D_
    constructor(private LWTableColumnNames: dataService) { }_x000D_
    ngOnInit() {_x000D_
        console.log(this.LWTableColumnNames.refLWTableColumnNames);// calling the object from another component_x000D_

Log all requests from the python-requests module

The underlying urllib3 library logs all new connections and URLs with the logging module, but not POST bodies. For GET requests this should be enough:

import logging


which gives you the most verbose logging option; see the logging HOWTO for more details on how to configure logging levels and destinations.

Short demo:

>>> import requests
>>> import logging
>>> logging.basicConfig(level=logging.DEBUG)
>>> r = requests.get('')
DEBUG:urllib3.connectionpool:Starting new HTTP connection (1):
DEBUG:urllib3.connectionpool: "GET /get?foo=bar&baz=python HTTP/1.1" 200 366

Depending on the exact version of urllib3, the following messages are logged:

  • INFO: Redirects
  • WARN: Connection pool full (if this happens often increase the connection pool size)
  • WARN: Failed to parse headers (response headers with invalid format)
  • WARN: Retrying the connection
  • WARN: Certificate did not match expected hostname
  • WARN: Received response with both Content-Length and Transfer-Encoding, when processing a chunked response
  • DEBUG: New connections (HTTP or HTTPS)
  • DEBUG: Dropped connections
  • DEBUG: Connection details: method, path, HTTP version, status code and response length
  • DEBUG: Retry count increments

This doesn't include headers or bodies. urllib3 uses the http.client.HTTPConnection class to do the grunt-work, but that class doesn't support logging, it can normally only be configured to print to stdout. However, you can rig it to send all debug information to logging instead by introducing an alternative print name into that module:

import logging
import http.client

httpclient_logger = logging.getLogger("http.client")

def httpclient_logging_patch(level=logging.DEBUG):
    """Enable HTTPConnection debug logging to the logging framework"""

    def httpclient_log(*args):
        httpclient_logger.log(level, " ".join(args))

    # mask the print() built-in in the http.client module to use
    # logging instead
    http.client.print = httpclient_log
    # enable debugging
    http.client.HTTPConnection.debuglevel = 1

Calling httpclient_logging_patch() causes http.client connections to output all debug information to a standard logger, and so are picked up by logging.basicConfig():

>>> httpclient_logging_patch()
>>> r = requests.get('')
DEBUG:urllib3.connectionpool:Starting new HTTP connection (1):
DEBUG:http.client:send: b'GET /get?foo=bar&baz=python HTTP/1.1\r\nHost:\r\nUser-Agent: python-requests/2.22.0\r\nAccept-Encoding: gzip, deflate\r\nAccept: */*\r\nConnection: keep-alive\r\n\r\n'
DEBUG:http.client:reply: 'HTTP/1.1 200 OK\r\n'
DEBUG:http.client:header: Date: Tue, 04 Feb 2020 13:36:53 GMT
DEBUG:http.client:header: Content-Type: application/json
DEBUG:http.client:header: Content-Length: 366
DEBUG:http.client:header: Connection: keep-alive
DEBUG:http.client:header: Server: gunicorn/19.9.0
DEBUG:http.client:header: Access-Control-Allow-Origin: *
DEBUG:http.client:header: Access-Control-Allow-Credentials: true
DEBUG:urllib3.connectionpool: "GET /get?foo=bar&baz=python HTTP/1.1" 200 366

How do I increase memory on Tomcat 7 when running as a Windows Service?

For Tomcat 7 to increase memory :

Identify your service name, you will find it in the service properties, under the "Path to executable" at the end of the line

For me it is //RS//Tomcat70 so the name is Tomcat70

Then write as administrator :

tomcat7.exe //US//Tomcat70 --JvmOptions=-Xmx1024M

How to set a cell to NaN in a pandas dataframe

df.loc[df.y == 'N/A',['y']] = np.nan

This solve your problem. With the double [], you are working on a copy of the DataFrame. You have to specify exact location in one call to be able to modify it.

Is there a way to suppress JSHint warning for one given line?

The "evil" answer did not work for me. Instead, I used what was recommended on the JSHints docs page. If you know the warning that is thrown, you can turn it off for a block of code. For example, I am using some third party code that does not use camel case functions, yet my JSHint rules require it, which led to a warning. To silence it, I wrote:

/*jshint -W106 */
/*jshint +W106 */

Reading a resource file from within jar

Up until now (December 2017), this is the only solution I found which works both inside and outside the IDE.

Use PathMatchingResourcePatternResolver

Note: it works also in spring-boot

In this example I'm reading some files located in src/main/resources/my_folder:

try {
    // Get all the files under this inner resource folder: my_folder
    String scannedPackage = "my_folder/*";
    PathMatchingResourcePatternResolver scanner = new PathMatchingResourcePatternResolver();
    Resource[] resources = scanner.getResources(scannedPackage);

    if (resources == null || resources.length == 0)
        log.warn("Warning: could not find any resources in this scanned package: " + scannedPackage);
    else {
        for (Resource resource : resources) {
            // Read the file content (I used BufferedReader, but there are other solutions for that):
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(resource.getInputStream()));
            String line = null;
            while ((line = bufferedReader.readLine()) != null) {
                // ...
                // ...                      
} catch (Exception e) {
    throw new Exception("Failed to read the resources folder: " + e.getMessage(), e);

Error converting data types when importing from Excel to SQL Server 2008

There is a workaround.

  1. Import excel sheet with numbers as float (default).
  2. After importing, Goto Table-Design
  3. Change DataType of the column from Float to Int or Bigint
  4. Save Changes
  5. Change DataType of the column from Bigint to any Text Type (Varchar, nvarchar, text, ntext etc)
  6. Save Changes.

That's it.

Does Python have “private” variables in classes?

Sorry guys for "resurrecting" the thread, but, I hope this will help someone:

In Python3 if you just want to "encapsulate" the class attributes, like in Java, you can just do the same thing like this:

class Simple:
    def __init__(self, str):
        print("inside the simple constructor")
        self.__s = str

    def show(self):

    def showMsg(self, msg):
        print(msg + ':',

To instantiate this do:

ss = Simple("lol")

Note that: print(ss.__s) will throw an error.

In practice, Python3 will obfuscate the global attribute name. Turning this like a "private" attribute, like in Java. The attribute's name is still global, but in an inaccessible way, like a private attribute in other languages.

But don't be afraid of it. It doesn't matter. It does the job too. ;)

Generating random numbers with normal distribution in Excel

The numbers generated by


are uniformally distributed. If you want the numbers to be normally distributed, you will have to write a function I guess.

hadoop No FileSystem for scheme: file

Configuration conf = new Configuration();
conf.set("fs.defaultFS", "hdfs://nameNode:9000");
FileSystem fs = FileSystem.get(conf);

set fs.defaultFS works for me! Hadoop-2.8.1

How to pass url arguments (query string) to a HTTP request on Angular?

Edit Angular >= 4.3.x

HttpClient has been introduced along with HttpParams. Below an example of use :

import { HttpParams, HttpClient } from '@angular/common/http';

constructor(private http: HttpClient) { }

let params = new HttpParams();
params = params.append('var1', val1);
params = params.append('var2', val2);

this.http.get(StaticSettings.BASE_URL, {params: params}).subscribe(...);

(Old answers)

Edit Angular >= 4.x has been deprecated. Use requestOptions.params instead :

let requestOptions = new RequestOptions();
requestOptions.params = params;

Original answer (Angular 2)

You need to import URLSearchParams as below

import { Http, RequestOptions, URLSearchParams } from '@angular/http';

And then build your parameters and make the http request as the following :

let params: URLSearchParams = new URLSearchParams();
params.set('var1', val1);
params.set('var2', val2);

let requestOptions = new RequestOptions(); = params;

this.http.get(StaticSettings.BASE_URL, requestOptions)
    .then(response => response.json())

Why should C++ programmers minimize use of 'new'?

Two reasons:

  1. It's unnecessary in this case. You're making your code needlessly more complicated.
  2. It allocates space on the heap, and it means that you have to remember to delete it later, or it will cause a memory leak.

Fixing Sublime Text 2 line endings?

to chnage line endings from LF to CRLF:

open Sublime and follow the steps:-

1 press Ctrl+shift+p then install package name line unify endings

then again press Ctrl+shift+p

2 in the blank input box type "Line unify ending "

3 Hit enter twice

Sublime may freeze for sometimes and as a result will change the line endings from LF to CRLF

Dynamically Dimensioning A VBA Array?

You have to use the ReDim statement to dynamically size arrays.

Public Sub Test()
    Dim NumberOfZombies As Integer
    NumberOfZombies = 20000
    Dim Zombies() As New Zombie
    ReDim Zombies(NumberOfZombies)

End Sub

This can seem strange when you already know the size of your array, but there you go!

Dataset - Vehicle make/model/year (free)

These guys have an API that will give the results. It's also free to use.

Note: they also provide data source download in xls or sql format at a premium price. but these data also provides technical specifications for all the make model and trim options.

Cannot connect to local SQL Server with Management Studio

Try to see, if the service "SQL Server (MSSQLSERVER)" it's started, this solved my problem.

Moving items around in an ArrayList

I came across this old question in my search for an answer, and I thought I would just post the solution I found in case someone else passes by here looking for the same.

For swapping 2 elements, Collections.swap is fine. But if we want to move more elements, there is a better solution that involves a creative use of Collections.sublist and Collections.rotate that I hadn't thought of until I saw it described here:,%20int%29

Here's a quote, but go there and read the whole thing for yourself too:

Note that this method can usefully be applied to sublists to move one or more elements within a list while preserving the order of the remaining elements. For example, the following idiom moves the element at index j forward to position k (which must be greater than or equal to j):

Collections.rotate(list.subList(j, k+1), -1);

How to print a string multiple times?

def repeat_char_rows_cols(char, rows, cols):
    return (char*cols + '\n')*rows

>>> print(repeat_char_rows_cols('@', 4, 2))

SSIS Excel Import Forcing Incorrect Column Type

Another workaround is to sort the spreadsheet with the character data at the top, thereby causing Excel to see the column as string, and importing everything as such.

How to write console output to a txt file

This is my idea of what you are trying to do and it works fine:

public static void main(String[] args) throws IOException{

    BufferedReader in = new BufferedReader(new InputStreamReader(;

    BufferedWriter out = new BufferedWriter(new FileWriter("c://output.txt"));
    try {
        String inputLine = null;
        do {
        } while (!inputLine.equalsIgnoreCase("eof"));
        System.out.print("Write Successful");
    } catch(IOException e1) {
        System.out.println("Error during reading/writing");
    } finally {

SQL Server: Get data for only the past year

Well, I think something is missing here. User wants to get data from the last year and not from the last 365 days. There is a huge diference. In my opinion, data from the last year is every data from 2007 (if I am in 2008 now). So the right answer would be:


Then if you want to restrict this query, you can add some other filter, but always searching in the last year.

SELECT ... FROM ... WHERE YEAR(DATE) = YEAR(GETDATE()) - 1 AND DATE > '05/05/2007'

How to Execute a Python File in Notepad ++?

None of the previously proposed solutions worked for me. Slight modification needed.

After hitting F5 in Notepad++, type:

cmd /k "C:\Python27\python.exe $(FULL_CURRENT_PATH)"

The command prompt stays open so you can see the output of your script.

Check if all checkboxes are selected

$('.abc[checked!=true]').length == 0

How to add months to a date in JavaScript?

I took a look at the datejs and stripped out the code necessary to add months to a date handling edge cases (leap year, shorter months, etc):

Date.isLeapYear = function (year) { 
    return (((year % 4 === 0) && (year % 100 !== 0)) || (year % 400 === 0)); 

Date.getDaysInMonth = function (year, month) {
    return [31, (Date.isLeapYear(year) ? 29 : 28), 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][month];

Date.prototype.isLeapYear = function () { 
    return Date.isLeapYear(this.getFullYear()); 

Date.prototype.getDaysInMonth = function () { 
    return Date.getDaysInMonth(this.getFullYear(), this.getMonth());

Date.prototype.addMonths = function (value) {
    var n = this.getDate();
    this.setMonth(this.getMonth() + value);
    this.setDate(Math.min(n, this.getDaysInMonth()));
    return this;

This will add "addMonths()" function to any javascript date object that should handle edge cases. Thanks to Coolite Inc!


var myDate = new Date("01/31/2012");
var result1 = myDate.addMonths(1);

var myDate2 = new Date("01/31/2011");
var result2 = myDate2.addMonths(1);

->> newDate.addMonths -> mydate.addMonths

result1 = "Feb 29 2012"

result2 = "Feb 28 2011"

How to re-enable right click so that I can inspect HTML elements in Chrome?

Open inspect mode before navigating to the page. It worked.hehe

How to select rows that have current day's timestamp?

SELECT * FROM `table` WHERE timestamp >= CURDATE()

it is shorter , there is no need to use 'AND timestamp < CURDATE() + INTERVAL 1 DAY'

because CURDATE() always return current day

MySQL CURDATE() Function

Rounding a double value to x number of decimal places in swift

This seems to work in Swift 5.

Quite surprised there isn't a standard function for this already.

//Truncation of Double to n-decimal places with rounding

extension Double {

    func truncate(to places: Int) -> Double {
    return Double(Int((pow(10, Double(places)) * self).rounded())) / pow(10, Double(places))


Linker command failed with exit code 1 - duplicate symbol __TMRbBp

Don't double click Project.xcodeproj to start your xcode project. Instead, close your project and open the xcworkspace.

File -> Close Workspace

File -> Open -> Search your project folder for Project.xcworkspace

All my errors are gone.

Tooltips with Twitter Bootstrap

That's because these things (I mean tooltip etc) are jQuery plug-ins. And yes, they assume some basic knowledge about jQuery. I would suggest you to look for at least a basic tutorial about jQuery.

You'll always have to define which elements should have a tooltip. And I don't understand why Bootstrap should provide the class, you define those classes or yourself. Maybe you were hoping that bootstrap did automatically some magic? This magic however, can cause a lot of problems as well (unwanted side effects).

This magic can be easily achieved to just write $(".myclass").tooltip(), this line of code does exact what you want. The only thing you have to do is attach the myclass class to those elements that need to apply the tooltip thingy. (Just make sure you run that line of code after your DOM has been loaded. See below.)

$(document).ready(function() {

EDIT: apparently you can't use the class tooltip (probably because it is somewhere internally used!).

I'm just wondering why bootstrap doesn't run the code you specified with some class I can include.

The thing you want produces almost the same code as you have to do now. The biggest reason however they did not do that, is because it causes a lot of trouble. One person wants to assign it to an element with an ID; others want to assign it to elements with a specified classname; and again others want to assign it to one specified element achieved through some selection process. Those 3 options cause extra complexity, while it is already provided by jQuery. I haven't seen many plugins do what you want (just because it is needless; it really doesn't save you code).

Typescript: Type X is missing the following properties from type Y length, pop, push, concat, and 26 more. [2740]

You must specify which type the response is

  this.productService.getProducts().subscribe(res => {
          this.productsArray = res;

Try this

  this.productService.getProducts().subscribe((res: Product[]) => {
          this.productsArray = res;

Disable/Enable button in Excel/VBA

The following works for me (Excel 2010)

Dim b1 As Button

Set b1 = ActiveSheet.Buttons("Button 1")

b1.Font.ColorIndex = 15
b1.Enabled = False
Application.Cursor = xlWait
Call aLongAction
b1.Enabled = True
b1.Font.ColorIndex = 1
Application.Cursor = xlDefault

Be aware that .enabled = False does not gray out a button.

The font color has to be set explicitely to get it grayed.

How to make a page redirect using JavaScript?

You can append the values in the query string for the next page to see and process. You can wrap them inside the link tags:

<a href="your_page.php?var1=value1&var2=value2">

You separate each of those values with the & sign.

Or you can create this on a button click like this:

<input type="button" onclick="document.location.href = 'your_page.php?var1=value1&var2=value2';">

Change Placeholder Text using jQuery

try this

$('#Selector_ID').attr("placeholder", "your Placeholder");

How to get the total number of rows of a GROUP BY query?

You have to use rowCount — Returns the number of rows affected by the last SQL statement

$query = $dbh->prepare("SELECT * FROM table_name");
$count =$query->rowCount();
echo $count;

"Operation must use an updateable query" error in MS Access

I had the same error when was trying to update linked table.

The issue was that linked table had no PRIMARY KEY.

After adding primary key constraint on database side and re linking this table to access problem was solved.

Hope it will help somebody.

How to insert pandas dataframe via mysqldb into database?

Python 2 + 3


  • Pandas
  • MySQL server
  • sqlalchemy
  • pymysql: pure python mysql client


from import sql
from sqlalchemy import create_engine

engine = create_engine("mysql+pymysql://{user}:{pw}@localhost/{db}"
df.to_sql(con=engine, name='table_name', if_exists='replace')

$('body').on('click', '.anything', function(){})

You can try this:

You must follow the following format

    $('element,id,class').on('click', function(){....});

*JQuery code*

    $('body').addClass('.anything').on('click', function(){
      //do some code here i.e

sublime text2 python error message /usr/bin/python: can't find '__main__' module in ''

Edit the configuration and then in the box: Script path, select your .py file!

Returning null in a method whose signature says return int?

Do you realy want to return null ? Something you can do, is maybe initialise savedkey with 0 value and return 0 as a null value. It can be more simple.

One or more types required to compile a dynamic expression cannot be found. Are you missing references to Microsoft.CSharp.dll and System.Core.dll?

Make sure that your project is targeting the .NET framework 4.0. Visual Studio 2010 supports .NET 3.5 framework target also, but .NET 3.5 does not support the dynamic keyword.

You can adjust the framework version in the project properties. See for more info.