Programs & Examples On #Mysql error 1066

MySql Error #1066: Not unique table/alias: '%s'

Why does this SQL code give error 1066 (Not unique table/alias: 'user')?

You need to give the user table an alias the second time you join to it

e.g.

SELECT article . * , section.title, category.title, user.name, u2.name 
FROM article 
INNER JOIN section ON article.section_id = section.id 
INNER JOIN category ON article.category_id = category.id 
INNER JOIN user ON article.author_id = user.id 
LEFT JOIN user u2 ON article.modified_by = u2.id 
WHERE article.id = '1'

Not unique table/alias

Your query contains columns which could be present with the same name in more than one table you are referencing, hence the not unique error. It's best if you make the references explicit and/or use table aliases when joining.

Try

    SELECT pa.ProjectID, p.Project_Title, a.Account_ID, a.Username, a.Access_Type, c.First_Name, c.Last_Name
      FROM Project_Assigned pa
INNER JOIN Account a
        ON pa.AccountID = a.Account_ID
INNER JOIN Project p
        ON pa.ProjectID = p.Project_ID
INNER JOIN Clients c
        ON a.Account_ID = c.Account_ID
     WHERE a.Access_Type = 'Client';

How to export SQL Server database to MySQL?

if you have a MSSQL compatible SQL dump you can convert it to MySQL queries one by one using this online tool

http://burrist.com/mstomy.php

Hope it saved your time

How do I call an Angular 2 pipe with multiple arguments?

You're missing the actual pipe.

{{ myData | date:'fullDate' }}

Multiple parameters can be separated by a colon (:).

{{ myData | myPipe:'arg1':'arg2':'arg3' }}

Also you can chain pipes, like so:

{{ myData | date:'fullDate' | myPipe:'arg1':'arg2':'arg3' }}

Check if selected dropdown value is empty using jQuery

You need to use .change() event as well as using # to target element by id:

$('#EventStartTimeMin').change(function() {
    if($(this).val()===""){ 
        console.log('empty');    
    }
});

Fiddle Demo

Create an array of strings

one of the simplest ways to create a string matrix is as follow :

x = [ {'first string'} {'Second parameter} {'Third text'} {'Fourth component'} ]

Get value (String) of ArrayList<ArrayList<String>>(); in Java

A cleaner way of iterating the lists is:

// initialise the collection
collection = new ArrayList<ArrayList<String>>();
// iterate
for (ArrayList<String> innerList : collection) {
    for (String string : innerList) {
        // do stuff with string
    }
}

SQL query for today's date minus two months

If you are using SQL Server try this:

SELECT * FROM MyTable
WHERE MyDate < DATEADD(month, -2, GETDATE())

Based on your update it would be:

SELECT * FROM FB WHERE Dte <  DATEADD(month, -2, GETDATE())

SQLSTATE[28000] [1045] Access denied for user 'root'@'localhost' (using password: YES) Symfony2

In your app/config/parameters.yml

# This file is auto-generated during the composer install
parameters:
    database_driver: pdo_mysql
    database_host: 127.0.0.1
    database_port: 3306
    database_name: symfony
    database_user: root
    database_password: "your_password"
    mailer_transport: smtp
    mailer_host: 127.0.0.1
    mailer_user: null
    mailer_password: null
    locale: en
    secret: ThisTokenIsNotSoSecretChangeIt

The value of database_password should be within double or single quotes as in: "your_password" or 'your_password'.

I have seen most of users experiencing this error because they are using password with leading zero or numeric values.

unique object identifier in javascript

For browsers implementing the Object.defineProperty() method, the code below generates and returns a function that you can bind to any object you own.

This approach has the advantage of not extending Object.prototype.

The code works by checking if the given object has a __objectID__ property, and by defining it as a hidden (non-enumerable) read-only property if not.

So it is safe against any attempt to change or redefine the read-only obj.__objectID__ property after it has been defined, and consistently throws a nice error instead of silently fail.

Finally, in the quite extreme case where some other code would already have defined __objectID__ on a given object, this value would simply be returned.

var getObjectID = (function () {

    var id = 0;    // Private ID counter

    return function (obj) {

         if(obj.hasOwnProperty("__objectID__")) {
             return obj.__objectID__;

         } else {

             ++id;
             Object.defineProperty(obj, "__objectID__", {

                 /*
                  * Explicitly sets these two attribute values to false,
                  * although they are false by default.
                  */
                 "configurable" : false,
                 "enumerable" :   false,

                 /* 
                  * This closure guarantees that different objects
                  * will not share the same id variable.
                  */
                 "get" : (function (__objectID__) {
                     return function () { return __objectID__; };
                  })(id),

                 "set" : function () {
                     throw new Error("Sorry, but 'obj.__objectID__' is read-only!");
                 }
             });

             return obj.__objectID__;

         }
    };

})();

Experimental decorators warning in TypeScript compilation

I had this error with following statement

Experimental support for decorators is a feature that is subject to change in a future release. Set the 'experimentalDecorators' option in your tsconfig or jsconfig to remove this warning.ts(1219)

It was there because my Component was not registered in AppModule or (app.module.ts) i simply gave the namespace like

import { abcComponent } from '../app/abc/abc.component';

and also registered it in declarations

How to set corner radius of imageView?

Layer draws out of clip region, you need to set it to mask to bounds:

self.mainImageView.layer.masksToBounds = true

From the docs:

By default, the corner radius does not apply to the image in the layer’s contents property; it applies only to the background color and border of the layer. However, setting the masksToBounds property to true causes the content to be clipped to the rounded corners

Environment variables in Mac OS X

For 2020 Mac OS X Catalina users:

Forget about other useless answers, here only two steps needed:

  1. Create a file with the naming convention: priority-appname. Then copy-paste the path you want to add to PATH.

    E.g. 80-vscode with content /Applications/Visual Studio Code.app/Contents/Resources/app/bin/ in my case.

  2. Move that file to /etc/paths.d/. Don't forget to open a new tab(new session) in the Terminal and type echo $PATH to check that your path is added!

Notice: this method only appends your path to PATH.

MatPlotLib: Multiple datasets on the same scatter plot

I don't know, it works fine for me. Exact commands:

import scipy, pylab
ax = pylab.subplot(111)
ax.scatter(scipy.randn(100), scipy.randn(100), c='b')
ax.scatter(scipy.randn(100), scipy.randn(100), c='r')
ax.figure.show()

Linking to a specific part of a web page

That is only possible if that site has declared anchors in the page. It is done by giving a tag a name or id attribute, so look for any of those close to where you want to link to.

And then the syntax would be

<a href="page.html#anchor">text</a>

How to get box-shadow on left & right sides only

Classical approach: Negative spread

CSS box-shadow uses 4 parameters: h-shadow, v-shadow, blur, spread:

box-shadow: 10px 0 8px -8px black;

The v-shadow (verical shadow) is set to 0.

The blur parameter adds the gradient effect, but adds also a little shadow on vertical borders (the one we want to get rid of).

Negative spread reduces the shadow on all borders: you can play with it trying to remove that little vertical shadow without affecting too much the one obn the sides (it's easier for small shadows, 5 to 10px.)

Here a fiddle example.


Second approach: Absolute div on the side

Add an empty div in your element, and style it with absolute positioning so it doesen't affect the element content.

Here the fiddle with an example of left-shadow.

<div id="container">
  <div class="shadow"></div>
</div>

.shadow{
    position:absolute;
    height: 100%;
    width: 4px;
    left:0px;
    top:0px;
    box-shadow: -4px 0 3px black;
}

Third: Masking shadow

If you have a fixed background, you can hide the side-shadow effect with two masking shadows having the same color of the background and blur = 0, example:

box-shadow: 
    0 -6px white,          // Top Masking Shadow
    0 6px white,           // Bottom Masking Shadow
    7px 0 4px -3px black,  // Left-shadow
    -7px 0 4px -3px black; // Right-shadow

I've added again a negative spread (-3px) to the black shadow, so it doesn't stretch beyond the corners.

Here the fiddle.

How do I call Objective-C code from Swift?

See Apple's guide to Using Swift with Cocoa and Objective-C. This guide covers how to use Objective-C and C code from Swift and vice versa and has recommendations for how to convert a project or mix and match Objective-C/C and Swift parts in an existing project.

The compiler automatically generates Swift syntax for calling C functions and Objective-C methods. As seen in the documentation, this Objective-C:

UITableView *myTableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];

turns into this Swift code:

let myTableView: UITableView = UITableView(frame: CGRectZero, style: .Grouped)

Xcode also does this translation on the fly — you can use Open Quickly while editing a Swift file and type an Objective-C class name, and it'll take you to a Swift-ified version of the class header. (You can also get this by cmd-clicking on an API symbol in a Swift file.) And all the API reference documentation in the iOS 8 and OS X v10.10 (Yosemite) developer libraries is visible in both Objective-C and Swift forms (e.g. UIView).

Should I use past or present tense in git commit messages?

Stick with the present tense imperative because

  • it's good to have a standard
  • it matches tickets in the bug tracker which naturally have the form "implement something", "fix something", or "test something."

How exactly to use Notification.Builder

In case it helps anyone... I was having a lot of trouble with setting up notifications using the support package when testing against newer an older API's. I was able to get them to work on the newer device but would get an error testing on the old device. What finally got it working for me was to delete all the imports related to the notification functions. In particular the NotificationCompat and the TaskStackBuilder. It seems that while setting up my code in the beginning the imports where added from the newer build and not from the support package. Then when I wanted to implement these items later in eclipse, I wasn't prompted to import them again. Hope that makes sense, and that it helps someone else out :)

Read a javascript cookie by name

document.cookie="MYBIGCOOKIE=1";

Your cookies would look like:

"MYBIGCOOKIE=1; PHPSESSID=d76f00dvgrtea8f917f50db8c31cce9"

first of all read all cookies:

var read_cookies = document.cookie;

then split all cookies with ";":

var split_read_cookie = read_cookies.split(";");

then use for loop to read each value. Into loop each value split again with "=":

for (i=0;i<split_read_cookie.length;i++){
    var value=split_read_cookie[i];
    value=value.split("=");
    if(value[0]=="MYBIGCOOKIE" && value[1]=="1"){
        alert('it is 1');
    }
}

How can I parse / create a date time stamp formatted with fractional seconds UTC timezone (ISO 8601, RFC 3339) in Swift?

To further compliment Andrés Torres Marroquín and Leo Dabus, I have a version that preserves fractional seconds. I can't find it documented anywhere, but Apple truncate fractional seconds to the microsecond (3 digits of precision) on both input and output (even though specified using SSSSSSS, contrary to Unicode tr35-31).

I should stress that this is probably not necessary for most use cases. Dates online do not typically need millisecond precision, and when they do, it is often better to use a different data format. But sometimes one must interoperate with a pre-existing system in a particular way.

Xcode 8/9 and Swift 3.0-3.2

extension Date {
    struct Formatter {
        static let iso8601: DateFormatter = {
            let formatter = DateFormatter()
            formatter.calendar = Calendar(identifier: .iso8601)
            formatter.locale = Locale(identifier: "en_US_POSIX")
            formatter.timeZone = TimeZone(identifier: "UTC")
            formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSSSSXXXXX"
            return formatter
        }()
    }

    var iso8601: String {
        // create base Date format 
         var formatted = DateFormatter.iso8601.string(from: self)

        // Apple returns millisecond precision. find the range of the decimal portion
         if let fractionStart = formatted.range(of: "."),
             let fractionEnd = formatted.index(fractionStart.lowerBound, offsetBy: 7, limitedBy: formatted.endIndex) {
             let fractionRange = fractionStart.lowerBound..<fractionEnd
            // replace the decimal range with our own 6 digit fraction output
             let microseconds = self.timeIntervalSince1970 - floor(self.timeIntervalSince1970)
             var microsecondsStr = String(format: "%.06f", microseconds)
             microsecondsStr.remove(at: microsecondsStr.startIndex)
             formatted.replaceSubrange(fractionRange, with: microsecondsStr)
        }
         return formatted
    }
}

extension String {
    var dateFromISO8601: Date? {
        guard let parsedDate = Date.Formatter.iso8601.date(from: self) else {
            return nil
        }

        var preliminaryDate = Date(timeIntervalSinceReferenceDate: floor(parsedDate.timeIntervalSinceReferenceDate))

        if let fractionStart = self.range(of: "."),
            let fractionEnd = self.index(fractionStart.lowerBound, offsetBy: 7, limitedBy: self.endIndex) {
            let fractionRange = fractionStart.lowerBound..<fractionEnd
            let fractionStr = self.substring(with: fractionRange)

            if var fraction = Double(fractionStr) {
                fraction = Double(floor(1000000*fraction)/1000000)
                preliminaryDate.addTimeInterval(fraction)
            }
        }
        return preliminaryDate
    }
}

Select a random sample of results from a query result

We were given and assignment to select only two records from the list of agents..i.e 2 random records for each agent over the span of a week etc.... and below is what we got and it works

with summary as (
Select Dbms_Random.Random As Ran_Number,
             colmn1,
             colm2,
             colm3
             Row_Number() Over(Partition By col2 Order By Dbms_Random.Random) As Rank
    From table1, table2
 Where Table1.Id = Table2.Id
 Order By Dbms_Random.Random Asc)
Select tab1.col2,
             tab1.col4,
             tab1.col5,
    From Summary s
 Where s.Rank <= 2;

Adding text to ImageView in Android

Best Option to use text and image in a single view try this:

<TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"

        android:drawableBottom="@drawable/ic_launcher"

        android:text="TextView" />

How can I concatenate a string and a number in Python?

Since Python is a strongly typed language, concatenating a string and an integer as you may do in Perl makes no sense, because there's no defined way to "add" strings and numbers to each other.

Explicit is better than implicit.

...says "The Zen of Python", so you have to concatenate two string objects. You can do this by creating a string from the integer using the built-in str() function:

>>> "abc" + str(9)
'abc9'

Alternatively use Python's string formatting operations:

>>> 'abc%d' % 9
'abc9'

Perhaps better still, use str.format():

>>> 'abc{0}'.format(9)
'abc9'

The Zen also says:

There should be one-- and preferably only one --obvious way to do it.

Which is why I've given three options. It goes on to say...

Although that way may not be obvious at first unless you're Dutch.

Get a particular cell value from HTML table using JavaScript

Here is perhaps the simplest way to obtain the value of a single cell.

document.querySelector("#table").children[0].children[r].children[c].innerText

where r is the row index and c is the column index

Therefore, to obtain all cell data and put it in a multi-dimensional array:

var tableData = [];  
Array.from(document.querySelector("#table").children[0].children).forEach(function(tr){tableData.push(Array.from(tr.children).map(cell => cell.innerText))}); 
var cell = tableData[1][2];//2nd row, 3rd column

To access a specific cell's data in this multi-dimensional array, use the standard syntax: array[rowIndex][columnIndex].

What is the reason for java.lang.IllegalArgumentException: No enum const class even though iterating through values() works just fine?

Enum.valueOf() only checks the constant name, so you need to pass it "COLUMN_HEADINGS" instead of "columnHeadings". Your name property has nothing to do with Enum internals.


To address the questions/concerns in the comments:

The enum's "builtin" (implicitly declared) valueOf(String name) method will look up an enum constant with that exact name. If your input is "columnHeadings", you have (at least) three choices:

  1. Forget about the naming conventions for a bit and just name your constants as it makes most sense: enum PropName { contents, columnHeadings, ...}. This is obviously the most convenient.
  2. Convert your camelCase input into UPPER_SNAKE_CASE before calling valueOf, if you're really fond of naming conventions.
  3. Implement your own lookup method instead of the builtin valueOf to find the corresponding constant for an input. This makes most sense if there are multiple possible mappings for the same set of constants.

How do I auto-hide placeholder text upon focus using css or jquery?

Sometimes you need SPECIFICITY to make sure your styles are applied with strongest factor id Thanks for @Rob Fletcher for his great answer, in our company we have used

So please consider adding styles prefixed with the id of the app container

_x000D_
_x000D_
    #app input:focus::-webkit-input-placeholder, #app  textarea:focus::-webkit-input-placeholder {_x000D_
        color: #FFFFFF;_x000D_
    }_x000D_
_x000D_
    #app input:focus:-moz-placeholder, #app textarea:focus:-moz-placeholder {_x000D_
        color: #FFFFFF;_x000D_
    }
_x000D_
_x000D_
_x000D_

How to set all elements of an array to zero or any same value?

int myArray[10] = { 5, 5, 5, 5, 5, 5, 5, 5, 5, 5 }; // All elements of myArray are 5
int myArray[10] = { 0 };    // Will initialize all elements to 0
int myArray[10] = { 5 };    // Will initialize myArray[0] to 5 and other elements to 0
static int myArray[10]; // Will initialize all elements to 0
/************************************************************************************/
int myArray[10];// This will declare and define (allocate memory) but won’t initialize
int i;  // Loop variable
for (i = 0; i < 10; ++i) // Using for loop we are initializing
{
    myArray[i] = 5;
}
/************************************************************************************/
int myArray[10] = {[0 ... 9] = 5}; // This works only in GCC

Filtering a list of strings based on contents

Tried this out quickly in the interactive shell:

>>> l = ['a', 'ab', 'abc', 'bac']
>>> [x for x in l if 'ab' in x]
['ab', 'abc']
>>>

Why does this work? Because the in operator is defined for strings to mean: "is substring of".

Also, you might want to consider writing out the loop as opposed to using the list comprehension syntax used above:

l = ['a', 'ab', 'abc', 'bac']
result = []
for s in l:
   if 'ab' in s:
       result.append(s)

How to use Selenium with Python?

You mean Selenium WebDriver? Huh....

Prerequisite: Install Python based on your OS

Install with following command

pip install -U selenium

And use this module in your code

from selenium import webdriver

You can also use many of the following as required

from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import Select
from selenium.common.exceptions import NoSuchElementException

Here is an updated answer

I would recommend you to run script without IDE... Here is my approach

  1. USE IDE to find xpath of object / element
  2. And use find_element_by_xpath().click()

An example below shows login page automation

#ScriptName : Login.py
#---------------------
from selenium import webdriver

#Following are optional required
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import Select
from selenium.common.exceptions import NoSuchElementException

baseurl = "http://www.mywebsite.com/login.php"
username = "admin"
password = "admin"

xpaths = { 'usernameTxtBox' : "//input[@name='username']",
           'passwordTxtBox' : "//input[@name='password']",
           'submitButton' :   "//input[@name='login']"
         }

mydriver = webdriver.Firefox()
mydriver.get(baseurl)
mydriver.maximize_window()

#Clear Username TextBox if already allowed "Remember Me" 
mydriver.find_element_by_xpath(xpaths['usernameTxtBox']).clear()

#Write Username in Username TextBox
mydriver.find_element_by_xpath(xpaths['usernameTxtBox']).send_keys(username)

#Clear Password TextBox if already allowed "Remember Me" 
mydriver.find_element_by_xpath(xpaths['passwordTxtBox']).clear()

#Write Password in password TextBox
mydriver.find_element_by_xpath(xpaths['passwordTxtBox']).send_keys(password)

#Click Login button
mydriver.find_element_by_xpath(xpaths['submitButton']).click()

There is an another way that you can find xpath of any object -

  1. Install Firebug and Firepath addons in firefox
  2. Open URL in Firefox
  3. Press F12 to open Firepath developer instance
  4. Select Firepath in below browser pane and chose select by "xpath"
  5. Move cursor of the mouse to element on webpage
  6. in the xpath textbox you will get xpath of an object/element.
  7. Copy Paste xpath to the script.

Run script -

python Login.py

You can also use a CSS selector instead of xpath. CSS selectors are slightly faster than xpath in most cases, and are usually preferred over xpath (if there isn't an ID attribute on the elements you're interacting with).

Firepath can also capture the object's locator as a CSS selector if you move your cursor to the object. You'll have to update your code to use the equivalent find by CSS selector method instead -

find_element_by_css_selector(css_selector) 

How to Determine the Screen Height and Width in Flutter

Just declare a function

Size screenSize() {
return MediaQuery.of(context).size;
}

Use like below

return Container(
      width: screenSize().width,
      height: screenSize().height,
      child: ...
 )

Pointer arithmetic for void pointer in C

You have to cast it to another type of pointer before doing pointer arithmetic.

Filtering a spark dataframe based on date

df=df.filter(df["columnname"]>='2020-01-13')

How do I get a substring of a string in Python?

You've got it right there except for "end". It's called slice notation. Your example should read:

new_sub_string = myString[2:]

If you leave out the second parameter it is implicitly the end of the string.

MySQL foreign key constraints, cascade delete

If your cascading deletes nuke a product because it was a member of a category that was killed, then you've set up your foreign keys improperly. Given your example tables, you should have the following table setup:

CREATE TABLE categories (
    id int unsigned not null primary key,
    name VARCHAR(255) default null
)Engine=InnoDB;

CREATE TABLE products (
    id int unsigned not null primary key,
    name VARCHAR(255) default null
)Engine=InnoDB;

CREATE TABLE categories_products (
    category_id int unsigned not null,
    product_id int unsigned not null,
    PRIMARY KEY (category_id, product_id),
    KEY pkey (product_id),
    FOREIGN KEY (category_id) REFERENCES categories (id)
       ON DELETE CASCADE
       ON UPDATE CASCADE,
    FOREIGN KEY (product_id) REFERENCES products (id)
       ON DELETE CASCADE
       ON UPDATE CASCADE
)Engine=InnoDB;

This way, you can delete a product OR a category, and only the associated records in categories_products will die alongside. The cascade won't travel farther up the tree and delete the parent product/category table.

e.g.

products: boots, mittens, hats, coats
categories: red, green, blue, white, black

prod/cats: red boots, green mittens, red coats, black hats

If you delete the 'red' category, then only the 'red' entry in the categories table dies, as well as the two entries prod/cats: 'red boots' and 'red coats'.

The delete will not cascade any farther and will not take out the 'boots' and 'coats' categories.

comment followup:

you're still misunderstanding how cascaded deletes work. They only affect the tables in which the "on delete cascade" is defined. In this case, the cascade is set in the "categories_products" table. If you delete the 'red' category, the only records that will cascade delete in categories_products are those where category_id = red. It won't touch any records where 'category_id = blue', and it would not travel onwards to the "products" table, because there's no foreign key defined in that table.

Here's a more concrete example:

categories:     products:
+----+------+   +----+---------+
| id | name |   | id | name    |
+----+------+   +----+---------+
| 1  | red  |   | 1  | mittens |
| 2  | blue |   | 2  | boots   |
+---++------+   +----+---------+

products_categories:
+------------+-------------+
| product_id | category_id |
+------------+-------------+
| 1          | 1           | // red mittens
| 1          | 2           | // blue mittens
| 2          | 1           | // red boots
| 2          | 2           | // blue boots
+------------+-------------+

Let's say you delete category #2 (blue):

DELETE FROM categories WHERE (id = 2);

the DBMS will look at all the tables which have a foreign key pointing at the 'categories' table, and delete the records where the matching id is 2. Since we only defined the foreign key relationship in products_categories, you end up with this table once the delete completes:

+------------+-------------+
| product_id | category_id |
+------------+-------------+
| 1          | 1           | // red mittens
| 2          | 1           | // red boots
+------------+-------------+

There's no foreign key defined in the products table, so the cascade will not work there, so you've still got boots and mittens listed. There's just no 'blue boots' and no 'blue mittens' anymore.

Iterating through array - java

You should definitely encapsulate this logic into a method.

There is no benefit to repeating identical code multiple times.

Also, if you place the logic in a method and it changes, you only need to modify your code in one place.

Whether or not you want to use a 3rd party library is an entirely different decision.

Query an object array using linq

Add:

using System.Linq;

to the top of your file.

And then:

Car[] carList = ...
var carMake = 
    from item in carList
    where item.Model == "bmw" 
    select item.Make;

or if you prefer the fluent syntax:

var carMake = carList
    .Where(item => item.Model == "bmw")
    .Select(item => item.Make);

Things to pay attention to:

  • The usage of item.Make in the select clause instead if s.Make as in your code.
  • You have a whitespace between item and .Model in your where clause

how to rename an index in a cluster?

As such there is no direct method to copy or rename index in ES (I did search extensively for my own project)

However a very easy option is to use a popular migration tool [Elastic-Exporter].

http://www.retailmenot.com/corp/eng/posts/2014/12/02/elasticsearch-cluster-migration/

[PS: this is not my blog, just stumbled upon and found it good]

Thereby you can copy index/type and then delete the old one.

How to save a plot as image on the disk?

For the first question, I find dev.print to be the best when working interactively. First, you set up your plot visually and when you are happy with what you see, you can ask R to save the current plot to disk

dev.print(pdf, file="filename.pdf");

You can replace pdf with other formats such as png.

This will copy the image exactly as you see it on screen. The problem with dev.copy is that the image is often different and doesn't remember the window size and aspect ratio - it forces the plot to be square by default.

For the second question, (as others have already answered), you must direct the output to disk before you execute your plotting commands

pdf('filename.pdf')
plot( yourdata )
points (some_more_data)
dev.off() # to complete the writing process and return output to your monitor

SyntaxError: import declarations may only appear at top level of a module

I got this on Firefox (FF58). I fixed this with:

  1. It is still experimental on Firefox (from v54): You have to set to true the variable dom.moduleScripts.enabled in about:config

Source: Import page on mozilla (See Browser compatibility)

  1. Add type="module" to your script tag where you import the js file

<script type="module" src="appthatimports.js"></script>

  1. Import files have to be prefixed (./, /, ../ or http:// before)

import * from "./mylib.js"

For more examples, this blog post is good.

XMLHttpRequest Origin null is not allowed Access-Control-Allow-Origin for file:/// to file:/// (Serverless)

The way I just worked around this is not to use XMLHTTPRequest at all, but include the data needed in a separate javascript file instead. (In my case I needed a binary SQLite blob to use with https://github.com/kripken/sql.js/)

I created a file called base64_data.js (and used btoa() to convert the data that I needed and insert it into a <div> so I could copy it).

var base64_data = "U1FMaXRlIGZvcm1hdCAzAAQA ...<snip lots of data> AhEHwA==";

and then included the data in the html like normal javascript:

<div id="test"></div>

<script src="base64_data.js"></script>
<script>
    data = atob(base64_data);
    var sqldb = new SQL.Database(data);
    // Database test code from the sql.js project
    var test = sqldb.exec("SELECT * FROM Genre");
    document.getElementById("test").textContent = JSON.stringify(test);
</script>

I imagine it would be trivial to modify this to read JSON, maybe even XML; I'll leave that as an exercise for the reader ;)

What is the difference between 'my' and 'our' in Perl?

The perldoc has a good definition of our.

Unlike my, which both allocates storage for a variable and associates a simple name with that storage for use within the current scope, our associates a simple name with a package variable in the current package, for use within the current scope. In other words, our has the same scoping rules as my, but does not necessarily create a variable.

SQLSTATE[HY000] [1045] Access denied for user 'username'@'localhost' using CakePHP

I want to add to the answers posted on above that none of the solutions proposed here worked for me. My WAMP, is working on port 3308 instead of 3306 which is what it is installed by default. I found out that when working in a local environment, if you are using mysqladmin in your computer (for testing environment), and if you are working with port other than 3306, you must define your variable DB_SERVER with the value localhost:NumberOfThePort, so it will look like the following: define("DB_SERVER", "localhost:3308"). You can obtain this value by right-clicking on the WAMP icon in your taskbar (on the hidden icons section) and select Tools. You will see the section: "Port used by MySQL: NumberOfThePort"

This will fix your connection to your database.

This was the error I got: Error: SQLSTATE[HY1045] Access denied for user 'username'@'localhost' on line X.

I hope this helps you out.

:)

Is it acceptable and safe to run pip install under sudo?

Use a virtual environment:

$ virtualenv myenv
.. some output ..
$ source myenv/bin/activate
(myenv) $ pip install what-i-want

You only use sudo or elevated permissions when you want to install stuff for the global, system-wide Python installation.

It is best to use a virtual environment which isolates packages for you. That way you can play around without polluting the global python install.

As a bonus, virtualenv does not need elevated permissions.

When should I use double or single quotes in JavaScript?

There are people that claim to see performance differences: old mailing list thread. But I couldn't find any of them to be confirmed.

The main thing is to look at what kind of quotes (double or single) you are using inside your string. It helps to keep the number of escapes low. For instance, when you are working with HTML content inside your strings, it is easier to use single quotes so that you don't have to escape all double quotes around the attributes.

Copy directory to another directory using ADD command

You can use COPY. You need to specify the directory explicitly. It won't be created by itself

COPY go /usr/local/go

Reference: Docker CP reference

How to insert a character in a string at a certain position?

I think a simpler and more elegant solution to insert a String in a certain position would be this one-liner:

target.replaceAll("^(.{" + position + "})", "$1" + insert);

For example, to insert a missing : into a time String:

"-0300".replaceAll("^(.{3})", "$1:");

What it does is, matches position characters from the beginning of the string, groups that, and replaces the group with itself ($1) followed by the insert string. Mind the replaceAll, even though there's always one occurrence, because the first parameter must be a regex.

Of course it does not have the same performance as the StringBuilder solution, but I believe the succinctness and elegance as a simple and easier to read one-liner (compared to a huge method) is sufficient for making it the preferred solution in most non performance-critical use-cases.

Note I'm solving the generic problem in the title for documentation reasons, of course if you are dealing with decimal numbers you should use the domain-specific solutions already proposed.

Writing a list to a file with Python

with open ("test.txt","w")as fp:
   for line in list12:
       fp.write(line+"\n")

Can I use VARCHAR as the PRIMARY KEY?

Of course you can, in the sense that your RDBMS will let you do it. The answer to a question of whether or not you should do it is different, though: in most situations, values that have a meaning outside your database system should not be chosen to be a primary key.

If you know that the value is unique in the system that you are modeling, it is appropriate to add a unique index or a unique constraint to your table. However, your primary key should generally be some "meaningless" value, such as an auto-incremented number or a GUID.

The rationale for this is simple: data entry errors and infrequent changes to things that appear non-changeable do happen. They become much harder to fix on values which are used as primary keys.

Passing variable number of arguments around

There's no way of calling (eg) printf without knowing how many arguments you're passing to it, unless you want to get into naughty and non-portable tricks.

The generally used solution is to always provide an alternate form of vararg functions, so printf has vprintf which takes a va_list in place of the .... The ... versions are just wrappers around the va_list versions.

How to make ng-repeat filter out duplicate results

I had an array of strings, not objects and i used this approach:

ng-repeat="name in names | unique"

with this filter:

angular.module('app').filter('unique', unique);
function unique(){
return function(arry){
        Array.prototype.getUnique = function(){
        var u = {}, a = [];
        for(var i = 0, l = this.length; i < l; ++i){
           if(u.hasOwnProperty(this[i])) {
              continue;
           }
           a.push(this[i]);
           u[this[i]] = 1;
        }
        return a;
    };
    if(arry === undefined || arry.length === 0){
          return '';
    }
    else {
         return arry.getUnique(); 
    }

  };
}

How to unit test abstract classes: extend with stubs?

This is the pattern I usually follow when setting up a harness for testing an abstract class:

public abstract class MyBase{
  /*...*/
  public abstract void VoidMethod(object param1);
  public abstract object MethodWithReturn(object param1);
  /*,,,*/
}

And the version I use under test:

public class MyBaseHarness : MyBase{
  /*...*/
  public Action<object> VoidMethodFunction;
  public override void VoidMethod(object param1){
    VoidMethodFunction(param1);
  }
  public Func<object, object> MethodWithReturnFunction;
  public override object MethodWithReturn(object param1){
    return MethodWihtReturnFunction(param1);
  }
  /*,,,*/
}

If the abstract methods are called when I don't expect it, the tests fail. When arranging the tests, I can easily stub out the abstract methods with lambdas that perform asserts, throw exceptions, return different values, etc.

How do I access the HTTP request header fields via JavaScript?

Almost by definition, the client-side JavaScript is not at the receiving end of a http request, so it has no headers to read. Most commonly, your JavaScript is the result of an http response. If you are trying to get the values of the http request that generated your response, you'll have to write server side code to embed those values in the JavaScript you produce.

It gets a little tricky to have server-side code generate client side code, so be sure that is what you need. For instance, if you want the User-agent information, you might find it sufficient to get the various values that JavaScript provides for browser detection. Start with navigator.appName and navigator.appVersion.

C++, copy set to vector

You haven't reserved enough space in your vector object to hold the contents of your set.

std::vector<double> output(input.size());
std::copy(input.begin(), input.end(), output.begin());

How to send a POST request from node.js Express?

I use superagent, which is simliar to jQuery.

Here is the docs

And the demo like:

var sa = require('superagent');
sa.post('url')
  .send({key: value})
  .end(function(err, res) {
    //TODO
  });

Select dropdown with fixed width cutting off content in IE

For my layout, I didn't want a hack (no width increasing, no on click with auto and then coming to original). It broke my existing layout. I just wanted it to work normally like other browsers.

I found this to be exactly like that :-

http://www.jquerybyexample.net/2012/05/fix-for-ie-select-dropdown-with-fixed.html

Relative path in HTML

The relative pathing is based on the document level of the client side i.e. the URL level of the document as seen in the browser.

If the URL of your website is: http://www.example.com/mywebsite/ then starting at the root level starts above the "mywebsite" folder path.

javascript date + 7 days

_x000D_
_x000D_
var date = new Date();_x000D_
date.setDate(date.getDate() + 7);_x000D_
_x000D_
console.log(date);
_x000D_
_x000D_
_x000D_

And yes, this also works if date.getDate() + 7 is greater than the last day of the month. See MDN for more information.

Link to reload current page

<a href="/home" target="_self">Reload the page</a>

How to specify the default error page in web.xml?

You can also do something like that:

<error-page>
    <error-code>403</error-code>
    <location>/403.html</location>
</error-page>

<error-page>
    <location>/error.html</location>
</error-page>

For error code 403 it will return the page 403.html, and for any other error code it will return the page error.html.

How to resolve a Java Rounding Double issue

To control the precision of floating point arithmetic, you should use java.math.BigDecimal. Read The need for BigDecimal by John Zukowski for more information.

Given your example, the last line would be as following using BigDecimal.

import java.math.BigDecimal;

BigDecimal premium = BigDecimal.valueOf("1586.6");
BigDecimal netToCompany = BigDecimal.valueOf("708.75");
BigDecimal commission = premium.subtract(netToCompany);
System.out.println(commission + " = " + premium + " - " + netToCompany);

This results in the following output.

877.85 = 1586.6 - 708.75

Check if PHP-page is accessed from an iOS device

preg_match("/iPhone|Android|iPad|iPod|webOS/", $_SERVER['HTTP_USER_AGENT'], $matches);
$os = current($matches);

switch($os){
   case 'iPhone': /*do something...*/ break;
   case 'Android': /*do something...*/ break;
   case 'iPad': /*do something...*/ break;
   case 'iPod': /*do something...*/ break;
   case 'webOS': /*do something...*/ break;
}

Show "loading" animation on button click

The best loading and blocking that particular div for ajax call until it succeeded is Blockui

go through this link http://www.malsup.com/jquery/block/#element

example usage:

 <span class="no-display smallLoader"><img src="/images/loader-small.png" /></span>

script

jQuery.ajax(
{   
 url: site_path+"/restaurantlist/addtocart",
 type: "POST",
 success: function (data) {
   jQuery("#id").unblock(); 
},
beforeSend:function (data){
    jQuery("#id").block({ 
    message: jQuery(".smallLoader").html(), 
    css: { 
         border: 'none', 
         backgroundColor: 'none'
    },
    overlayCSS: { backgroundColor: '#afafaf' } 
    });

}
});

hope this helps really it is very interactive.

Trigger function when date is selected with jQuery UI datepicker

Working demo : http://jsfiddle.net/YbLnj/

Documentation: http://jqueryui.com/demos/datepicker/

code

$("#dt").datepicker({
    onSelect: function(dateText, inst) {
        var date = $(this).val();
        var time = $('#time').val();
        alert('on select triggered');
        $("#start").val(date + time.toString(' HH:mm').toString());

    }
});

Removing fields from struct or hiding them in JSON Response

I also faced this problem, at first I just wanted to specialize the responses in my http handler. My first approach was creating a package that copies the information of a struct to another struct and then marshal that second struct. I did that package using reflection, so, never liked that approach and also I wasn't dynamically.

So I decided to modify the encoding/json package to do this. The functions Marshal, MarshalIndent and (Encoder) Encode additionally receives a

type F map[string]F

I wanted to simulate a JSON of the fields that are needed to marshal, so it only marshals the fields that are in the map.

https://github.com/JuanTorr/jsont

package main

import (
    "fmt"
    "log"
    "net/http"

    "github.com/JuanTorr/jsont"
)

type SearchResult struct {
    Date        string      `json:"date"`
    IdCompany   int         `json:"idCompany"`
    Company     string      `json:"company"`
    IdIndustry  interface{} `json:"idIndustry"`
    Industry    string      `json:"industry"`
    IdContinent interface{} `json:"idContinent"`
    Continent   string      `json:"continent"`
    IdCountry   interface{} `json:"idCountry"`
    Country     string      `json:"country"`
    IdState     interface{} `json:"idState"`
    State       string      `json:"state"`
    IdCity      interface{} `json:"idCity"`
    City        string      `json:"city"`
} //SearchResult

type SearchResults struct {
    NumberResults int            `json:"numberResults"`
    Results       []SearchResult `json:"results"`
} //type SearchResults
func main() {
    msg := SearchResults{
        NumberResults: 2,
        Results: []SearchResult{
            {
                Date:        "12-12-12",
                IdCompany:   1,
                Company:     "alfa",
                IdIndustry:  1,
                Industry:    "IT",
                IdContinent: 1,
                Continent:   "america",
                IdCountry:   1,
                Country:     "México",
                IdState:     1,
                State:       "CDMX",
                IdCity:      1,
                City:        "Atz",
            },
            {
                Date:        "12-12-12",
                IdCompany:   2,
                Company:     "beta",
                IdIndustry:  1,
                Industry:    "IT",
                IdContinent: 1,
                Continent:   "america",
                IdCountry:   2,
                Country:     "USA",
                IdState:     2,
                State:       "TX",
                IdCity:      2,
                City:        "XYZ",
            },
        },
    }
    fmt.Println(msg)
    http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {

        //{"numberResults":2,"results":[{"date":"12-12-12","idCompany":1,"idIndustry":1,"country":"México"},{"date":"12-12-12","idCompany":2,"idIndustry":1,"country":"USA"}]}
        err := jsont.NewEncoder(w).Encode(msg, jsont.F{
            "numberResults": nil,
            "results": jsont.F{
                "date":       nil,
                "idCompany":  nil,
                "idIndustry": nil,
                "country":    nil,
            },
        })
        if err != nil {
            log.Fatal(err)
        }
    })

    http.ListenAndServe(":3009", nil)
}

How to get key names from JSON using jq

To print keys on one line as csv:

echo '{"b":"2","a":"1"}' | jq -r 'keys | [ .[] | tostring ] | @csv'

Output:

"a","b"

For csv completeness ... to print values on one line as csv:

echo '{"b":"2","a":"1"}' | jq -rS . | jq -r '. | [ .[] | tostring ] | @csv'

Output:

"1","2"

Change marker size in Google maps V3

This answer expounds on John Black's helpful answer, so I will repeat some of his answer content in my answer.

The easiest way to resize a marker seems to be leaving argument 2, 3, and 4 null and scaling the size in argument 5.

var pinIcon = new google.maps.MarkerImage(
    "http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=%E2%80%A2|FFFF00",
    null, /* size is determined at runtime */
    null, /* origin is 0,0 */
    null, /* anchor is bottom center of the scaled image */
    new google.maps.Size(42, 68)
);  

As an aside, this answer to a similar question asserts that defining marker size in the 2nd argument is better than scaling in the 5th argument. I don't know if this is true.

Leaving arguments 2-4 null works great for the default google pin image, but you must set an anchor explicitly for the default google pin shadow image, or it will look like this:

what happens when you leave anchor null on an enlarged shadow

The bottom center of the pin image happens to be collocated with the tip of the pin when you view the graphic on the map. This is important, because the marker's position property (marker's LatLng position on the map) will automatically be collocated with the visual tip of the pin when you leave the anchor (4th argument) null. In other words, leaving the anchor null ensures the tip points where it is supposed to point.

However, the tip of the shadow is not located at the bottom center. So you need to set the 4th argument explicitly to offset the tip of the pin shadow so the shadow's tip will be colocated with the pin image's tip.

By experimenting I found the tip of the shadow should be set like this: x is 1/3 of size and y is 100% of size.

var pinShadow = new google.maps.MarkerImage(
    "http://chart.apis.google.com/chart?chst=d_map_pin_shadow",
    null,
    null,
    /* Offset x axis 33% of overall size, Offset y axis 100% of overall size */
    new google.maps.Point(40, 110), 
    new google.maps.Size(120, 110)); 

to give this:

offset the enlarged shadow anchor explicitly

Proper way to get page content

A simple, fast way to get the content by id :

echo get_post_field('post_content', $id);

And if you want to get the content formatted :

echo apply_filters('the_content', get_post_field('post_content', $id));

Works with pages, posts & custom posts.

A connection was successfully established with the server, but then an error occurred during the login process. (Error Number: 233)

To add on top of @Pranav Singh and @Rahul Tripathi answer. After doing all the mentioned by those 2 users, my .net app still wasnt connecting to the database. My solution was.

Open Sql Server Configuration Manager, go to Network configuration of SQL SERVER, click on protocols, right click on TCP/IP and select enabled. I also right clicked on it opened properties, Ip directions, and scrolled to the bottom (IPAII , and there in TCP Port, I did setup a port (1433 is supposed to be default))

How to put a symbol above another in LaTeX?

${a \atop \#}$

or

${a \above 0pt \#}$

Fatal error: Call to a member function query() on null

First, you declared $db outside the function. If you want to use it inside the function, you should put this at the begining of your function code:

global $db;

And I guess, when you wrote:

if($result->num_rows){
        return (mysqli_result($query, 0) == 1) ? true : false;

what you really wanted was:

if ($result->num_rows==1) { return true; } else { return false; }

openpyxl - adjust column width size

You could estimate (or use a mono width font) to achieve this. Let's assume data is a nested array like [['a1','a2'],['b1','b2']]

We can get the max characters in each column. Then set the width to that. Width is exactly the width of a monospace font (if not changing other styles at least). Even if you use a variable width font it is a decent estimation. This will not work with formulas.

from openpyxl.utils import get_column_letter

column_widths = []
for row in data:
    for i, cell in enumerate(row):
        if len(column_widths) > i:
            if len(cell) > column_widths[i]:
                column_widths[i] = len(cell)
        else:
            column_widths += [len(cell)]

for i, column_width in enumerate(column_widths):
    worksheet.column_dimensions[get_column_letter(i+1)].width = column_width

A bit of a hack but your reports will be more readable.

Why call git branch --unset-upstream to fixup?

torek's answer is probably perfect, but I just wanted for the record to mention another case which is different than the one described in the original question but the same error may appear (as it may help others with similar problem):

I have created an empty (new) repo using git init --bare on one of my servers. Then I have git cloned it to a local workspace on my PC.

After committing a single version on the local repo I got that error after calling git status.

Following torek's answer, I understand that what happened is that the first commit on local working directory repo created "master" branch. But on the remote repo (on the server) there was never anything, so there was not even a "master" (remotes/origin/master) branch.

After running git push origin master from local repo the remote repo finally had a master branch. This stopped the error from appearing.

So to conclude - one may get such an error for a fresh new remote repo with zero commits since it has no branch, including "master".

List the queries running on SQL Server

SELECT 
    p.spid, p.status, p.hostname, p.loginame, p.cpu, r.start_time, t.text
FROM
    sys.dm_exec_requests as r,
    master.dbo.sysprocesses as p
    CROSS APPLY sys.dm_exec_sql_text(p.sql_handle) t
WHERE
    p.status NOT IN ('sleeping', 'background')
AND r.session_id = p.spid

And

KILL @spid

How to select from subquery using Laravel Query Builder?

Laravel v5.6.12 (2018-03-14) added fromSub() and fromRaw() methods to query builder (#23476).

The accepted answer is correct but can be simplified into:

DB::query()->fromSub(function ($query) {
    $query->from('abc')->groupBy('col1');
}, 'a')->count();

The above snippet produces the following SQL:

select count(*) as aggregate from (select * from `abc` group by `col1`) as `a`

Use stored procedure to insert some data into a table

If you have the table definition to have an IDENTITY column e.g. IDENTITY(1,1) then don't include MyId in your INSERT INTO statement. The point of IDENTITY is it gives it the next unused value as the primary key value.

insert into MYDB.dbo.MainTable (MyFirstName, MyLastName, MyAddress, MyPort)
values(@myFirstName, @myLastName, @myAddress, @myPort)

There is then no need to pass the @MyId parameter into your stored procedure either. So change it to:

CREATE PROCEDURE [dbo].[sp_Test]
@myFirstName nvarchar(50)
,@myLastName nvarchar(50)
,@myAddress nvarchar(MAX)
,@myPort int

AS 

If you want to know what the ID of the newly inserted record is add

SELECT @@IDENTITY

to the end of your procedure. e.g. http://msdn.microsoft.com/en-us/library/ms187342.aspx

You will then be able to pick this up in which ever way you are calling it be it SQL or .NET.

P.s. a better way to show you table definision would have been to script the table and paste the text into your stackoverflow browser window because your screen shot is missing the column properties part where IDENTITY is set via the GUI. To do that right click the table 'Script Table as' --> 'CREATE to' --> Clipboard. You can also do File or New Query Editor Window (all self explanitory) experient and see what you get.

Does dispatch_async(dispatch_get_main_queue(), ^{...}); wait until done?

OK, there are two ways of doing that:

// GLOBAL_CONCURRENT_QUEUE


- (void)doCalculationsAndUpdateUIsWith_GlobalQUEUE 
{
    dispatch_queue_t globalConcurrentQ = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_async(globalConcurrentQ, ^{

       // DATA PROCESSING 1
       sleep(1);
       NSLog(@"Hello world chekpoint 1");
       dispatch_sync(dispatch_get_main_queue(), ^{
           // UI UPDATION 1
           sleep(1);
           NSLog(@"Hello world chekpoint 2");
       });

        /* the control to come here after UI UPDATION 1 */
        sleep(1);
        NSLog(@"Hello world chekpoint 3");
        // DATA PROCESSING 2

        dispatch_sync(dispatch_get_main_queue(), ^{
            // UI UPDATION 2
            sleep(1);
            NSLog(@"Hello world chekpoint 4");
        });

        /* the control to come here after UI UPDATION 2 */
        sleep(1);
        NSLog(@"Hello world chekpoint 5");
        // DATA PROCESSING 3

        dispatch_sync(dispatch_get_main_queue(), ^{
            // UI UPDATION 3
            sleep(1);
            NSLog(@"Hello world chekpoint 6");
        });
   });
}



// SERIAL QUEUE
- (void)doCalculationsAndUpdateUIsWith_GlobalQUEUE 
{

    dispatch_queue_t serialQ = dispatch_queue_create("com.example.MyQueue", NULL);
    dispatch_async(serialQ, ^{

       // DATA PROCESSING 1
       sleep(1);
       NSLog(@"Hello world chekpoint 1");

       dispatch_sync(dispatch_get_main_queue(), ^{
           // UI UPDATION 1
           sleep(1);
           NSLog(@"Hello world chekpoint 2");
       });


       sleep(1);
       NSLog(@"Hello world chekpoint 3");
       // DATA PROCESSING 2

       dispatch_sync(dispatch_get_main_queue(), ^{
           // UI UPDATION 2
           sleep(1);
           NSLog(@"Hello world chekpoint 4");
       });  
   });
}

How do I use select with date condition?

if you do not want to be bothered by the date format, you could compare the column with the general date format, for example

select * From table where cast (RegistrationDate as date) between '20161201' and '20161220'

make sure the date is in DATE format, otherwise cast (col as DATE)

Window.open and pass parameters by post method

I've used this in the past, since we typically use razor syntax for coding

@using (Html.BeginForm("actionName", "controllerName", FormMethod.Post, new { target = "_blank" }))

{

// add hidden and form filed here

}

What are the applications of binary trees?

To squabble about the performance of binary-trees is meaningless - they are not a data structure, but a family of data structures, all with different performance characteristics. While it is true that unbalanced binary trees perform much worse than self-balancing binary trees for searching, there are many binary trees (such as binary tries) for which "balancing" has no meaning.

Applications of binary trees

  • Binary Search Tree - Used in many search applications where data is constantly entering/leaving, such as the map and set objects in many languages' libraries.
  • Binary Space Partition - Used in almost every 3D video game to determine what objects need to be rendered.
  • Binary Tries - Used in almost every high-bandwidth router for storing router-tables.
  • Hash Trees - used in p2p programs and specialized image-signatures in which a hash needs to be verified, but the whole file is not available.
  • Heaps - Used in implementing efficient priority-queues, which in turn are used for scheduling processes in many operating systems, Quality-of-Service in routers, and A* (path-finding algorithm used in AI applications, including robotics and video games). Also used in heap-sort.
  • Huffman Coding Tree (Chip Uni) - used in compression algorithms, such as those used by the .jpeg and .mp3 file-formats.
  • GGM Trees - Used in cryptographic applications to generate a tree of pseudo-random numbers.
  • Syntax Tree - Constructed by compilers and (implicitly) calculators to parse expressions.
  • Treap - Randomized data structure used in wireless networking and memory allocation.
  • T-tree - Though most databases use some form of B-tree to store data on the drive, databases which keep all (most) their data in memory often use T-trees to do so.

The reason that binary trees are used more often than n-ary trees for searching is that n-ary trees are more complex, but usually provide no real speed advantage.

In a (balanced) binary tree with m nodes, moving from one level to the next requires one comparison, and there are log_2(m) levels, for a total of log_2(m) comparisons.

In contrast, an n-ary tree will require log_2(n) comparisons (using a binary search) to move to the next level. Since there are log_n(m) total levels, the search will require log_2(n)*log_n(m) = log_2(m) comparisons total. So, though n-ary trees are more complex, they provide no advantage in terms of total comparisons necessary.

(However, n-ary trees are still useful in niche-situations. The examples that come immediately to mind are quad-trees and other space-partitioning trees, where divisioning space using only two nodes per level would make the logic unnecessarily complex; and B-trees used in many databases, where the limiting factor is not how many comparisons are done at each level but how many nodes can be loaded from the hard-drive at once)

Setting font on NSAttributedString on UITextView disregards line spacing

I found your question because I was also fighting with NSAttributedString. For me, the beginEditing and endEditing methods did the trick, like stated in Changing an Attributed String. Apart from that, the lineSpacing is set with setLineSpacing on the paragraphStyle.

So you might want to try changing your code to:

NSString *string = @" Hello \n world";
attrString = [[NSMutableAttributedString alloc] initWithString:string];
NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle defaultParagraphStyle] mutableCopy];

[paragraphStyle setLineSpacing:20]  // Or whatever (positive) value you like...    
[attrSting beginEditing];

[attrString addAttribute:NSFontAttributeName value:[UIFont boldSystemFontOfSize:20] range:NSMakeRange(0, string.length)];
[attrString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, string.length)];

[attrString endEditing];

mainTextView.attributedText = attrString;

Didn't test this exact code though, btw, but mine looks nearly the same.

EDIT:

Meanwhile, I've tested it, and, correct me if I'm wrong, the - beginEditing and - endEditing calls seem to be of quite an importance.

Now() function with time trim

You could also use Format$(Now(), "Short Date") or whatever date format you want. Be aware, this function will return the Date as a string, so using Date() is a better approach.

What is the difference between dynamic and static polymorphism in Java?

Following on from Naresh's answer, dynamic polymorphism is only 'dynamic' in Java because of the presence of the virtual machine and its ability to interpret the code at run time rather than the code running natively.

In C++ it must be resolved at compile time if it is being compiled to a native binary using gcc, obviously; however, the runtime jump and thunk in the virtual table is still referred to as a 'lookup' or 'dynamic'. If C inherits B, and you declare B* b = new C(); b->method1();, b will be resolved by the compiler to point to a B object inside C (for a simple class inherits a class situation, the B object inside C and C will start at the same memory address so nothing is required to be done; it will be pointing at the vptr that they both use). If C inherits B and A, the virtual function table of the A object inside C entry for method1 will have a thunk which will offset the pointer to the start of the encapsulating C object and then pass it to the real A::method1() in the text segment which C has overridden. For C* c = new C(); c->method1(), c will be pointing to the outer C object already and the pointer will be passed to C::method1() in the text segment. Refer to: http://www.programmersought.com/article/2572545946/

In java, for B b = new C(); b.method1();, the virtual machine is able to dynamically check the type of the object paired with b and can pass the correct pointer and call the correct method. The extra step of the virtual machine eliminates the need for virtual function tables or the type being resolved at compile time, even when it could be known at compile time. It's just a different way of doing it which makes sense when a virtual machine is involved and code is only compiled to bytecode.

SQL Server : How to test if a string has only digit characters

Method that will work. The way it is used above will not work.

declare @str varchar(50)='79136'

select 
  case 
    when  @str LIKE replicate('[0-9]',LEN(@str)) then 1 
    else 0 
  end

declare @str2 varchar(50)='79D136'

select 
  case 
    when  @str2 LIKE replicate('[0-9]',LEN(@str)) then 1 
    else 0 
  end

jQuery add text to span within a div

You can use append or prepend

The .append() method inserts the specified content as the last child of each element in the jQuery collection (To insert it as the first child, use .prepend()).

$("#tagscloud span").append(second);
$("#tagscloud span").append(third);
$("#tagscloud span").prepend(first);

how to run two commands in sudo?

sudo can run multiple commands via a shell, for example:

$ sudo -s -- 'whoami; whoami'
root
root

Your command would be something like:

sudo -u db2inst1 -s -- "db2 connect to ttt; db2 UPDATE CONTACT SET EMAIL_ADDRESS = '[email protected]'"

If your sudo version doesn't work with semicolons with -s (apparently, it doesn't if compiled with certain options), you can use

sudo -- sh -c 'whoami; whoami'

instead, which basically does the same thing but makes you name the shell explicitly.

Making a button invisible by clicking another button in HTML

I found problems with the elements being moved around using some of the above, so if you have objects next to each other that you want to just swap this worked best for me

document.getElementById('uncheckAll').hidden = false;
document.getElementById('checkAll').hidden = true;

How to compare two columns in Excel and if match, then copy the cell next to it

try this formula in column E:

=IF( AND( ISNUMBER(D2), D2=G2), H2, "")

your error is the number test, ISNUMBER( ISMATCH(D2,G:G,0) )

you do check if ismatch is-a-number, (i.e. isNumber("true") or isNumber("false"), which is not!.

I hope you understand my explanation.

jquery get height of iframe content when loaded

Accepted answer's $('iframe').load will now produce a.indexOf is not a function error. Can be updated to:

$('iframe').on('load', function() {
  // ...
});

Few others similar to .load deprecated since jQuery 1.8: "Uncaught TypeError: a.indexOf is not a function" error when opening new foundation project

Remove a symlink to a directory

Assuming it actually is a symlink,

$ rm -d symlink

It should figure it out, but since it can't we enable the latent code that was intended for another case that no longer exists but happens to do the right thing here.

jQuery How to Get Element's Margin and Padding?

I've a snippet that shows, how to get the spacings of elements with jQuery:

/* messing vertical spaces of block level elements with jQuery in pixels */

console.clear();

var jObj = $('selector');

for(var i = 0, l = jObj.length; i < l; i++) {
  //jObj.eq(i).css('display', 'block');
  console.log('jQuery object:', jObj.eq(i));
  console.log('plain element:', jObj[i]);

  console.log('without spacings                - jObj.eq(i).height():         ', jObj.eq(i).height());
  console.log('with padding                    - jObj[i].clientHeight:        ', jObj[i].clientHeight);
  console.log('with padding and border         - jObj.eq(i).outerHeight():    ', jObj.eq(i).outerHeight());
  console.log('with padding, border and margin - jObj.eq(i).outerHeight(true):', jObj.eq(i).outerHeight(true));
  console.log('total vertical spacing:                                        ', jObj.eq(i).outerHeight(true) - jObj.eq(i).height());
}

Inline IF Statement in C#

You may define your enum like so and use cast where needed

public enum MyEnum
{
    VariablePeriods = 1,
    FixedPeriods = 2
}

Usage

public class Entity
{
    public MyEnum Property { get; set; }
}

var returnedFromDB = 1;
var entity = new Entity();
entity.Property = (MyEnum)returnedFromDB;

Apache Maven install "'mvn' not recognized as an internal or external command" after setting OS environmental variables?

I had this same problem, restart the command prompt and then check try mvn --version. It was probably set and working the whole time but command prompt needed to be restarted to be able to access the new system variable.

How to enable mod_rewrite for Apache 2.2

There's obviously more than one way to do it, but I would suggest using the more standard:

ErrorDocument 404 /index.php?page=404

Clearing _POST array fully

Yes, that is fine. $_POST is just another variable, except it has (super)global scope.

$_POST = array();

...will be quite enough. The loop is useless. It's probably best to keep it as an array rather than unset it, in case other files are attempting to read it and assuming it is an array.

PHP ternary operator vs null coalescing operator

Both of them behave differently when it comes to dynamic data handling.

If the variable is empty ( '' ) the null coalescing will treat the variable as true but the shorthand ternary operator won't. And that's something to have in mind.

$a = NULL;
$c = '';

print $a ?? '1b';
print "\n";

print $a ?: '2b';
print "\n";

print $c ?? '1d';
print "\n";

print $c ?: '2d';
print "\n";

print $e ?? '1f';
print "\n";

print $e ?: '2f';

And the output:

1b
2b

2d
1f

Notice: Undefined variable: e in /in/ZBAa1 on line 21
2f

Link: https://3v4l.org/ZBAa1

JavaScript pattern for multiple constructors

This is the example given for multiple constructors in Programming in HTML5 with JavaScript and CSS3 - Exam Ref.

function Book() {
    //just creates an empty book.
}


function Book(title, length, author) {
    this.title = title;
    this.Length = length;
    this.author = author;
}

Book.prototype = {
    ISBN: "",
    Length: -1,
    genre: "",
    covering: "",
    author: "",
    currentPage: 0,
    title: "",

    flipTo: function FlipToAPage(pNum) {
        this.currentPage = pNum;
    },

    turnPageForward: function turnForward() {
        this.flipTo(this.currentPage++);
    },

    turnPageBackward: function turnBackward() {
        this.flipTo(this.currentPage--);
    }
};

var books = new Array(new Book(), new Book("First Edition", 350, "Random"));

YouTube API to fetch all videos on a channel

To get channels list :

Get Channels list by forUserName:

https://www.googleapis.com/youtube/v3/channels?part=snippet,contentDetails,statistics&forUsername=Apple&key=

Get channels list by channel id:

https://www.googleapis.com/youtube/v3/channels/?part=snippet,contentDetails,statistics&id=UCE_M8A5yxnLfW0KghEeajjw&key=

Get Channel sections:

https://www.googleapis.com/youtube/v3/channelSections?part=snippet,contentDetails&channelId=UCE_M8A5yxnLfW0KghEeajjw&key=

To get Playlists :

Get Playlists by Channel ID:

https://www.googleapis.com/youtube/v3/playlists?part=snippet,contentDetails&channelId=UCq-Fj5jknLsUf-MWSy4_brA&maxResults=50&key=

Get Playlists by Channel ID with pageToken:

https://www.googleapis.com/youtube/v3/playlists?part=snippet,contentDetails&channelId=UCq-Fj5jknLsUf-MWSy4_brA&maxResults=50&key=&pageToken=CDIQAA

To get PlaylistItems :

Get PlaylistItems list by PlayListId:

https://www.googleapis.com/youtube/v3/playlistItems?part=snippet,contentDetails&maxResults=25&playlistId=PLHFlHpPjgk70Yv3kxQvkDEO5n5tMQia5I&key=

To get videos :

Get videos list by video id:

https://www.googleapis.com/youtube/v3/videos?part=snippet,contentDetails,statistics&id=YxLCwfA1cLw&key=

Get videos list by multiple videos id:

https://www.googleapis.com/youtube/v3/videos?part=snippet,contentDetails,statistics&id=YxLCwfA1cLw,Qgy6LaO3SB0,7yPJXGO2Dcw&key=

Get comments list

Get Comment list by video ID:

https://www.googleapis.com/youtube/v3/commentThreads?part=snippet,replies&videoId=el****kQak&key=A**********k

Get Comment list by channel ID:

https://www.googleapis.com/youtube/v3/commentThreads?part=snippet,replies&channelId=U*****Q&key=AI********k

Get Comment list by allThreadsRelatedToChannelId:

https://www.googleapis.com/youtube/v3/commentThreads?part=snippet,replies&allThreadsRelatedToChannelId=UC*****ntcQ&key=AI*****k

Here all api's are Get approach.

Based on channel id we con't get all videos directly, that's the important point here.

For integration https://developers.google.com/youtube/v3/quickstart/ios?ver=swift

What's the difference between unit tests and integration tests?

A unit test is a test written by the programmer to verify that a relatively small piece of code is doing what it is intended to do. They are narrow in scope, they should be easy to write and execute, and their effectiveness depends on what the programmer considers to be useful. The tests are intended for the use of the programmer, they are not directly useful to anybody else, though, if they do their job, testers and users downstream should benefit from seeing fewer bugs.

Part of being a unit test is the implication that things outside the code under test are mocked or stubbed out. Unit tests shouldn't have dependencies on outside systems. They test internal consistency as opposed to proving that they play nicely with some outside system.

An integration test is done to demonstrate that different pieces of the system work together. Integration tests can cover whole applications, and they require much more effort to put together. They usually require resources like database instances and hardware to be allocated for them. The integration tests do a more convincing job of demonstrating the system works (especially to non-programmers) than a set of unit tests can, at least to the extent the integration test environment resembles production.

Actually "integration test" gets used for a wide variety of things, from full-on system tests against an environment made to resemble production to any test that uses a resource (like a database or queue) that isn't mocked out. At the lower end of the spectrum an integration test could be a junit test where a repository is exercised against an in-memory database, toward the upper end it could be a system test verifying applications can exchange messages.

How do we use runOnUiThread in Android?

runOnUiThread(new Runnable() {
                public void run() {
                //Do something on UiThread
            }
        });

Can't connect to MySQL server on 'localhost' (10061) after Installation

The main reason for this kind of error is you might have uninstalled Mysql server application. Install it and then give it a go.

Is there a function to copy an array in C/C++?

Use memcpy in C, std::copy in C++.

Linq order by, group by and order by each group?

The way to do it without projection:

StudentsGrades.OrderBy(student => student.Name).
ThenBy(student => student.Grade);

How do I dump an object's fields to the console?

puts foo.to_json

might come in handy since the json module is loaded by default

Re-render React component when prop changes

You could use KEY unique key (combination of the data) that changes with props, and that component will be rerendered with updated props.

Clear dropdownlist with JQuery

Just use .empty():

// snip...
}).done(function (data) {
    // Clear drop down list
    $(dropdown).empty(); // <<<<<< No more issue here
    // Fill drop down list with new data
    $(data).each(function () {
        // snip...

There's also a more concise way to build up the options:

// snip...
$(data).each(function () {
    $("<option />", {
        val: this.value,
        text: this.text
    }).appendTo(dropdown);
});

Autowiring fails: Not an managed Type

If anyone is strugling with the same problem I solved it by adding @EntityScan in my main class. Just add your model package to the basePackages property.

How to select all columns, except one column in pandas?

Here is another way:

df[[i for i in list(df.columns) if i != '<your column>']]

You just pass all columns to be shown except of the one you do not want.

Cannot find firefox binary in PATH. Make sure firefox is installed

I have also face same issue on Windows 10-64 bit OS.

When I am installed firefox on my PC its installed location is "C:\Program Files\Mozilla Firefox\firefox.exe" instead of "C:\Program Files (x86)\Mozilla Firefox", because OS is 64 bit,

So I just copy & paste "Mozilla Firefox" folder in "C:\Program Files (x86)" folder and execute selenium scripts, its work for me.

How to use SQL Order By statement to sort results case insensitive?

You can also do ORDER BY TITLE COLLATE NOCASE.

Edit: If you need to specify ASC or DESC, add this after NOCASE like

ORDER BY TITLE COLLATE NOCASE ASC

or

ORDER BY TITLE COLLATE NOCASE DESC

trace a particular IP and port

Firstly, check the IP address that your application has bound to. It could only be binding to a local address, for example, which would mean that you'd never see it from a different machine regardless of firewall states.

You could try using a portscanner like nmap to see if the port is open and visible externally... it can tell you if the port is closed (there's nothing listening there), open (you should be able to see it fine) or filtered (by a firewall, for example).

Carriage Return\Line feed in Java

Encapsulate your writer to provide char replacement, like this:

public class WindowsFileWriter extends Writer {

    private Writer writer;

    public WindowsFileWriter(File file) throws IOException {
        try {
            writer = new OutputStreamWriter(new FileOutputStream(file), "ISO-8859-15");
        } catch (UnsupportedEncodingException e) {
            writer = new FileWriter(logfile);
        }
    }

    @Override
    public void write(char[] cbuf, int off, int len) throws IOException {
        writer.write(new String(cbuf, off, len).replace("\n", "\r\n"));
    }

    @Override
    public void flush() throws IOException {
        writer.flush();
    }

    @Override
    public void close() throws IOException {
        writer.close();
    }

}

Access denied for root user in MySQL command-line

Gain access to a MariaDB 10 database server

After stopping the database server, the next step is to gain access to the server through a backdoor by starting the database server and skipping networking and permission tables. This can be done by running the commands below.

sudo mysqld_safe --skip-grant-tables --skip-networking &

Reset MariaDB root Password

Now that the database server is started in safe mode, run the commands below to logon as root without password prompt. To do that, run the commands below

sudo mysql -u root

Then run the commands below to use the mysql database.

use mysql;

Finally, run the commands below to reset the root password.

update user set password=PASSWORD("new_password_here") where User='root';

Replace new_password _here with the new password you want to create for the root account, then press Enter.

After that, run the commands below to update the permissions and save your changes to disk.

flush privileges;

Exit (CTRL + D) and you’re done.

Next start MariaDB normally and test the new password you just created.

sudo systemctl stop mariadb.service
sudo systemctl start mariadb.service

Logon to the database by running the commands below.

sudo mysql -u root -p

source: https://websiteforstudents.com/reset-mariadb-root-password-ubuntu-17-04-17-10/

How to prevent rm from reporting that a file was not found?

The main use of -f is to force the removal of files that would not be removed using rm by itself (as a special case, it "removes" non-existent files, thus suppressing the error message).

You can also just redirect the error message using

$ rm file.txt 2> /dev/null

(or your operating system's equivalent). You can check the value of $? immediately after calling rm to see if a file was actually removed or not.

Compare 2 JSON objects

Simply parsing the JSON and comparing the two objects is not enough because it wouldn't be the exact same object references (but might be the same values).

You need to do a deep equals.

From http://threebit.net/mail-archive/rails-spinoffs/msg06156.html - which seems the use jQuery.

Object.extend(Object, {
   deepEquals: function(o1, o2) {
     var k1 = Object.keys(o1).sort();
     var k2 = Object.keys(o2).sort();
     if (k1.length != k2.length) return false;
     return k1.zip(k2, function(keyPair) {
       if(typeof o1[keyPair[0]] == typeof o2[keyPair[1]] == "object"){
         return deepEquals(o1[keyPair[0]], o2[keyPair[1]])
       } else {
         return o1[keyPair[0]] == o2[keyPair[1]];
       }
     }).all();
   }
});

Usage:

var anObj = JSON.parse(jsonString1);
var anotherObj= JSON.parse(jsonString2);

if (Object.deepEquals(anObj, anotherObj))
   ...

Why are interface variables static and final by default?

Think of a web application where you have interface defined and other classes implement it. As you cannot create an instance of interface to access the variables you need to have a static keyword. Since its static any change in the value will reflect to other instances which has implemented it. So in order to prevent it we define them as final.

Limiting the number of characters per line with CSS

A better solution would be you use in style css, the command to break lines. Works in older versions of browsers.

p {
word-wrap: break-word;
}

Class 'DOMDocument' not found

If you are using PHP7.0 to install Magento, I suggest to install all extensions by this command

sudo apt-get install php7.0 php7.0-xml php7.0-mcrypt php7.0-curl php7.0-cli php7.0-mysql php7.0-gd libapache2-mod-php7.0 php7.0-intl php7.0-soap php7.0-zip php7.0-bcmath

I need to Google some times to meet Magento requirement.

I think you can replace the PHP version to 7.x if you use another PHP version

And restart Apache is needed to load new extensions

sudo service apache2 restart

Postgresql SQL: How check boolean field with null and True,False Value?

Resurrecting this to post the DISTINCT FROM option, which has been around since Postgres 8. The approach is similar to Brad Dre's answer. In your case, your select would be something like

SELECT *
  FROM table_name
 WHERE boolean_column IS DISTINCT FROM TRUE

IndexError: index 1 is out of bounds for axis 0 with size 1/ForwardEuler

The problem, as the Traceback says, comes from the line x[i+1] = x[i] + ( t[i+1] - t[i] ) * f( x[i], t[i] ). Let's replace it in its context:

  • x is an array equal to [x0 * n], so its length is 1
  • you're iterating from 0 to n-2 (n doesn't matter here), and i is the index. In the beginning, everything is ok (here there's no beginning apparently... :( ), but as soon as i + 1 >= len(x) <=> i >= 0, the element x[i+1] doesn't exist. Here, this element doesn't exist since the beginning of the for loop.

To solve this, you must replace x[i+1] = x[i] + ( t[i+1] - t[i] ) * f( x[i], t[i] ) by x.append(x[i] + ( t[i+1] - t[i] ) * f( x[i], t[i] )).

Save results to csv file with Python

this will provide exact output

import csv

import collections

with open('file.csv', 'rb') as f:

  data = list(csv.reader(f))

counter = collections.defaultdict(int)

for row in data:

    counter[row[0]] += 1

writer = csv.writer(open("file1.csv", 'w'))

for row in data:

    if counter[row[0]] >= 1:

        writer.writerow(row)

Adjust plot title (main) position

To summarize and explain visually how it works. Code construction is as follows:

par(mar = c(3,2,2,1))
barplot(...all parameters...)
title("Title text", adj = 0.5, line = 0)

explanation:

par(mar = c(low, left, top, right)) - margins of the graph area.

title("text" - title text
      adj  = from left (0) to right (1) with anything in between: 0.1, 0.2, etc...
      line = positive values move title text up, negative - down)

enter image description here

Why is SQL server throwing this error: Cannot insert the value NULL into column 'id'?

You can insert a value manually in the ID column (here I call it "PK"):

insert into table1 (PK, var1, var2)
values ((select max(PK)+1 from table1), 123, 456)

Oracle: Import CSV file

SQL Loader is the way to go. I recently loaded my table from a csv file,new to this concept,would like to share an example.

LOAD DATA
    infile '/ipoapplication/utl_file/LBR_HE_Mar16.csv'
    REPLACE
    INTO TABLE LOAN_BALANCE_MASTER_INT
    fields terminated by ',' optionally enclosed by '"'
    (
    ACCOUNT_NO,
    CUSTOMER_NAME,
    LIMIT,
    REGION

    )

Place the control file and csv at the same location on the server. Locate the sqlldr exe and invoce it.

sqlldr userid/passwd@DBname control= Ex : sqlldr abc/xyz@ora control=load.ctl

Hope it helps.

How to delete/truncate tables from Hadoop-Hive?

You need to drop the table and then recreate it and then load it again

LINQ query to return a Dictionary<string, string>

Look at the ToLookup and/or ToDictionary extension methods.

How to ignore conflicts in rpm installs

From the context, the conflict was caused by the version of the package.
Let's take a look the manual about rpm:

--force
    Same as using --replacepkgs, --replacefiles, and --oldpackage.

--oldpackage
    Allow an upgrade to replace a newer package with an older one.

So, you can execute the command rpm -Uvh info-4.13a-2.rpm --force to solve your issue.

Check if a string is palindrome

// The below C++ function checks for a palindrome and 
// returns true if it is a palindrome and returns false otherwise

bool checkPalindrome ( string s )
{
    // This calculates the length of the string

    int n = s.length();

    // the for loop iterates until the first half of the string
    // and checks first element with the last element,
    // second element with second last element and so on.
    // if those two characters are not same, hence we return false because
    // this string is not a palindrome 

    for ( int i = 0; i <= n/2; i++ ) 
    {
        if ( s[i] != s[n-1-i] )
            return false;
    }
    
    // if the above for loop executes completely , 
    // this implies that the string is palindrome, 
    // hence we return true and exit

    return true;
}

Redeploy alternatives to JRebel

Take a look at DCEVM, it's a modification of the HotSpot VM that allows unlimited class redefinitions at runtime. You can add/remove fields and methods and change the super types of a class at runtime.

The binaries available on the original site are limited to Java 6u25 and to early versions of Java 7. The project has been forked on Github and supports recent versions of Java 7 and 8. The maintainer provides binaries for 32/64 bits VMs on Windows/Linux. Starting with Java 11 the project moved to a new GitHub repository and now also provides binaries for OS X.

DCEVM is packaged for Debian and Ubuntu, it's conveniently integrated with OpenJDK and can be invoked with java -dcevm. The name of the package depends on the version of the default JDK:

Hibernate throws MultipleBagFetchException - cannot simultaneously fetch multiple bags

For me, the problem was having nested EAGER fetches.

One solution is to set the nested fields to LAZY and use Hibernate.initialize() to load the nested field(s):

x = session.get(ClassName.class, id);
Hibernate.initialize(x.getNestedField());

How do I grep for all non-ASCII characters?

You can use the command:

grep --color='auto' -P -n "[\x80-\xFF]" file.xml

This will give you the line number, and will highlight non-ascii chars in red.

In some systems, depending on your settings, the above will not work, so you can grep by the inverse

grep --color='auto' -P -n "[^\x00-\x7F]" file.xml

Note also, that the important bit is the -P flag which equates to --perl-regexp: so it will interpret your pattern as a Perl regular expression. It also says that

this is highly experimental and grep -P may warn of unimplemented features.

Android get current Locale, not default

As per official documentation ConfigurationCompat is deprecated in support libraries

You can consider using

LocaleListCompat.getDefault()[0].toLanguageTag() 0th position will be user preferred locale

To get Default locale at 0th position would be LocaleListCompat.getAdjustedDefault()

Decompile .smali files on an APK

I second that.

Dex2jar will generate a WORKING jar, which you can add as your project source, with the xmls you got from apktool.

However, JDGUI generates .java files which have ,more often than not, errors.

It has got something to do with code obfuscation I guess.

Horizontal swipe slider with jQuery and touch devices support?

Checkout Portfoliojs jQuery plugin: http://portfoliojs.com

This plugin supports Touch Devices, Desktops and Mobile Browsers. Also, It has pre-loading feature.

Check if input is number or letter javascript

A better(error-free) code would be like:

function isReallyNumber(data) {
    return typeof data === 'number' && !isNaN(data);
}

This will handle empty strings as well. Another reason, isNaN("12") equals to false but "12" is a string and not a number, so it should result to true. Lastly, a bonus link which might interest you.

Show all current locks from get_lock

I found following way which can be used if you KNOW name of lock

select IS_USED_LOCK('lockname');

however i not found any info about how to list all names.

Cleanest way to write retry logic?

Do it simple in C#, Java or other languages:

  internal class ShouldRetryHandler {
    private static int RETRIES_MAX_NUMBER = 3;
    private static int numberTryes;

    public static bool shouldRetry() {
        var statusRetry = false;

        if (numberTryes< RETRIES_MAX_NUMBER) {
            numberTryes++;
            statusRetry = true;
            //log msg -> 'retry number' + numberTryes

        }

        else {
            statusRetry = false;
            //log msg -> 'reached retry number limit' 
        }

        return statusRetry;
    }
}

and use it in your code very simple:

 void simpleMethod(){
    //some code

    if(ShouldRetryHandler.shouldRetry()){
    //do some repetitive work
     }

    //some code    
    }

or you can use it in recursive methods:

void recursiveMethod(){
    //some code

    if(ShouldRetryHandler.shouldRetry()){
    recursiveMethod();
     }

    //some code    
    }

php string to int

You can remove the spaces before casting to int:

(int)str_replace(' ', '', $b);

Also, if you want to strip other commonly used digit delimiters (such as ,), you can give the function an array (beware though -- in some countries, like mine for example, the comma is used for fraction notation):

(int)str_replace(array(' ', ','), '', $b);

What is difference between CrudRepository and JpaRepository interfaces in Spring Data JPA?

Ken's answer is basically right but I'd like to chime in on the "why would you want to use one over the other?" part of your question.

Basics

The base interface you choose for your repository has two main purposes. First, you allow the Spring Data repository infrastructure to find your interface and trigger the proxy creation so that you inject instances of the interface into clients. The second purpose is to pull in as much functionality as needed into the interface without having to declare extra methods.

The common interfaces

The Spring Data core library ships with two base interfaces that expose a dedicated set of functionalities:

  • CrudRepository - CRUD methods
  • PagingAndSortingRepository - methods for pagination and sorting (extends CrudRepository)

Store-specific interfaces

The individual store modules (e.g. for JPA or MongoDB) expose store-specific extensions of these base interfaces to allow access to store-specific functionality like flushing or dedicated batching that take some store specifics into account. An example for this is deleteInBatch(…) of JpaRepository which is different from delete(…) as it uses a query to delete the given entities which is more performant but comes with the side effect of not triggering the JPA-defined cascades (as the spec defines it).

We generally recommend not to use these base interfaces as they expose the underlying persistence technology to the clients and thus tighten the coupling between them and the repository. Plus, you get a bit away from the original definition of a repository which is basically "a collection of entities". So if you can, stay with PagingAndSortingRepository.

Custom repository base interfaces

The downside of directly depending on one of the provided base interfaces is two-fold. Both of them might be considered as theoretical but I think they're important to be aware of:

  1. Depending on a Spring Data repository interface couples your repository interface to the library. I don't think this is a particular issue as you'll probably use abstractions like Page or Pageable in your code anyway. Spring Data is not any different from any other general purpose library like commons-lang or Guava. As long as it provides reasonable benefit, it's just fine.
  2. By extending e.g. CrudRepository, you expose a complete set of persistence method at once. This is probably fine in most circumstances as well but you might run into situations where you'd like to gain more fine-grained control over the methods expose, e.g. to create a ReadOnlyRepository that doesn't include the save(…) and delete(…) methods of CrudRepository.

The solution to both of these downsides is to craft your own base repository interface or even a set of them. In a lot of applications I have seen something like this:

interface ApplicationRepository<T> extends PagingAndSortingRepository<T, Long> { }

interface ReadOnlyRepository<T> extends Repository<T, Long> {

  // Al finder methods go here
}

The first repository interface is some general purpose base interface that actually only fixes point 1 but also ties the ID type to be Long for consistency. The second interface usually has all the find…(…) methods copied from CrudRepository and PagingAndSortingRepository but does not expose the manipulating ones. Read more on that approach in the reference documentation.

Summary - tl;dr

The repository abstraction allows you to pick the base repository totally driven by you architectural and functional needs. Use the ones provided out of the box if they suit, craft your own repository base interfaces if necessary. Stay away from the store specific repository interfaces unless unavoidable.

GridLayout (not GridView) how to stretch all children evenly

Here you are :

Button button = new Button(this);
// weight = 1f , gravity = GridLayout.FILL 
GridLayout.LayoutParams param= new GridLayout.LayoutParams(GridLayout.spec(
            GridLayout.UNDEFINED,GridLayout.FILL,1f),
            GridLayout.spec(GridLayout.UNDEFINED,GridLayout.FILL,1f));
// Layout_height = 0 ,Layout_weight = 0
params.height =0;                                                                                                           
params.width = 0;
button.setLayoutParams(param);

How to use putExtra() and getExtra() for string data

Put String in Intent Object

  Intent intent = new Intent(FirstActivity.this,NextAcitivity.class);
  intent.putExtra("key",your_String);
  StartActivity(intent);

NextAcitvity in onCreate method get String

String my_string=getIntent().getStringExtra("key");

that is easy and short method

Dynamically allocating an array of objects

I'd recommend using std::vector: something like

typedef std::vector<int> A;
typedef std::vector<A> AS;

There's nothing wrong with the slight overkill of STL, and you'll be able to spend more time implementing the specific features of your app instead of reinventing the bicycle.

iOS 8 UITableView separator inset 0 not working

Adding this snippet, simple elegant in Swift works for me in iOS8 :)

    // tableview single line
func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
    cell.preservesSuperviewLayoutMargins = false
    cell.layoutMargins = UIEdgeInsetsZero
}

What is the difference between UTF-8 and ISO-8859-1?

From another perspective, files that both unicode and ascii encodings fail to read because they have a byte 0xc0 in them, seem to get read by iso-8859-1 properly. The caveat is that the file shouldn't have unicode characters in it of course.

What is the purpose of global.asax in asp.net

The Global.asax file, also known as the ASP.NET application file, is an optional file that contains code for responding to application-level and session-level events raised by ASP.NET or by HTTP modules.

http://msdn.microsoft.com/en-us/library/2027ewzw.aspx

Web link to specific whatsapp contact

You can use the following URL as per the WhatsApp FAQ:

https://wa.me/PHONENUMBERHERE

Add the country code in front of the number and don't add any plus (+) sign or any dashes (-) or any other characters in the number. Only integrers/numeric values.

You can also predefine a text message to start with:

https://wa.me/PHONENUMBERHERE/?text=urlencodedtext

Create own colormap using matplotlib and plot color scale

If you want to automate the creating of a custom divergent colormap commonly used for surface plots, this module combined with @unutbu method worked well for me.

def diverge_map(high=(0.565, 0.392, 0.173), low=(0.094, 0.310, 0.635)):
    '''
    low and high are colors that will be used for the two
    ends of the spectrum. they can be either color strings
    or rgb color tuples
    '''
    c = mcolors.ColorConverter().to_rgb
    if isinstance(low, basestring): low = c(low)
    if isinstance(high, basestring): high = c(high)
    return make_colormap([low, c('white'), 0.5, c('white'), high])

The high and low values can be either string color names or rgb tuples. This is the result using the surface plot demo: enter image description here

Delete all the queues from RabbitMQ?

In case you only want to purge the queues which are not empty (a lot faster):

rabbitmqctl list_queues | awk '$2!=0 { print $1 }' | sed 's/Listing//' | xargs -L1 rabbitmqctl purge_queue

For me, it takes 2-3 seconds to purge a queue (both empty and non-empty ones), so iterating through 50 queues is such a pain while I just need to purge 10 of them (40/50 are empty).

Differences between C++ string == and compare()?

std::string::compare() returns an int:

  • equal to zero if s and t are equal,
  • less than zero if s is less than t,
  • greater than zero if s is greater than t.

If you want your first code snippet to be equivalent to the second one, it should actually read:

if (!s.compare(t)) {
    // 's' and 't' are equal.
}

The equality operator only tests for equality (hence its name) and returns a bool.

To elaborate on the use cases, compare() can be useful if you're interested in how the two strings relate to one another (less or greater) when they happen to be different. PlasmaHH rightfully mentions trees, and it could also be, say, a string insertion algorithm that aims to keep the container sorted, a dichotomic search algorithm for the aforementioned container, and so on.

EDIT: As Steve Jessop points out in the comments, compare() is most useful for quick sort and binary search algorithms. Natural sorts and dichotomic searches can be implemented with only std::less.

Delete all rows with timestamp older than x days

DELETE FROM on_search WHERE search_date < NOW() - INTERVAL N DAY

Replace N with your day count

How can I run an external command asynchronously from Python?

What I am wondering is if this [os.system()] is the proper way to accomplish such a thing?

No. os.system() is not the proper way. That's why everyone says to use subprocess.

For more information, read http://docs.python.org/library/os.html#os.system

The subprocess module provides more powerful facilities for spawning new processes and retrieving their results; using that module is preferable to using this function. Use the subprocess module. Check especially the Replacing Older Functions with the subprocess Module section.

Download files from server php

Here is the code that will not download courpt files

$filename = "myfile.jpg";
$file = "/uploads/images/".$filename;

header('Content-type: application/octet-stream');
header("Content-Type: ".mime_content_type($file));
header("Content-Disposition: attachment; filename=".$filename);
while (ob_get_level()) {
    ob_end_clean();
}
readfile($file);

I have included mime_content_type which will return content type of file .

To prevent from corrupt file download i have added ob_get_level() and ob_end_clean();

Url decode UTF-8 in Python

The data is UTF-8 encoded bytes escaped with URL quoting, so you want to decode, with urllib.parse.unquote(), which handles decoding from percent-encoded data to UTF-8 bytes and then to text, transparently:

from urllib.parse import unquote

url = unquote(url)

Demo:

>>> from urllib.parse import unquote
>>> url = 'example.com?title=%D0%BF%D1%80%D0%B0%D0%B2%D0%BE%D0%B2%D0%B0%D1%8F+%D0%B7%D0%B0%D1%89%D0%B8%D1%82%D0%B0'
>>> unquote(url)
'example.com?title=????????+??????'

The Python 2 equivalent is urllib.unquote(), but this returns a bytestring, so you'd have to decode manually:

from urllib import unquote

url = unquote(url).decode('utf8')

Check if string contains only whitespace

Check the length of the list given by of split() method.

if len(your_string.split()==0:
     print("yes")

Or Compare output of strip() method with null.

if your_string.strip() == '':
     print("yes")

How to print without newline or space?

...you do not need to import any library. Just use the delete character:

BS=u'\0008' # the unicode for "delete" character
for i in range(10):print(BS+"."),

this removes the newline and the space (^_^)*

Node.js Error: connect ECONNREFUSED

You're trying to connect to localhost:8080 ... is any service running on your localhost and on this port? If not, the connection is refused which cause this error. I would suggest to check if there is anything running on localhost:8080 first.

MVC 4 Razor adding input type date

I managed to do it by using the following code.

@Html.TextBoxFor(model => model.EndTime, new { type = "time" })

Adding Git-Bash to the new Windows Terminal

Because most answers either show a lot of unrelated configuration or don't show the configuration, I created my own answer that tries to be more focused. It is mainly based on the profile settings reference and Archimedes Trajano's answer.

Steps

  1. Open PowerShell and enter [guid]::NewGuid() to generate a new GUID. We will use it at step 3.

    > [guid]::NewGuid()
    
    Guid
    ----
    a3da8d92-2f3f-4e36-9714-98876b6cb480
    
  2. Open the settings of Windows Terminal. (CTRL+,)

  3. Add the following JSON object to profiles.list. Replace guid with the one you generated at step 1.

    {
      "guid": "{a3da8d92-2f3f-4e36-9714-98876b6cb480}",
      "name": "Git Bash",
      "commandline": "\"%PROGRAMFILES%\\Git\\usr\\bin\\bash.exe\" -i -l",
      "icon": "%PROGRAMFILES%\\Git\\mingw64\\share\\git\\git-for-windows.ico",
      "startingDirectory" : "%USERPROFILE%"
    },
    

Notes

  • There is currently an issue that you cannot use your arrow keys (and some other keys). It seems to work with the latest preview version, though. (issue #6859)

  • Specifying "startingDirectory" : "%USERPROFILE%" shouldn't be necessary according to the reference. However, if I don't specify it, the starting directory was different depending on how I started the terminal initially.

  • Settings that shall apply to all terminals can be specified in profiles.defaults.

  • I recommend to set "antialiasingMode": "cleartype" in profiles.defaults. You have to remove "useAcrylic" (if you have added it as suggested by some other answers) to make it work. It improves the quality of text rendering. However, you cannot have transparent background without useAcrylic. See issue #1298.

  • If you have problems with the cursor, you can try another shape like "cursorShape": "filledBox". See cursor settings for more information.

How to remove decimal part from a number in C#

Well 12 and 12.00 have exactly the same representation as double values. Are you trying to end up with a double or something else? (For example, you could cast to int, if you were convinced the value would be in the right range, and if the truncation effect is what you want.)

You might want to look at these methods too:

Excel how to fill all selected blank cells with text

If all the cells are under one column, you could just filter the column and then select "(blank)" and then insert any value into the cells. But be careful, press "alt + 4" to make sure you are inserting value into the visible cells only.

Error "package android.support.v7.app does not exist"

After Rebuild the project issue resolved..

SQL Server tables: what is the difference between @, # and ##?

if you need a unique global temp table, create your own with a Uniqueidentifier Prefix/Suffix and drop post execution if an if object_id(.... The only drawback is using Dynamic sql and need to drop explicitly.

Read properties file outside JAR file

I did it by other way.

Properties prop = new Properties();
    try {

        File jarPath=new File(MyClass.class.getProtectionDomain().getCodeSource().getLocation().getPath());
        String propertiesPath=jarPath.getParentFile().getAbsolutePath();
        System.out.println(" propertiesPath-"+propertiesPath);
        prop.load(new FileInputStream(propertiesPath+"/importer.properties"));
    } catch (IOException e1) {
        e1.printStackTrace();
    }
  1. Get Jar file path.
  2. Get Parent folder of that file.
  3. Use that path in InputStreamPath with your properties file name.

for each loop in Objective-C for accessing NSMutable dictionary

The easiest way to enumerate a dictionary is

for (NSString *key in tDictionary.keyEnumerator) 
{
    //do something here;
}

where tDictionary is the NSDictionary or NSMutableDictionary you want to iterate.

How to generate a random number between a and b in Ruby?

rand(3..10)

Kernel#rand

When max is a Range, rand returns a random number where range.member?(number) == true.

Sourcetree - undo unpushed commits

If you select the log entry to which you want to revert to then you can click on "Reset to this commit". Only use this option if you didn't push the reverse commit changes. If you're worried about losing the changes then you can use the soft mode which will leave a set of uncommitted changes (what you just changed). Using the mixed resets the working copy but keeps those changes, and a hard will just get rid of the changes entirely. Here's some screenshots:

enter image description here

Load properties file in JAR?

For the record, this is documented in How do I add resources to my JAR? (illustrated for unit tests but the same applies for a "regular" resource):

To add resources to the classpath for your unit tests, you follow the same pattern as you do for adding resources to the JAR except the directory you place resources in is ${basedir}/src/test/resources. At this point you would have a project directory structure that would look like the following:

my-app
|-- pom.xml
`-- src
    |-- main
    |   |-- java
    |   |   `-- com
    |   |       `-- mycompany
    |   |           `-- app
    |   |               `-- App.java
    |   `-- resources
    |       `-- META-INF
    |           |-- application.properties
    `-- test
        |-- java
        |   `-- com
        |       `-- mycompany
        |           `-- app
        |               `-- AppTest.java
        `-- resources
            `-- test.properties

In a unit test you could use a simple snippet of code like the following to access the resource required for testing:

...

// Retrieve resource
InputStream is = getClass().getResourceAsStream("/test.properties" );

// Do something with the resource

...

Determine what user created objects in SQL Server

If you need a small and specific mechanism, you can search for DLL Triggers info.

How to reset a timer in C#?

You could write an extension method called Reset(), which

  • calls Stop()-Start() for Timers.Timer and Forms.Timer
  • calls Change for Threading.Timer

Restarting cron after changing crontab file?

Depending on distribution, using "cron reload" might do nothing. To paste a snippet out of init.d/cron (debian squeeze):

reload|force-reload) log_daemon_msg "Reloading configuration files for periodic command scheduler" "cron"
    # cron reloads automatically
    log_end_msg 0
    ;;

Some developer/maintainer relied on it reloading, but doesn't, and in this case there's not a way to force reload. I'm generating my crontab files as part of a deploy, and unless somehow the length of the file changes, the changes are not reloaded.

How to URL encode in Python 3?

For Python 3 you could try using quote instead of quote_plus:

import urllib.parse

print(urllib.parse.quote("http://www.sample.com/"))

Result:

http%3A%2F%2Fwww.sample.com%2F

Or:

from requests.utils import requote_uri
requote_uri("http://www.sample.com/?id=123 abc")

Result:

'https://www.sample.com/?id=123%20abc'

Using varchar(MAX) vs TEXT on SQL Server

The VARCHAR(MAX) type is a replacement for TEXT. The basic difference is that a TEXT type will always store the data in a blob whereas the VARCHAR(MAX) type will attempt to store the data directly in the row unless it exceeds the 8k limitation and at that point it stores it in a blob.

Using the LIKE statement is identical between the two datatypes. The additional functionality VARCHAR(MAX) gives you is that it is also can be used with = and GROUP BY as any other VARCHAR column can be. However, if you do have a lot of data you will have a huge performance issue using these methods.

In regard to if you should use LIKE to search, or if you should use Full Text Indexing and CONTAINS. This question is the same regardless of VARCHAR(MAX) or TEXT.

If you are searching large amounts of text and performance is key then you should use a Full Text Index.

LIKE is simpler to implement and is often suitable for small amounts of data, but it has extremely poor performance with large data due to its inability to use an index.

How do I delete a local repository in git?

To piggyback on rkj's answer, to avoid endless prompts (and force the command recursively), enter the following into the command line, within the project folder:

$ rm -rf .git

Or to delete .gitignore and .gitmodules if any (via @aragaer):

$ rm -rf .git*

Then from the same ex-repository folder, to see if hidden folder .git is still there:

$ ls -lah

If it's not, then congratulations, you've deleted your local git repo, but not a remote one if you had it. You can delete GitHub repo on their site (github.com).

To view hidden folders in Finder (Mac OS X) execute these two commands in your terminal window:

defaults write com.apple.finder AppleShowAllFiles TRUE
killall Finder

Source: http://lifehacker.com/188892/show-hidden-files-in-finder.

How to sort a Collection<T>?

If your collections object is a list, I would use the sort method, as proposed in the other answers.

However, if it is not a list, and you don't really care about what type of Collection object is returned, I think it is faster to create a TreeSet instead of a List:

TreeSet sortedSet = new TreeSet(myComparator);
sortedSet.addAll(myCollectionToBeSorted);

Assign output of a program to a variable using a MS batch file

Some macros to set the output of a command to a variable/

For directly in the command prompt

c:\>doskey assign=for /f "tokens=1,2 delims=," %a in ("$*") do @for /f "tokens=* delims=" %# in ('"%a"') do @set "%b=%#"

c:\>assign WHOAMI /LOGONID,my-id

c:\>echo %my-id%

Macro with arguments

As this macro accepts arguments as a function i think it is the neatest macro to be used in a batch file:

@echo off

::::: ---- defining the assign macro ---- ::::::::
setlocal DisableDelayedExpansion
(set LF=^
%=EMPTY=%
)
set ^"\n=^^^%LF%%LF%^%LF%%LF%^^"

::set argv=Empty
set assign=for /L %%n in (1 1 2) do ( %\n%
   if %%n==2 (%\n%
      setlocal enableDelayedExpansion%\n%
      for /F "tokens=1,2 delims=," %%A in ("!argv!") do (%\n%
         for /f "tokens=* delims=" %%# in ('%%~A') do endlocal^&set "%%~B=%%#" %\n%
      ) %\n%
   ) %\n%
) ^& set argv=,

::::: -------- ::::::::


:::EXAMPLE
%assign% "WHOAMI /LOGONID",result
echo %result%

FOR /F macro

not so easy to read as the previous macro.

::::::::::::::::::::::::::::::::::::::::::::::::::
;;set "{{=for /f "tokens=* delims=" %%# in ('" &::
;;set "--=') do @set ""                        &::
;;set "}}==%%#""                               &::
::::::::::::::::::::::::::::::::::::::::::::::::::

:: --examples

::assigning ver output to %win-ver% variable
%{{% ver %--%win-ver%}}%
echo 3: %win-ver%


::assigning hostname output to %my-host% variable
%{{% hostname %--%my-host%}}%
echo 4: %my-host%

Macro using a temp file

Easier to read , it is not so slow if you have a SSD drive but still it creates a temp file.

@echo off

:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
;;set "[[=>"#" 2>&1&set/p "&set "]]==<# & del /q # >nul 2>&1" &::
:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::

chcp %[[%code-page%]]%
echo ~~%code-page%~~

whoami %[[%its-me%]]%
echo ##%its-me%##

How to change port for jenkins window service when 8080 is being used

Use Default Port

If the default port 8080 has been bind with other process, Then kill that process.

DOS> netstat -a -o -n

Find the process id (PID) XXXX of the process which occupied 8080.

DOS> taskkill /F /PID XXXX

Now, start Jenkins (on default port)

DOS> Java -jar jenkins.war

Use Custom Port

DOS> Java -jar jenkins.war --httpPort=8008

Custom circle button

AngryTool for custom android button

You can make any kind of custom android button with this tool site... i make circle and square button with round corner with this toolsite.. Visit it may be i will help you

"Adaptive Server is unavailable or does not exist" error connecting to SQL Server from PHP

I've found an issue happen to be with the Firewall. So, make sure your IP is whitelisted and the firewall does not block your connection. You can check connectivity with:

tsql -H somehost.com -p 1433

In my case, the output was:

Error 20009 (severity 9):
  Unable to connect: Adaptive Server is unavailable or does not exist
  OS error 111, "Connection refused"
There was a problem connecting to the server

symbol(s) not found for architecture i386

I had used a CLGeocoder without adding a Core.Location Framework. Basically this error can mean multiple things. I hope this helps someone else.

Python class inherits object

Is there any reason for a class declaration to inherit from object?

In Python 3, apart from compatibility between Python 2 and 3, no reason. In Python 2, many reasons.


Python 2.x story:

In Python 2.x (from 2.2 onwards) there's two styles of classes depending on the presence or absence of object as a base-class:

  1. "classic" style classes: they don't have object as a base class:

    >>> class ClassicSpam:      # no base class
    ...     pass
    >>> ClassicSpam.__bases__
    ()
    
  2. "new" style classes: they have, directly or indirectly (e.g inherit from a built-in type), object as a base class:

    >>> class NewSpam(object):           # directly inherit from object
    ...    pass
    >>> NewSpam.__bases__
    (<type 'object'>,)
    >>> class IntSpam(int):              # indirectly inherit from object...
    ...    pass
    >>> IntSpam.__bases__
    (<type 'int'>,) 
    >>> IntSpam.__bases__[0].__bases__   # ... because int inherits from object  
    (<type 'object'>,)
    

Without a doubt, when writing a class you'll always want to go for new-style classes. The perks of doing so are numerous, to list some of them:

  • Support for descriptors. Specifically, the following constructs are made possible with descriptors:

    1. classmethod: A method that receives the class as an implicit argument instead of the instance.
    2. staticmethod: A method that does not receive the implicit argument self as a first argument.
    3. properties with property: Create functions for managing the getting, setting and deleting of an attribute.
    4. __slots__: Saves memory consumptions of a class and also results in faster attribute access. Of course, it does impose limitations.
  • The __new__ static method: lets you customize how new class instances are created.

  • Method resolution order (MRO): in what order the base classes of a class will be searched when trying to resolve which method to call.

  • Related to MRO, super calls. Also see, super() considered super.

If you don't inherit from object, forget these. A more exhaustive description of the previous bullet points along with other perks of "new" style classes can be found here.

One of the downsides of new-style classes is that the class itself is more memory demanding. Unless you're creating many class objects, though, I doubt this would be an issue and it's a negative sinking in a sea of positives.


Python 3.x story:

In Python 3, things are simplified. Only new-style classes exist (referred to plainly as classes) so, the only difference in adding object is requiring you to type in 8 more characters. This:

class ClassicSpam:
    pass

is completely equivalent (apart from their name :-) to this:

class NewSpam(object):
     pass

and to this:

class Spam():
    pass

All have object in their __bases__.

>>> [object in cls.__bases__ for cls in {Spam, NewSpam, ClassicSpam}]
[True, True, True]

So, what should you do?

In Python 2: always inherit from object explicitly. Get the perks.

In Python 3: inherit from object if you are writing code that tries to be Python agnostic, that is, it needs to work both in Python 2 and in Python 3. Otherwise don't, it really makes no difference since Python inserts it for you behind the scenes.

How can I read numeric strings in Excel cells as string (not numbers)?

Do you control the excel worksheet in anyway? Is there a template the users have for giving you the input? If so, you can have code format the input cells for you.

What is difference between sleep() method and yield() method of multi threading?

Yield(): method will stop the currently executing thread and give a chance to another thread of same priority which are waiting in queue. If thier is no thread then current thread will continue to execute. CPU will never be in ideal state.

Sleep(): method will stop the thread for particular time (time will be given in milisecond). If this is single thread which is running then CPU will be in ideal state at that period of time.

Both are static menthod.

How to connect Bitbucket to Jenkins properly

In order to build your repo after new commits, use Bitbucket Plugin.

There is just one thing to notice: When creating a POST Hook (notice that it is POST hook, not Jenkins hook), the URL works when it has a "/" in the end. Like:

URL: JENKINS_URL/bitbucket-hook/
e.g. someAddress:8080/bitbucket-hook/

Do not forget to check "Build when a change is pushed to Bitbucket" in your job configuration.

Javascript to export html table to Excel

If you add:

<meta http-equiv="content-type" content="text/plain; charset=UTF-8"/>

in the head of the document it will start working as expected:

<script type="text/javascript">
var tableToExcel = (function() {
  var uri = 'data:application/vnd.ms-excel;base64,'
    , template = '<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40"><head><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>{worksheet}</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--><meta http-equiv="content-type" content="text/plain; charset=UTF-8"/></head><body><table>{table}</table></body></html>'
    , base64 = function(s) { return window.btoa(unescape(encodeURIComponent(s))) }
    , format = function(s, c) { return s.replace(/{(\w+)}/g, function(m, p) { return c[p]; }) }
  return function(table, name) {
    if (!table.nodeType) table = document.getElementById(table)
    var ctx = {worksheet: name || 'Worksheet', table: table.innerHTML}
    window.location.href = uri + base64(format(template, ctx))
  }
})()
</script>

Updated Fiddle Here.

How to get a parent element to appear above child

Since your divs are position:absolute, they're not really nested as far as position is concerned. On your jsbin page I switched the order of the divs in the HTML to:

<div class="child"><div class="parent"></div></div>

and the red box covered the blue box, which I think is what you're looking for.

Setting the Vim background colors

Using set bg=dark with a white background can produce nearly unreadable text in some syntax highlighting schemes. Instead, you can change the overall colorscheme to something that looks good in your terminal. The colorscheme file should set the background attribute for you appropriately. Also, for more information see:

:h color

Jackson serialization: ignore empty values (or null)

You can also set the global option:

objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);

How can I display the users profile pic using the facebook graph api?

Here is the code that worked for me!

Assuming that you have a valid session going,

//Get the current users id
$uid = $facebook->getUser();

//create the url
$profile_pic =  "http://graph.facebook.com/".$uid."/picture";

//echo the image out
echo "<img src=\"" . $profile_pic . "\" />";

Thanx goes to Raine, you da man!

How to find which git branch I am on when my disk is mounted on other server

.git/HEAD contains the path of the current ref, the working directory is using as HEAD.

What does string::npos mean in this code?

string::npos is a constant (probably -1) representing a non-position. It's returned by method find when the pattern was not found.

Python sockets error TypeError: a bytes-like object is required, not 'str' with send function

An alternative solution is to introduce a method to the file instance that would do the explicit conversion.

import types

def _write_str(self, ascii_str):
    self.write(ascii_str.encode('ascii'))

source_file = open("myfile.bin", "wb")
source_file.write_str = types.MethodType(_write_str, source_file)

And then you can use it as source_file.write_str("Hello World").

"Cannot create an instance of OLE DB provider" error as Windows Authentication user

Similar situation for following configuration:

  • Windows Server 2012 R2 Standard
  • MS SQL server 2008 (tested also SQL 2012)
  • Oracle 10g client (OracleDB v8.1.7)
  • MSDAORA provider
  • Error ID: 7302

My solution:

  • Install 32bit MS SQL Server (64bit MSDAORA doesn't exist)
  • Install 32bit Oracle 10g 10.2.0.5 patch (set W7 compatibility on setup.exe)
  • Restart SQL services
  • Check Allow in process in MSDAORA provider
  • Test linked oracle server connection

How should strace be used?

I liked some of the answers where it reads strace checks how you interacts with your operating system.

This is exactly what we can see. The system calls. If you compare strace and ltrace the difference is more obvious.

$>strace -c cd
Desktop  Documents  Downloads  examples.desktop  Music  Pictures  Public  Templates  Videos
% time     seconds  usecs/call     calls    errors syscall
------ ----------- ----------- --------- --------- ----------------
  0.00    0.000000           0         7           read
  0.00    0.000000           0         1           write
  0.00    0.000000           0        11           close
  0.00    0.000000           0        10           fstat
  0.00    0.000000           0        17           mmap
  0.00    0.000000           0        12           mprotect
  0.00    0.000000           0         1           munmap
  0.00    0.000000           0         3           brk
  0.00    0.000000           0         2           rt_sigaction
  0.00    0.000000           0         1           rt_sigprocmask
  0.00    0.000000           0         2           ioctl
  0.00    0.000000           0         8         8 access
  0.00    0.000000           0         1           execve
  0.00    0.000000           0         2           getdents
  0.00    0.000000           0         2         2 statfs
  0.00    0.000000           0         1           arch_prctl
  0.00    0.000000           0         1           set_tid_address
  0.00    0.000000           0         9           openat
  0.00    0.000000           0         1           set_robust_list
  0.00    0.000000           0         1           prlimit64
------ ----------- ----------- --------- --------- ----------------
100.00    0.000000                    93        10 total

On the other hand there is ltrace that traces functions.

$>ltrace -c cd
Desktop  Documents  Downloads  examples.desktop  Music  Pictures  Public  Templates  Videos
% time     seconds  usecs/call     calls      function
------ ----------- ----------- --------- --------------------
 15.52    0.004946         329        15 memcpy
 13.34    0.004249          94        45 __ctype_get_mb_cur_max
 12.87    0.004099        2049         2 fclose
 12.12    0.003861          83        46 strlen
 10.96    0.003491         109        32 __errno_location
 10.37    0.003303         117        28 readdir
  8.41    0.002679         133        20 strcoll
  5.62    0.001791         111        16 __overflow
  3.24    0.001032         114         9 fwrite_unlocked
  1.26    0.000400         100         4 __freading
  1.17    0.000372          41         9 getenv
  0.70    0.000222         111         2 fflush
  0.67    0.000214         107         2 __fpending
  0.64    0.000203         101         2 fileno
  0.62    0.000196         196         1 closedir
  0.43    0.000138         138         1 setlocale
  0.36    0.000114         114         1 _setjmp
  0.31    0.000098          98         1 realloc
  0.25    0.000080          80         1 bindtextdomain
  0.21    0.000068          68         1 opendir
  0.19    0.000062          62         1 strrchr
  0.18    0.000056          56         1 isatty
  0.16    0.000051          51         1 ioctl
  0.15    0.000047          47         1 getopt_long
  0.14    0.000045          45         1 textdomain
  0.13    0.000042          42         1 __cxa_atexit
------ ----------- ----------- --------- --------------------
100.00    0.031859                   244 total

Although I checked the manuals several time, I haven't found the origin of the name strace but it is likely system-call trace, since this is obvious.

There are three bigger notes to say about strace.

Note 1: Both these functions strace and ltrace are using the system call ptrace. So ptrace system call is effectively how strace works.

The ptrace() system call provides a means by which one process (the "tracer") may observe and control the execution of another process (the "tracee"), and examine and change the tracee's memory and registers. It is primarily used to implement breakpoint debugging and system call tracing.

Note 2: There are different parameters you can use with strace, since strace can be very verbose. I like to experiment with -c which is like a summary of things. Based on -c you can select one system-call like -e trace=open where you will see only that call. This can be interesting if you are examining what files will be opened during the command you are tracing. And of course, you can use the grep for the same purpose but note you need to redirect like this 2>&1 | grep etc to understand that config files are referenced when the command was issued.

Note 3: I find this very important note. You are not limited to a specific architecture. strace will blow you mind, since it can trace over binaries of different architectures. enter image description here

Reading Datetime value From Excel sheet

Perhaps you could try using the DateTime.FromOADate method to convert between Excel and .net.

Android Studio: Drawable Folder: How to put Images for Multiple dpi?

0

Right click "drawable" Click on "New", then "Image Asset" Change "Icon Type" to "Action Bar and Tab Icons" Change "Asset Type" to "Clip Art" for icon & "Image" for images For Icon: Click on "Clip Art" icon button & choose your icon For Image: Click on "Path" folder icon & choose your image For "Name" type in your icon / image file name

Multiline string literal in C#

Why do people keep confusing strings with string literals? The accepted answer is a great answer to a different question; not to this one.

I know this is an old topic, but I came here with possibly the same question as the OP, and it is frustrating to see how people keep misreading it. Or maybe I am misreading it, I don't know.

Roughly speaking, a string is a region of computer memory that, during the execution of a program, contains a sequence of bytes that can be mapped to text characters. A string literal, on the other hand, is a piece of source code, not yet compiled, that represents the value used to initialize a string later on, during the execution of the program in which it appears.

In C#, the statement...

 string query = "SELECT foo, bar"
 + " FROM table"
 + " WHERE id = 42";

... does not produce a three-line string but a one liner; the concatenation of three strings (each initialized from a different literal) none of which contains a new-line modifier.

What the OP seems to be asking -at least what I would be asking with those words- is not how to introduce, in the compiled string, line breaks that mimick those found in the source code, but how to break up for clarity a long, single line of text in the source code without introducing breaks in the compiled string. And without requiring an extended execution time, spent joining the multiple substrings coming from the source code. Like the trailing backslashes within a multiline string literal in javascript or C++.

Suggesting the use of verbatim strings, nevermind StringBuilders, String.Joins or even nested functions with string reversals and what not, makes me think that people are not really understanding the question. Or maybe I do not understand it.

As far as I know, C# does not (at least in the paleolithic version I am still using, from the previous decade) have a feature to cleanly produce multiline string literals that can be resolved during compilation rather than execution.

Maybe current versions do support it, but I thought I'd share the difference I perceive between strings and string literals.

UPDATE:

(From MeowCat2012's comment) You can. The "+" approach by OP is the best. According to spec the optimization is guaranteed: http://stackoverflow.com/a/288802/9399618

How to add bootstrap in angular 6 project?

npm install --save bootstrap

afterwards, inside angular.json (previously .angular-cli.json) inside the project's root folder, find styles and add the bootstrap css file like this:

for angular 6

"styles": [
          "../node_modules/bootstrap/dist/css/bootstrap.min.css",
          "styles.css"
],

for angular 7

"styles": [
          "node_modules/bootstrap/dist/css/bootstrap.min.css",
          "src/styles.css"
],

Using Spring RestTemplate in generic method with generic parameter

As the code below shows it, it works.

public <T> ResponseWrapper<T> makeRequest(URI uri, final Class<T> clazz) {
   ResponseEntity<ResponseWrapper<T>> response = template.exchange(
        uri,
        HttpMethod.POST,
        null,
        new ParameterizedTypeReference<ResponseWrapper<T>>() {
            public Type getType() {
                return new MyParameterizedTypeImpl((ParameterizedType) super.getType(), new Type[] {clazz});
        }
    });
    return response;
}

public class MyParameterizedTypeImpl implements ParameterizedType {
    private ParameterizedType delegate;
    private Type[] actualTypeArguments;

    MyParameterizedTypeImpl(ParameterizedType delegate, Type[] actualTypeArguments) {
        this.delegate = delegate;
        this.actualTypeArguments = actualTypeArguments;
    }

    @Override
    public Type[] getActualTypeArguments() {
        return actualTypeArguments;
    }

    @Override
    public Type getRawType() {
        return delegate.getRawType();
    }

    @Override
    public Type getOwnerType() {
        return delegate.getOwnerType();
    }

}

SQL Server: What is the difference between CROSS JOIN and FULL OUTER JOIN?

I'd like to add one important aspect to other answers, which actually explained this topic to me in the best way:

If 2 joined tables contain M and N rows, then cross join will always produce (M x N) rows, but full outer join will produce from MAX(M,N) to (M + N) rows (depending on how many rows actually match "on" predicate).

EDIT:

From logical query processing perspective, CROSS JOIN does indeed always produce M x N rows. What happens with FULL OUTER JOIN is that both left and right tables are "preserved", as if both LEFT and RIGHT join happened. So rows, not satisfying ON predicate, from both left and right tables are added to the result set.