Programs & Examples On #Blobstore

A storage API used for binary data storage, eg. Google App Engine blobstore service.

What is it exactly a BLOB in a DBMS context

I won't expand the acronym yet again... but I will add some nuance to the other definition: you can store any data in a blob regardless of other byte interpretations they may have. Text can be stored in a blob, but you would be better off with a CLOB if you have that option.

There should be no differences between BLOBS across databases in the sense that after you have saved and retrieved the data it is unchanged.... how each database achieves that is a blackbox and thankfully almost without exception irrelevant. The manner of interacting with BLOBS, however can be very different since there are no specifications in SQL standards (or standards in the specifications?) for it. Usually you will have to invoke procedures/functions to save retrieve them, and limiting any query based on the contents of a BLOB is nearly impossible if not prohibited.

Among the other stuff enumerated as binary data, you can also store binary representations of text -> character codes with a given encoding... without actually knowing or specifying the encoding used.

BLOBS are the lowest common denominators of storage formats.

Android Layout Animations from bottom to top and top to bottom on ImageView click

create directory in /res/anim and create bottom_to_original.xml

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
    <translate
        android:duration="1500"
        android:fromYDelta="100%"
        android:toYDelta="1%" />
</set>

JAVA:

    LinearLayout ll = findViewById(R.id.ll);

    Animation animation;
    animation = AnimationUtils.loadAnimation(getApplicationContext(),
            R.anim.sample_animation);
    ll .setAnimation(animation);

What is the difference between logical data model and conceptual data model?

First of all, a data model is an abstraction tool and a database model (or scheme/diagramm) is a modeling result.

Conceptual data model is DBMS-independent and covers functional/domain design area. The most known conceptual data model is "Entity-Relationship". Normally, you can reuse the conceptual scheme to produce different logical schemes not only relational.

Logical data model is intended to be implemented by some DBMS and corresponds mostly to the conceptual level of ANSI/SPARC architecture (proposed in 1975); this point gives some collisions of terminology. Zachman Framework tried to resolve this kind of collision ten years later introducing conceptual, logical and physical models.

There are many logical data models, and the most known is relational one.

So main differences of conceptual data model are the focusing on the domain and DBMS-independence whereas logical data model is the most abstract level of concrete DBMS you plan to use. Note that contemporary DBMS support several logical models at the same time.

You can also have a look to my book and to the article for more details.

Swift: How to get substring from start to last index of character

Do you want to get a substring of a string from start index to the last index of one of its characters? If so, you may choose one of the following Swift 2.0+ methods.

Methods that require Foundation

Get a substring that includes the last index of a character:

import Foundation

let string = "www.stackoverflow.com"
if let rangeOfIndex = string.rangeOfCharacterFromSet(NSCharacterSet(charactersInString: "."), options: .BackwardsSearch) {
    print(string.substringToIndex(rangeOfIndex.endIndex))
}

// prints "www.stackoverflow."

Get a substring that DOES NOT include the last index of a character:

import Foundation

let string = "www.stackoverflow.com"
if let rangeOfIndex = string.rangeOfCharacterFromSet(NSCharacterSet(charactersInString: "."), options: .BackwardsSearch) {
    print(string.substringToIndex(rangeOfIndex.startIndex))
}

// prints "www.stackoverflow"

If you need to repeat those operations, extending String can be a good solution:

import Foundation

extension String {
    func substringWithLastInstanceOf(character: Character) -> String? {
        if let rangeOfIndex = rangeOfCharacterFromSet(NSCharacterSet(charactersInString: String(character)), options: .BackwardsSearch) {
            return self.substringToIndex(rangeOfIndex.endIndex)
        }
        return nil
    }
    func substringWithoutLastInstanceOf(character: Character) -> String? {
        if let rangeOfIndex = rangeOfCharacterFromSet(NSCharacterSet(charactersInString: String(character)), options: .BackwardsSearch) {
            return self.substringToIndex(rangeOfIndex.startIndex)
        }
        return nil
    }
}

print("www.stackoverflow.com".substringWithLastInstanceOf("."))
print("www.stackoverflow.com".substringWithoutLastInstanceOf("."))

/*
prints:
Optional("www.stackoverflow.")
Optional("www.stackoverflow")
*/

Methods that DO NOT require Foundation

Get a substring that includes the last index of a character:

let string = "www.stackoverflow.com"
if let reverseIndex = string.characters.reverse().indexOf(".") {
    print(string[string.startIndex ..< reverseIndex.base])
}

// prints "www.stackoverflow."

Get a substring that DOES NOT include the last index of a character:

let string = "www.stackoverflow.com"
if let reverseIndex = string.characters.reverse().indexOf(".") {
    print(string[string.startIndex ..< reverseIndex.base.advancedBy(-1)])
}

// prints "www.stackoverflow"

If you need to repeat those operations, extending String can be a good solution:

extension String {
    func substringWithLastInstanceOf(character: Character) -> String? {
        if let reverseIndex = characters.reverse().indexOf(".") {
            return self[self.startIndex ..< reverseIndex.base]
        }
        return nil
    }
    func substringWithoutLastInstanceOf(character: Character) -> String? {
        if let reverseIndex = characters.reverse().indexOf(".") {
            return self[self.startIndex ..< reverseIndex.base.advancedBy(-1)]
        }
        return nil
    }
}

print("www.stackoverflow.com".substringWithLastInstanceOf("."))
print("www.stackoverflow.com".substringWithoutLastInstanceOf("."))

/*
prints:
Optional("www.stackoverflow.")
Optional("www.stackoverflow")
*/

Combining the results of two SQL queries as separate columns

how to club the 4 query's as a single query

show below query

  1. total number of cases pending + 2.cases filed during this month ( base on sysdate) + total number of cases (1+2) + no. cases disposed where nse= disposed + no. of cases pending (other than nse <> disposed)

nsc = nature of case

report is taken on 06th of every month

( monthly report will be counted from 05th previous month to 05th present of present month)

How do you calculate program run time in python?

@JoshAdel covered a lot of it, but if you just want to time the execution of an entire script, you can run it under time on a unix-like system.

kotai:~ chmullig$ cat sleep.py 
import time

print "presleep"
time.sleep(10)
print "post sleep"
kotai:~ chmullig$ python sleep.py 
presleep
post sleep
kotai:~ chmullig$ time python sleep.py 
presleep
post sleep

real    0m10.035s
user    0m0.017s
sys 0m0.016s
kotai:~ chmullig$ 

Safely casting long to int in Java

I think I'd do it as simply as:

public static int safeLongToInt(long l) {
    if (l < Integer.MIN_VALUE || l > Integer.MAX_VALUE) {
        throw new IllegalArgumentException
            (l + " cannot be cast to int without changing its value.");
    }
    return (int) l;
}

I think that expresses the intent more clearly than the repeated casting... but it's somewhat subjective.

Note of potential interest - in C# it would just be:

return checked ((int) l);

Java rounding up to an int using Math.ceil

int total = (int) Math.ceil((double)157/32);

Python popen command. Wait until the command is finished

Let the command you are trying to pass be

os.system('x')

then you covert it to a statement

t = os.system('x')

now the python will be waiting for the output from the commandline so that it could be assigned to the variable t.

"Active Directory Users and Computers" MMC snap-in for Windows 7?

Per Noalt's answer is correct. However, if you want the snap-in mentioned in the title (Users and Computers), you'll also have to run these commands at a command-line afterwards, as an Administrator:

dism /online /enable-feature /featurename:RemoteServerAdministrationTools-Roles-AD-DS
dism /online /enable-feature /featurename:RemoteServerAdministrationTools-Roles-AD-DS-SnapIns

Note - I had to run these in order for AD Users and Computers to show up, as they were disabled on my computer after the install. This might not be the case for all users.

Nested JSON objects - do I have to use arrays for everything?

You have too many redundant nested arrays inside your jSON data, but it is possible to retrieve the information. Though like others have said you might want to clean it up.

use each() wrap within another each() until the last array.

for result.data[0].stuff[0].onetype[0] in jQuery you could do the following:

`

$.each(data.result.data, function(index0, v) {
    $.each(v, function (index1, w) {
        $.each(w, function (index2, x) {
            alert(x.id);
        });
    });

});

`

How set background drawable programmatically in Android

You can also set the background of any Image:

View v;
Drawable image=(Drawable)getResources().getDrawable(R.drawable.img);
(ImageView)v.setBackground(image);

What is the difference between :focus and :active?

Using "focus" will give keyboard users the same effect that mouse users get when they hover with a mouse. "Active" is needed to get the same effect in Internet Explorer.

The reality is, these states do not work as they should for all users. Not using all three selectors creates accessibility issues for many keyboard-only users who are physically unable to use a mouse. I invite you to take the #nomouse challenge (nomouse dot org).

Detect if a jQuery UI dialog box is open

Nick Craver's comment is the simplest to avoid the error that occurs if the dialog has not yet been defined:

if ($('#elem').is(':visible')) { 
  // do something
}

You should set visibility in your CSS first though, using simply:

#elem { display: none; }

Generic Property in C#

You would need to create a generic class named MyProp. Then, you will need to add implicit or explicit cast operators so you can get and set the value as if it were the type specified in the generic type parameter. These cast operators can do the extra work that you need.

json_encode function: special characters

you should use this code:

$json = json_encode(array_map('utf8_encode', $arr))

array_map function converts special characters in UTF8 standard

Git: How to check if a local repo is up to date?

git remote show origin


Enter passphrase for key ....ssh/id_rsa:
* remote origin
  Fetch URL: [email protected]:mamaque/systems.git
  Push  URL: [email protected]:mamaque/systems.git 

  HEAD branch: main
  Remote branch:
    main tracked
   Local ref configured for 'git push':

main pushes to main (up-to-date) Both are up to date
main pushes to main (fast-forwardable) Remote can be updated with Local
main pushes to main (local out of date) Local can be update with Remote

get specific row from spark dataframe

This is how I achieved the same in Scala. I am not sure if it is more efficient than the valid answer, but it requires less coding

val parquetFileDF = sqlContext.read.parquet("myParquetFule.parquet")

val myRow7th = parquetFileDF.rdd.take(7).last

Sort JavaScript object by key

I am actually very surprised that over 30 answers were given, and yet none gave a full deep solution for this problem. Some had shallow solution, while others had deep but faulty (it'll crash if undefined, function or symbol will be in the json).

Here is the full solution:

function sortObject(unordered, sortArrays = false) {
  if (!unordered || typeof unordered !== 'object') {
    return unordered;
  }

  if (Array.isArray(unordered)) {
    const newArr = unordered.map((item) => sortObject(item, sortArrays));
    if (sortArrays) {
      newArr.sort();
    }
    return newArr;
  }

  const ordered = {};
  Object.keys(unordered)
    .sort()
    .forEach((key) => {
      ordered[key] = sortObject(unordered[key], sortArrays);
    });
  return ordered;
}

const json = {
  b: 5,
  a: [2, 1],
  d: {
    b: undefined,
    a: null,
    c: false,
    d: true,
    g: '1',
    f: [],
    h: {},
    i: 1n,
    j: () => {},
    k: Symbol('a')
  },
  c: [
    {
      b: 1,
      a: 1
    }
  ]
};
console.log(sortObject(json, true));

How to get a path to the desktop for current user in C#?

// Environment.GetFolderPath
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData); // Current User's Application Data
Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData); // All User's Application Data
Environment.GetFolderPath(Environment.SpecialFolder.CommonProgramFiles); // Program Files
Environment.GetFolderPath(Environment.SpecialFolder.Cookies); // Internet Cookie
Environment.GetFolderPath(Environment.SpecialFolder.Desktop); // Logical Desktop
Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory); // Physical Desktop
Environment.GetFolderPath(Environment.SpecialFolder.Favorites); // Favorites
Environment.GetFolderPath(Environment.SpecialFolder.History); // Internet History
Environment.GetFolderPath(Environment.SpecialFolder.InternetCache); // Internet Cache
Environment.GetFolderPath(Environment.SpecialFolder.MyComputer); // "My Computer" Folder
Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); // "My Documents" Folder
Environment.GetFolderPath(Environment.SpecialFolder.MyMusic); // "My Music" Folder
Environment.GetFolderPath(Environment.SpecialFolder.MyPictures); // "My Pictures" Folder
Environment.GetFolderPath(Environment.SpecialFolder.Personal); // "My Document" Folder
Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles); // Program files Folder
Environment.GetFolderPath(Environment.SpecialFolder.Programs); // Programs Folder
Environment.GetFolderPath(Environment.SpecialFolder.Recent); // Recent Folder
Environment.GetFolderPath(Environment.SpecialFolder.SendTo); // "Sent to" Folder
Environment.GetFolderPath(Environment.SpecialFolder.StartMenu); // Start Menu
Environment.GetFolderPath(Environment.SpecialFolder.Startup); // Startup
Environment.GetFolderPath(Environment.SpecialFolder.System); // System Folder
Environment.GetFolderPath(Environment.SpecialFolder.Templates); // Document Templates

MSSQL Error 'The underlying provider failed on Open'

The SQL Server Express service were not set tostart automatically.

1) Go to control panel 2) Administrative Tools 3) Service 4) Set SQL Server express to start automatically by clicking on it 5) Right click and start the service

I hope that will help.

Java: splitting the filename into a base and extension

http://docs.oracle.com/javase/6/docs/api/java/io/File.html#getName()

From http://www.xinotes.org/notes/note/774/ :

Java has built-in functions to get the basename and dirname for a given file path, but the function names are not so self-apparent.

import java.io.File;

public class JavaFileDirNameBaseName {
    public static void main(String[] args) {
    File theFile = new File("../foo/bar/baz.txt");
    System.out.println("Dirname: " + theFile.getParent());
    System.out.println("Basename: " + theFile.getName());
    }
}

How to change the MySQL root account password on CentOS7?

All,

Here a little bit twist with mysql-community-server 5.7 I share some steps, how to reset mysql5.7 root password or set password. it will work centos7 and RHEL7 as well.

step1. 1st stop your databases

service mysqld stop

step2. 2nd modify /etc/my.cnf file add "skip-grant-tables"

vi /etc/my.cnf

[mysqld] skip-grant-tables

step3. 3rd start mysql

service mysqld start

step4. select mysql default database

mysql -u root

mysql>use mysql;

step4. set a new password

mysql> update user set authentication_string=PASSWORD("yourpassword") where User='root';

step5 restart mysql database

service mysqld restart

 mysql -u root -p

enjoy :)

Signed to unsigned conversion in C - is it always safe?

When one unsigned and one signed variable are added (or any binary operation) both are implicitly converted to unsigned, which would in this case result in a huge result.

So it is safe in the sense of that the result might be huge and wrong, but it will never crash.

How to convert an Object {} to an Array [] of key-value pairs in JavaScript

Use Object.keys and Array#map methods.

_x000D_
_x000D_
var obj = {_x000D_
  "1": 5,_x000D_
  "2": 7,_x000D_
  "3": 0,_x000D_
  "4": 0,_x000D_
  "5": 0,_x000D_
  "6": 0,_x000D_
  "7": 0,_x000D_
  "8": 0,_x000D_
  "9": 0,_x000D_
  "10": 0,_x000D_
  "11": 0,_x000D_
  "12": 0_x000D_
};_x000D_
// get all object property names_x000D_
var res = Object.keys(obj)_x000D_
  // iterate over them and generate the array_x000D_
  .map(function(k) {_x000D_
    // generate the array element _x000D_
    return [+k, obj[k]];_x000D_
  });_x000D_
_x000D_
console.log(res);
_x000D_
_x000D_
_x000D_

Extracting text from a PDF file using PDFMiner in python?

this code is tested with pdfminer for python 3 (pdfminer-20191125)

from pdfminer.layout import LAParams
from pdfminer.converter import PDFPageAggregator
from pdfminer.pdfinterp import PDFResourceManager
from pdfminer.pdfinterp import PDFPageInterpreter
from pdfminer.pdfpage import PDFPage
from pdfminer.layout import LTTextBoxHorizontal

def parsedocument(document):
    # convert all horizontal text into a lines list (one entry per line)
    # document is a file stream
    lines = []
    rsrcmgr = PDFResourceManager()
    laparams = LAParams()
    device = PDFPageAggregator(rsrcmgr, laparams=laparams)
    interpreter = PDFPageInterpreter(rsrcmgr, device)
    for page in PDFPage.get_pages(document):
            interpreter.process_page(page)
            layout = device.get_result()
            for element in layout:
                if isinstance(element, LTTextBoxHorizontal):
                    lines.extend(element.get_text().splitlines())
    return lines

Sending "User-agent" using Requests library in Python

The user-agent should be specified as a field in the header.

Here is a list of HTTP header fields, and you'd probably be interested in request-specific fields, which includes User-Agent.

If you're using requests v2.13 and newer

The simplest way to do what you want is to create a dictionary and specify your headers directly, like so:

import requests

url = 'SOME URL'

headers = {
    'User-Agent': 'My User Agent 1.0',
    'From': '[email protected]'  # This is another valid field
}

response = requests.get(url, headers=headers)

If you're using requests v2.12.x and older

Older versions of requests clobbered default headers, so you'd want to do the following to preserve default headers and then add your own to them.

import requests

url = 'SOME URL'

# Get a copy of the default headers that requests would use
headers = requests.utils.default_headers()

# Update the headers with your custom ones
# You don't have to worry about case-sensitivity with
# the dictionary keys, because default_headers uses a custom
# CaseInsensitiveDict implementation within requests' source code.
headers.update(
    {
        'User-Agent': 'My User Agent 1.0',
    }
)

response = requests.get(url, headers=headers)

In what cases will HTTP_REFERER be empty

It will/may be empty when the enduser

  • entered the site URL in browser address bar itself.
  • visited the site by a browser-maintained bookmark.
  • visited the site as first page in the window/tab.
  • clicked a link in an external application.
  • switched from a https URL to a http URL.
  • switched from a https URL to a different https URL.
  • has security software installed (antivirus/firewall/etc) which strips the referrer from all requests.
  • is behind a proxy which strips the referrer from all requests.
  • visited the site programmatically (like, curl) without setting the referrer header (searchbots!).

Message: Trying to access array offset on value of type null

This happens because $cOTLdata is not null but the index 'char_data' does not exist. Previous versions of PHP may have been less strict on such mistakes and silently swallowed the error / notice while 7.4 does not do this anymore.

To check whether the index exists or not you can use isset():

isset($cOTLdata['char_data'])

Which means the line should look something like this:

$len = isset($cOTLdata['char_data']) ? count($cOTLdata['char_data']) : 0;

Note I switched the then and else cases of the ternary operator since === null is essentially what isset already does (but in the positive case).

PHP Get all subdirectories of a given directory

This is the one liner code:

 $sub_directories = array_map('basename', glob($directory_path . '/*', GLOB_ONLYDIR));

What does ON [PRIMARY] mean?

To add a very important note on what Mark S. has mentioned in his post. In the specific SQL Script that has been mentioned in the question you can NEVER mention two different file groups for storing your data rows and the index data structure.

The reason why is due to the fact that the index being created in this case is a clustered Index on your primary key column. The clustered index data and the data rows of your table can NEVER be on different file groups.

So in case you have two file groups on your database e.g. PRIMARY and SECONDARY then below mentioned script will store your row data and clustered index data both on PRIMARY file group itself even though I've mentioned a different file group ([SECONDARY]) for the table data. More interestingly the script runs successfully as well (when I was expecting it to give an error as I had given two different file groups :P). SQL Server does the trick behind the scene silently and smartly.

CREATE TABLE [dbo].[be_Categories](
    [CategoryID] [uniqueidentifier] ROWGUIDCOL  NOT NULL CONSTRAINT [DF_be_Categories_CategoryID]  DEFAULT (newid()),
    [CategoryName] [nvarchar](50) NULL,
    [Description] [nvarchar](200) NULL,
    [ParentID] [uniqueidentifier] NULL,
 CONSTRAINT [PK_be_Categories] PRIMARY KEY CLUSTERED 
(
    [CategoryID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [SECONDARY]
GO

NOTE: Your index can reside on a different file group ONLY if the index being created is non-clustered in nature.

The below script which creates a non-clustered index will get created on [SECONDARY] file group instead when the table data already resides on [PRIMARY] file group:

CREATE NONCLUSTERED INDEX [IX_Categories] ON [dbo].[be_Categories]
(
    [CategoryName] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Secondary]
GO

You can get more information on how storing non-clustered indexes on a different file group can help your queries perform better. Here is one such link.

java.lang.ClassNotFoundException: com.sun.jersey.spi.container.servlet.ServletContainer

We get this error because of build path issue. You should add "Server Runtime" libraries in Build Path.

"java.lang.ClassNotFoundException: com.sun.jersey.spi.container.servlet.ServletContainer"

Please follow below steps to resolve class not found exception.

Right click on project --> Build Path --> Java Build Path --> Add Library --> Server Runtime --> Apache Tomcat v7.0

How do you hide the Address bar in Google Chrome for Chrome Apps?

Even though the question is about gaining some space removing the address bar, you can also gain some space by toggling the bookmark bar on and off, using Ctrl + Shift + B, or ? Cmd + Shift + B, in Mac OS.

Unlocking tables if thread is lost

With Sequel Pro:

Restarting the app unlocked my tables. It resets the session connection.

NOTE: I was doing this for a site on my local machine.

Where is virtualenvwrapper.sh after pip install?

For RPM-based distributions(like Fedora 19), after running the sudo pip install virtualenvwrapper command, you may find the file at:

/usr/bin/virtualenvwrapper.sh

How to stop an animation (cancel() does not work)

If you are using the animation listener, set v.setAnimationListener(null). Use the following code with all options.

v.getAnimation().cancel();
v.clearAnimation();
animation.setAnimationListener(null);

Import CSV file as a pandas DataFrame

%cd C:\Users\asus\Desktop\python
import pandas as pd
df = pd.read_csv('value.txt')
df.head()
    Date    price   factor_1    factor_2
0   2012-06-11  1600.20 1.255   1.548
1   2012-06-12  1610.02 1.258   1.554
2   2012-06-13  1618.07 1.249   1.552
3   2012-06-14  1624.40 1.253   1.556
4   2012-06-15  1626.15 1.258   1.552

Hibernate error: ids for this class must be manually assigned before calling save():

For hibernate it is important to know that your object WILL have an id, when you want to persist/save it. Thus, make sure that

    private String U_id;

will have a value, by the time you are going to persist your object. You can do that with the @GeneratedValue annotation or by assigning a value manually.

In the case you need or want to assign your id's manually (and that's what the above error is actually about), I would prefer passing the values for the fields to your constructor, at least for U_id, e.g.

  public Role (String U_id) { ... }

This ensures that your object has an id, by the time you have instantiated it. I don't know what your use case is and how your application behaves in concurrency, however, in some cases this is not recommended. You need to ensure that your id is unique.

Further note: Hibernate will still require a default constructor, as stated in the hibernate documentation. In order to prevent you (and maybe other programmers if you're designing an api) of instantiations of Role using the default constructor, just declare it as private.

How to make a <div> always full screen?

This is the most stable (and easy) way to do it, and it works in all modern browsers:

_x000D_
_x000D_
.fullscreen {_x000D_
  position: fixed;_x000D_
  top: 0;_x000D_
  left: 0;_x000D_
  bottom: 0;_x000D_
  right: 0;_x000D_
  overflow: auto;_x000D_
  background: lime; /* Just to visualize the extent */_x000D_
  _x000D_
}
_x000D_
<div class="fullscreen">_x000D_
  Suspendisse aliquam in ante a ornare. Pellentesque quis sapien sit amet dolor euismod congue. Donec non semper arcu. Sed tortor ante, cursus in dui vitae, interdum vestibulum massa. Suspendisse aliquam in ante a ornare. Pellentesque quis sapien sit amet dolor euismod congue. Donec non semper arcu. Sed tortor ante, cursus in dui vitae, interdum vestibulum massa. Suspendisse aliquam in ante a ornare. Pellentesque quis sapien sit amet dolor euismod congue. Donec non semper arcu. Sed tortor ante, cursus in dui vitae, interdum vestibulum massa. Suspendisse aliquam in ante a ornare. Pellentesque quis sapien sit amet dolor euismod congue. Donec non semper arcu. Sed tortor ante, cursus in dui vitae, interdum vestibulum massa._x000D_
</div>
_x000D_
_x000D_
_x000D_

Tested to work in Firefox, Chrome, Opera, Vivaldi, IE7+ (based on emulation in IE11).

converting a javascript string to a html object

var s = '<div id="myDiv"></div>';
var htmlObject = document.createElement('div');
htmlObject.innerHTML = s;
htmlObject.getElementById("myDiv").style.marginTop = something;

How do I access ViewBag from JS

try: var cc = @Html.Raw(Json.Encode(ViewBag.CC)

How to lowercase a pandas dataframe string column if it has missing values?

copy your Dataframe column and simply apply

df=data['x']
newdf=df.str.lower()

ASP.NET MVC: Custom Validation by DataAnnotation

ExpressiveAnnotations gives you such a possibility:

[Required]
[AssertThat("Length(FieldA) + Length(FieldB) + Length(FieldC) + Length(FieldD) > 50")]
public string FieldA { get; set; }

What's an object file in C?

An object file is just what you get when you compile one (or several) source file(s).

It can be either a fully completed executable or library, or intermediate files.

The object files typically contain native code, linker information, debugging symbols and so forth.

How to replace a string in a SQL Server Table Column

select replace(ImagePath, '~/', '../') as NewImagePath from tblMyTable 

where "ImagePath" is my column Name.
"NewImagePath" is temporery column Name insted of "ImagePath"
"~/" is my current string.(old string)
"../" is my requried string.(new string)
"tblMyTable" is my table in database.

Is there a foreach in MATLAB? If so, how does it behave if the underlying data changes?

I think this is what the OP really wants:

array = -1:0.1:10

for i=1:numel(array)
    disp(array(i))
end

How to put multiple statements in one line?

You could use the built-in exec statement, eg.:

exec("try: \n \t if sam[0] != 'harry': \n \t\t print('hello',  sam) \nexcept: pass")

Where \n is a newline and \t is used as indentation (a tab).
Also, you should count the spaces you use, so your indentation matches exactly.

However, as all the other answers already said, this is of course only to be used when you really have to put it on one line.

exec is quite a dangerous statement (especially when building a webapp) since it allows execution of arbitrary Python code.

Trying to check if username already exists in MySQL database using PHP

Here's one that i wrote:

$error = false;
$sql= "SELECT username FROM users WHERE username = '$username'";
$checkSQL = mysqli_query($db, $checkSQL);

if(mysqli_num_rows($checkSQL) != 0) {
   $error = true;
   echo '<span class="error">Username taken.</span>';
}

Works like a charm!

AngularJS does not send hidden field value

In the controller:

$scope.entityId = $routeParams.entityId;

In the view:

<input type="hidden" name="entityId" ng-model="entity.entityId" ng-init="entity.entityId = entityId" />

How do you parse and process HTML/XML in PHP?

For 1a and 2: I would vote for the new Symfony Componet class DOMCrawler ( DomCrawler ). This class allows queries similar to CSS Selectors. Take a look at this presentation for real-world examples: news-of-the-symfony2-world.

The component is designed to work standalone and can be used without Symfony.

The only drawback is that it will only work with PHP 5.3 or newer.

How do I check if an integer is even or odd?

You guys are waaaaaaaay too efficient. What you really want is:

public boolean isOdd(int num) {
  int i = 0;
  boolean odd = false;

  while (i != num) {
    odd = !odd;
    i = i + 1;
  }

  return odd;
}

Repeat for isEven.

Of course, that doesn't work for negative numbers. But with brilliance comes sacrifice...

Sending event when AngularJS finished loading

Angular hasn't provided a way to signal when a page finished loading, maybe because "finished" depends on your application. For example, if you have hierarchical tree of partials, one loading the others. "Finish" would mean that all of them have been loaded. Any framework would have a hard time analyzing your code and understanding that everything is done, or still waited upon. For that, you would have to provide application-specific logic to check and determine that.

Markdown and image alignment

Many Markdown "extra" processors support attributes. So you can include a class name like so (PHP Markdown Extra):

![Flowers](/flowers.jpeg){.callout}

or, alternatively (Maruku, Kramdown, Python Markdown):

![Flowers](/flowers.jpeg){: .callout}

Then, of course, you can use a stylesheet the proper way:

.callout {
    float: right;
}

If yours supports this syntax, it gives you the best of both worlds: no embedded markup, and a stylesheet abstract enough to not need to be modified by your content editor.

How to get the file-path of the currently executing javascript code

I've coded a simple function which allows to get the absolute location of the current javascript file, by using a try/catch method.

// Get script file location
// doesn't work for older browsers

var getScriptLocation = function() {
    var fileName    = "fileName";
    var stack       = "stack";
    var stackTrace  = "stacktrace";
    var loc     = null;

    var matcher = function(stack, matchedLoc) { return loc = matchedLoc; };

    try { 

        // Invalid code
        0();

    }  catch (ex) {

        if(fileName in ex) { // Firefox
            loc = ex[fileName];
        } else if(stackTrace in ex) { // Opera
            ex[stackTrace].replace(/called from line \d+, column \d+ in (.*):/gm, matcher);
        } else if(stack in ex) { // WebKit, Blink and IE10
            ex[stack].replace(/at.*?\(?(\S+):\d+:\d+\)?$/g, matcher);
        }

        return loc;
    }

};

You can see it here.

Javascript setInterval not working

Try this:

function funcName() {
    alert("test");
}

var run = setInterval(funcName, 10000)

java.security.cert.CertificateException: Certificates does not conform to algorithm constraints

colleagues.

I have faced with this trouble during a development of automation tests for our REST API. JDK 7_80 was installed at my machine only. Before I installed JDK 8, everything worked just fine and I had a possibility to obtain OAuth 2.0 tokens with a JMeter. After I installed JDK 8, the nightmare with Certificates does not conform to algorithm constraints began.

Both JMeter and Serenity did not have a possibility to obtain a token. JMeter uses the JDK library to make the request. The library just raises an exception when the library call is made to connect to endpoints that use it, ignoring the request.

The next thing was to comment all the lines dedicated to disabledAlgorithms in ALL java.security files.

C:\Java\jre7\lib\security\java.security
C:\Java\jre8\lib\security\java.security
C:\Java\jdk8\jre\lib\security\java.security
C:\Java\jdk7\jre\lib\security\java.security

Then it started to work at last. I know, that's a brute force approach, but it was the most simple way to fix it.

# jdk.tls.disabledAlgorithms=SSLv3, RC4, MD5withRSA, DH keySize < 768
# jdk.certpath.disabledAlgorithms=MD2, MD5, RSA keySize < 1024

How to close TCP and UDP ports via windows command line

you can use program like tcpview from sysinternal. I guess it can help you a lot on both monitoring and killing unwanted connection.

Open Cygwin at a specific folder

I use and Icon to launch my cygwin without the chere package.

  1. Create a shortcut on my desktop for the cygwin terminal.
  2. R-click the icon and select properties.
  3. On the shortcut tab, use this for the TARGET: C:\cygwin64\bin\mintty.exe -i /Cygwin-Terminal.ico -c 'cd'
  4. For START IN, Put the path of the dir/folder where you want to launch cygwin. i.e. C:\some\dir\name\here

WPF Databinding: How do I access the "parent" data context?

You could try something like this:

...Binding="{Binding RelativeSource={RelativeSource FindAncestor, 
AncestorType={x:Type Window}}, Path=DataContext.AllowItemCommand}" ...

Can I animate absolute positioned element with CSS transition?

try this:

.test {
    position:absolute;
    background:blue;
    width:200px;
    height:200px;
    top:40px;
    transition:left 1s linear;
    left: 0;
}

Move existing, uncommitted work to a new branch in Git

Update 2020 / Git 2.23

Git 2.23 adds the new switch subcommand in an attempt to clear some of the confusion that comes from the overloaded usage of checkout (switching branches, restoring files, detaching HEAD, etc.)

Starting with this version of Git, replace above's command with:

git switch -c <new-branch>

The behavior is identical and remains unchanged.


Before Update 2020 / Git 2.23

Use the following:

git checkout -b <new-branch>

This will leave your current branch as it is, create and checkout a new branch and keep all your changes. You can then stage changes in files to commit with:

git add <files>

and commit to your new branch with:

git commit -m "<Brief description of this commit>"

The changes in the working directory and changes staged in index do not belong to any branch yet. This changes the branch where those modifications would end in.

You don't reset your original branch, it stays as it is. The last commit on <old-branch> will still be the same. Therefore you checkout -b and then commit.

Understanding PIVOT function in T-SQL

A pivot is used to convert one of the columns in your data set from rows into columns (this is typically referred to as the spreading column). In the example you have given, this means converting the PhaseID rows into a set of columns, where there is one column for each distinct value that PhaseID can contain - 1, 5 and 6 in this case.

These pivoted values are grouped via the ElementID column in the example that you have given.

Typically you also then need to provide some form of aggregation that gives you the values referenced by the intersection of the spreading value (PhaseID) and the grouping value (ElementID). Although in the example given the aggregation that will be used is unclear, but involves the Effort column.

Once this pivoting is done, the grouping and spreading columns are used to find an aggregation value. Or in your case, ElementID and PhaseIDX lookup Effort.

Using the grouping, spreading, aggregation terminology you will typically see example syntax for a pivot as:

WITH PivotData AS
(
    SELECT <grouping column>
        , <spreading column>
        , <aggregation column>
    FROM <source table>
)
SELECT <grouping column>, <distinct spreading values>
FROM PivotData
    PIVOT (<aggregation function>(<aggregation column>)
        FOR <spreading column> IN <distinct spreading values>));

This gives a graphical explanation of how the grouping, spreading and aggregation columns convert from the source to pivoted tables if that helps further.

View stored procedure/function definition in MySQL

SHOW CREATE PROCEDURE <name>

Returns the text of a previously defined stored procedure that was created using the CREATE PROCEDURE statement. Swap PROCEDURE for FUNCTION for a stored function.

How to increase image size of pandas.DataFrame.plot in jupyter notebook?

If you want to make a change global to the whole notebook:

import matplotlib.pyplot as plt
%matplotlib inline
plt.rcParams["figure.figsize"] = [10, 5]

Can a for loop increment/decrement by more than one?

for (var i = 0; i < myVar.length; i+=3) {
   //every three
}

additional

Operator   Example    Same As
  ++       X ++        x = x + 1
  --       X --        x = x - 1
  +=       x += y      x = x + y
  -=       x -= y      x = x - y
  *=       x *= y      x = x * y
  /=       x /= y      x = x / y
  %=       x %= y      x = x % y

IntelliJ IDEA "cannot resolve symbol" and "cannot resolve method"

First check if you have configured JDK correctly:

  • Go to File->Project Structure -> SDKs
  • your JDK home path should be something like this: /Library/Java/JavaVirtualMachine/jdk.1.7.0_79.jdk/Contents/Home
  • Hit Apply and then OK

Secondly check if you have provided in path in Library's section

  • Go to File->Project Structure -> Libraries
  • Hit the + button
  • Add the path to your src folder
  • Hit Apply and then OK

This should fix the problem

AngularJS: How to make angular load script inside ng-include?

ocLazyLoad allows to lazily load scripts in the templates/views via routers (e.g. ui-router). Here is a sniplet

$stateProvider.state('parent', {
    url: "/",
    resolve: {
        loadMyService: ['$ocLazyLoad', function($ocLazyLoad) {
             return $ocLazyLoad.load('js/ServiceTest.js');
        }]
    }
})
.state('parent.child', {
    resolve: {
        test: ['loadMyService', '$ServiceTest', function(loadMyService, $ServiceTest) {
            // you can use your service
            $ServiceTest.doSomething();
        }]
    }
});  

how to solve Error cannot add duplicate collection entry of type add with unique key attribute 'value' in iis 7

IIS7 defines a defaultDocument section in its configuration files which can be found in the %WinDir%\System32\InetSrv\Config folder. Most likely, the file index.aspx is already defined as a default document in one of IIS7's configuration files and you are adding it again in your web.config.

I suspect that removing the line <add value="index.aspx" />

from the defaultDocument/files section will fix your issue.

The defaultDocument section of your config will look like:

<defaultDocument>
  <files>
    <remove value="default.aspx" />
    <remove value="index.html" />
    <remove value="iisstart.htm" />
    <remove value="index.htm" />
    <remove value="Default.asp" />
    <remove value="Default.htm" />
  </files>
</defaultDocument>

Note that index.aspx will still appear in the list of default documents for your site in the IIS manager.

For more information about IIS7 configuration, click here.

angular 2 ngIf and CSS transition/animation

Am using angular 5 and for an ngif to work for me that is in a ngfor, I had to use animateChild and in the user-detail component I used the *ngIf="user.expanded" to show hide user and it worked for entering a leaving

 <div *ngFor="let user of users" @flyInParent>
  <ly-user-detail [user]= "user" @flyIn></user-detail>
</div>

//the animation file


export const FLIP_TRANSITION = [ 
trigger('flyInParent', [
    transition(':enter, :leave', [
      query('@*', animateChild())
    ])
  ]),
  trigger('flyIn', [
    state('void', style({width: '100%', height: '100%'})),
    state('*', style({width: '100%', height: '100%'})),
    transition(':enter', [
      style({
        transform: 'translateY(100%)',
        position: 'fixed'
      }),
      animate('0.5s cubic-bezier(0.35, 0, 0.25, 1)', style({transform: 'translateY(0%)'}))
    ]),
    transition(':leave', [
      style({
        transform: 'translateY(0%)',
        position: 'fixed'
      }),
      animate('0.5s cubic-bezier(0.35, 0, 0.25, 1)', style({transform: 'translateY(100%)'}))
    ])
  ])
];

Trouble Connecting to sql server Login failed. "The login is from an untrusted domain and cannot be used with Windows authentication"

If you have two servers on the same domain (eg. APP and DB), you can also use Windows Authentication between the app and MSSQL by setting up local users on both machines that match (same username and password). If you don't have the passwords matched up, it can throw this error.

How to make primary key as autoincrement for Room Persistence lib

Its unbelievable after so many answers, but I did it little differently in the end. I don't like primary key to be nullable, I want to have it as first argument and also want to insert without defining it and also it should not be var.

@Entity(tableName = "employments")
data class Employment(
    @PrimaryKey(autoGenerate = true) val id: Long,
    @ColumnInfo(name = "code") val code: String,
    @ColumnInfo(name = "title") val name: String
){
    constructor(code: String, name: String) : this(0, code, name)
}

Setting the default active profile in Spring-boot

One can have separate application properties files according to the environment, if Spring Boot application is being created. For example - properties file for dev environment, application-dev.properties:

spring.hivedatasource.url=<hive dev data source url>
spring.hivedatasource.username=dev
spring.hivedatasource.password=dev
spring.hivedatasource.driver-class-name=org.apache.hive.jdbc.HiveDriver

application-test.properties:

spring.hivedatasource.url=<hive dev data source url>
spring.hivedatasource.username=test
spring.hivedatasource.password=test
spring.hivedatasource.driver-class-name=org.apache.hive.jdbc.HiveDriver

And a primary application.properties file to select the profile:

application.properties:

spring.profiles.active=dev
server.tomcat.max-threads = 10
spring.application.name=sampleApp

Define the DB Configuration as below:

@Configuration
@ConfigurationProperties(prefix="spring.hivedatasource")
public class DBConfig {

    @Profile("dev")
    @Qualifier("hivedatasource")
    @Primary
    @Bean
    public DataSource devHiveDataSource() {
        System.out.println("DataSource bean created for Dev");
        return new BasicDataSource();
    }

    @Profile("test")
    @Qualifier("hivedatasource")
    @Primary
    @Bean
    public DataSource testHiveDataSource() {
        System.out.println("DataSource bean created for Test");
        return new BasicDataSource();
    }

This will automatically create the BasicDataSource bean according to the active profile set in application.properties file. Run the Spring-boot application and test.

Note that this will create an empty bean initially until getConnection() is called. Once the connection is available you can get the url, driver-class, etc. using that DataSource bean.

Install-Module : The term 'Install-Module' is not recognized as the name of a cmdlet

I have Windows 10 and PowerShell 5.1 was already installed. For whatever reason the x86 version works and can find "Install-Module", but the other version cannot.

Search your Start Menu for "powershell", and find the entry that ends in "(x86)":

Windows 10 Start Menu searching for PowerShell

Here is what I experience between the two different versions:

PowerShell x86 vs x64 running Install-Module cmdlet comparison

How to do sed like text replace with python?

If I want something like sed, then I usually just call sed itself using the sh library.

from sh import sed

sed(['-i', 's/^# deb/deb/', '/etc/apt/sources.list'])

Sure, there are downsides. Like maybe the locally installed version of sed isn't the same as the one you tested with. In my cases, this kind of thing can be easily handled at another layer (like by examining the target environment beforehand, or deploying in a docker image with a known version of sed).

How can I process each letter of text using Javascript?

You can simply iterate it as in an array:

for(var i in txt){
    console.log(txt[i]);
}

How to get page content using cURL?

For a realistic approach that emulates the most human behavior, you may want to add a referer in your curl options. You may also want to add a follow_location to your curl options. Trust me, whoever said that cURLING Google results is impossible, is a complete dolt and should throw his/her computer against the wall in hopes of never returning to the internetz again. Everything that you can do "IRL" with your own browser can all be emulated using PHP cURL or libCURL in Python. You just need to do more cURLS to get buff. Then you will see what I mean. :)

  $url = "http://www.google.com/search?q=".$strSearch."&hl=en&start=0&sa=N";
  $ch = curl_init();
  curl_setopt($ch, CURLOPT_REFERER, 'http://www.example.com/1');
  curl_setopt($ch, CURLOPT_HEADER, 0);
  curl_setopt($ch, CURLOPT_VERBOSE, 0);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible;)");
  curl_setopt($ch, CURLOPT_URL, urlencode($url));
  $response = curl_exec($ch);
  curl_close($ch);

how to insert date and time in oracle?

You can use

insert into table_name
(date_field)
values
(TO_DATE('2003/05/03 21:02:44', 'yyyy/mm/dd hh24:mi:ss'));

Hope it helps.

POST request with JSON body

You need to use the cURL library to send this request.

<?php
// Your ID and token
$blogID = '8070105920543249955';
$authToken = 'OAuth 2.0 token here';

// The data to send to the API
$postData = array(
    'kind' => 'blogger#post',
    'blog' => array('id' => $blogID),
    'title' => 'A new post',
    'content' => 'With <b>exciting</b> content...'
);

// Setup cURL
$ch = curl_init('https://www.googleapis.com/blogger/v3/blogs/'.$blogID.'/posts/');
curl_setopt_array($ch, array(
    CURLOPT_POST => TRUE,
    CURLOPT_RETURNTRANSFER => TRUE,
    CURLOPT_HTTPHEADER => array(
        'Authorization: '.$authToken,
        'Content-Type: application/json'
    ),
    CURLOPT_POSTFIELDS => json_encode($postData)
));

// Send the request
$response = curl_exec($ch);

// Check for errors
if($response === FALSE){
    die(curl_error($ch));
}

// Decode the response
$responseData = json_decode($response, TRUE);

// Close the cURL handler
curl_close($ch);

// Print the date from the response
echo $responseData['published'];

If, for some reason, you can't/don't want to use cURL, you can do this:

<?php
// Your ID and token
$blogID = '8070105920543249955';
$authToken = 'OAuth 2.0 token here';

// The data to send to the API
$postData = array(
    'kind' => 'blogger#post',
    'blog' => array('id' => $blogID),
    'title' => 'A new post',
    'content' => 'With <b>exciting</b> content...'
);

// Create the context for the request
$context = stream_context_create(array(
    'http' => array(
        // http://www.php.net/manual/en/context.http.php
        'method' => 'POST',
        'header' => "Authorization: {$authToken}\r\n".
            "Content-Type: application/json\r\n",
        'content' => json_encode($postData)
    )
));

// Send the request
$response = file_get_contents('https://www.googleapis.com/blogger/v3/blogs/'.$blogID.'/posts/', FALSE, $context);

// Check for errors
if($response === FALSE){
    die('Error');
}

// Decode the response
$responseData = json_decode($response, TRUE);

// Print the date from the response
echo $responseData['published'];

Swift programmatically navigate to another view controller/scene

All other answers sounds good, I would like to cover my case, where I had to make an animated LaunchScreen, then after 3 to 4 seconds of animation the next task was to move to Home screen. I tried segues, but that created problem for destination view. So at the end I accessed AppDelegates's Window property and I assigned a new NavigationController screen to it,

let storyboard = UIStoryboard(name: "Main", bundle: nil)
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let homeVC = storyboard.instantiateViewController(withIdentifier: "HomePageViewController") as! HomePageViewController

//Below's navigationController is useful if u want NavigationController in the destination View
let navigationController = UINavigationController(rootViewController: homeVC)
appDelegate.window!.rootViewController = navigationController

If incase, u don't want navigationController in the destination view then just assign as,

let storyboard = UIStoryboard(name: "Main", bundle: nil)
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let homeVC = storyboard.instantiateViewController(withIdentifier: "HomePageViewController") as! HomePageViewController
appDelegate.window!.rootViewController = homeVC

How do servlets work? Instantiation, sessions, shared variables and multithreading

The Servlet Specification JSR-315 clearly defines the web container behavior in the service (and doGet, doPost, doPut etc.) methods (2.3.3.1 Multithreading Issues, Page 9):

A servlet container may send concurrent requests through the service method of the servlet. To handle the requests, the Servlet Developer must make adequate provisions for concurrent processing with multiple threads in the service method.

Although it is not recommended, an alternative for the Developer is to implement the SingleThreadModel interface which requires the container to guarantee that there is only one request thread at a time in the service method. A servlet container may satisfy this requirement by serializing requests on a servlet, or by maintaining a pool of servlet instances. If the servlet is part of a Web application that has been marked as distributable, the container may maintain a pool of servlet instances in each JVM that the application is distributed across.

For servlets not implementing the SingleThreadModel interface, if the service method (or methods such as doGet or doPost which are dispatched to the service method of the HttpServlet abstract class) has been defined with the synchronized keyword, the servlet container cannot use the instance pool approach, but must serialize requests through it. It is strongly recommended that Developers not synchronize the service method (or methods dispatched to it) in these circumstances because of detrimental effects on performance

Google OAuth 2 authorization - Error: redirect_uri_mismatch

Make sure to check the protocol "http://" or "https://" as google checks protocol as well. Better to add both URL in the list.

How can I programmatically freeze the top row of an Excel worksheet in Excel 2007 VBA?

To expand this question into the realm of use outside of Excel s own VBA, the ActiveWindow property must be addressed as a child of the Excel.Application object.

Example for creating an Excel workbook from Access:

Using the Excel.Application object in another Office application's VBA project will require you to add Microsoft Excel 15.0 Object library (or equivalent for your own version).

Option Explicit

Sub xls_Build__Report()
    Dim xlApp As Excel.Application, ws As Worksheet, wb As Workbook
    Dim fn As String

    Set xlApp = CreateObject("Excel.Application")
    xlApp.DisplayAlerts = False
    xlApp.Visible = True

    Set wb = xlApp.Workbooks.Add
    With wb
        .Sheets(1).Name = "Report"
        With .Sheets("Report")

            'report generation here

        End With

        'This is where the Freeze Pane is dealt with
        'Freezes top row
        With xlApp.ActiveWindow
            .SplitColumn = 0
            .SplitRow = 1
            .FreezePanes = True
        End With

        fn = CurrentProject.Path & "\Reports\Report_" & Format(Date, "yyyymmdd") & ".xlsx"
        If CBool(Len(Dir(fn, vbNormal))) Then Kill fn
        .SaveAs FileName:=fn, FileFormat:=xlOpenXMLWorkbook
    End With

Close_and_Quit:
    wb.Close False
    xlApp.Quit
End Sub

The core process is really just a reiteration of previously submitted answers but I thought it was important to demonstrate how to deal with ActiveWindow when you are not within Excel's own VBA. While the code here is VBA, it should be directly transcribable to other languages and platforms.

Validate SSL certificates with Python

Jython DOES carry out certificate verification by default, so using standard library modules, e.g. httplib.HTTPSConnection, etc, with jython will verify certificates and give exceptions for failures, i.e. mismatched identities, expired certs, etc.

In fact, you have to do some extra work to get jython to behave like cpython, i.e. to get jython to NOT verify certs.

I have written a blog post on how to disable certificate checking on jython, because it can be useful in testing phases, etc.

Installing an all-trusting security provider on java and jython.
http://jython.xhaus.com/installing-an-all-trusting-security-provider-on-java-and-jython/

Overloading operators in typedef structs (c++)

try this:

struct Pos{
    int x;
    int y;

    inline Pos& operator=(const Pos& other){
        x=other.x;
        y=other.y;
        return *this;
    }

    inline Pos operator+(const Pos& other) const {
        Pos res {x+other.x,y+other.y};
        return res;
    }

    const inline bool operator==(const Pos& other) const {
        return (x==other.x and y == other.y);
    }
 };  

Best way to convert text files between character sets?

My favorite tool for this is Jedit (a java based text editor) which has two very convenient features :

  • One which enables the user to reload a text with a different encoding (and, as such, to control visually the result)
  • Another one which enables the user to explicitly choose the encoding (and end of line char) before saving

How can I do width = 100% - 100px in CSS?

CSS can not be used to animation, or any style modification on events.

The only way is to use a javascript function, which will return the width of a given element, then, subtract 100px to it, and set the new width size.

Assuming you are using jQuery, you could do something like that:

oldWidth = $('#yourElem').width();
$('#yourElem').width(oldWidth-100);

And with native javascript:

oldWidth = document.getElementById('yourElem').clientWidth;
document.getElementById('yourElem').style.width = oldWidth-100+'px';

We assume that you have a css style set with 100%;

Android. Fragment getActivity() sometimes returns null

It seems that I found a solution to my problem. Very good explanations are given here and here. Here is my example:

pulic class MyActivity extends FragmentActivity{

private ViewPager pager; 
private TitlePageIndicator indicator;
private TabsAdapter adapter;
private Bundle savedInstanceState;

 @Override
public void onCreate(Bundle savedInstanceState) {

    .... 
    this.savedInstanceState = savedInstanceState;
    pager = (ViewPager) findViewById(R.id.pager);;
    indicator = (TitlePageIndicator) findViewById(R.id.indicator);
    adapter = new TabsAdapter(getSupportFragmentManager(), false);

    if (savedInstanceState == null){    
        adapter.addFragment(new FirstFragment());
        adapter.addFragment(new SecondFragment());
    }else{
        Integer  count  = savedInstanceState.getInt("tabsCount");
        String[] titles = savedInstanceState.getStringArray("titles");
        for (int i = 0; i < count; i++){
            adapter.addFragment(getFragment(i), titles[i]);
        }
    }


    indicator.notifyDataSetChanged();
    adapter.notifyDataSetChanged();

    // push first task
    FirstTask firstTask = new FirstTask(MyActivity.this);
    // set first fragment as listener
    firstTask.setTaskListener((TaskListener) getFragment(0));
    firstTask.execute();

}

private Fragment getFragment(int position){
     return savedInstanceState == null ? adapter.getItem(position) : getSupportFragmentManager().findFragmentByTag(getFragmentTag(position));
}

private String getFragmentTag(int position) {
    return "android:switcher:" + R.id.pager + ":" + position;
}

 @Override
protected void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    outState.putInt("tabsCount",      adapter.getCount());
    outState.putStringArray("titles", adapter.getTitles().toArray(new String[0]));
}

 indicator.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
        @Override
        public void onPageSelected(int position) {
            Fragment currentFragment = adapter.getItem(position);
            ((Taskable) currentFragment).executeTask();
        }

        @Override
        public void onPageScrolled(int i, float v, int i1) {}

        @Override
        public void onPageScrollStateChanged(int i) {}
 });

The main idea in this code is that, while running your application normally, you create new fragments and pass them to the adapter. When you are resuming your application fragment manager already has this fragment's instance and you need to get it from fragment manager and pass it to the adapter.

UPDATE

Also, it is a good practice when using fragments to check isAdded before getActivity() is called. This helps avoid a null pointer exception when the fragment is detached from the activity. For example, an activity could contain a fragment that pushes an async task. When the task is finished, the onTaskComplete listener is called.

@Override
public void onTaskComplete(List<Feed> result) {

    progress.setVisibility(View.GONE);
    progress.setIndeterminate(false);
    list.setVisibility(View.VISIBLE);

    if (isAdded()) {

        adapter = new FeedAdapter(getActivity(), R.layout.feed_item, result);
        list.setAdapter(adapter);
        adapter.notifyDataSetChanged();
    }

}

If we open the fragment, push a task, and then quickly press back to return to a previous activity, when the task is finished, it will try to access the activity in onPostExecute() by calling the getActivity() method. If the activity is already detached and this check is not there:

if (isAdded()) 

then the application crashes.

Adding/removing items from a JavaScript object with jQuery

That's not JSON at all, it's just Javascript objects. JSON is a text representation of data, that uses a subset of the Javascript syntax.

The reason that you can't find any information about manipulating JSON using jQuery is because jQuery has nothing that can do that, and it's generally not done at all. You manipulate the data in the form of Javascript objects, and then turn it into a JSON string if that is what you need. (jQuery does have methods for the conversion, though.)

What you have is simply an object that contains an array, so you can use all the knowledge that you already have. Just use data.items to access the array.

For example, to add another item to the array using dynamic values:

// The values to put in the item
var id = 7;
var name = "The usual suspects";
var type = "crime";
// Create the item using the values
var item = { id: id, name: name, type: type };
// Add the item to the array
data.items.push(item);

Can't open file 'svn/repo/db/txn-current-lock': Permission denied

It's permission problem. It is not "classic" read/write permissions of apache user, but selinux one.

Apache cannot write to files labeled as httpd_sys_content_t they can be only read by apache.

You have 2 possibilities:

  1. label svn repository files as httpd_sys_content_rw_t:

    chcon -R -t httpd_sys_content_rw_t /path/to/your/svn/repo
    
  2. set selinux boolean httpd_unified --> on

    setsebool -P httpd_unified=1
    

I prefer 2nd possibility. You can play also with other selinux booleans connected with httpd:

getsebool -a | grep httpd

Is it possible to use jQuery .on and hover?

I'm not sure what the rest of your Javascript looks like, so I won't be able to tell if there is any interference. But .hover() works just fine as an event with .on().

$("#foo").on("hover", function() {
  // disco
});

If you want to be able to utilize its events, use the returned object from the event:

$("#foo").on("hover", function(e) {
  if(e.type == "mouseenter") {
    console.log("over");
  }
  else if (e.type == "mouseleave") {
    console.log("out");
  }
});

http://jsfiddle.net/hmUPP/2/

How do I look inside a Python object?

Python has a strong set of introspection features.

Take a look at the following built-in functions:

type() and dir() are particularly useful for inspecting the type of an object and its set of attributes, respectively.

shorthand c++ if else statement

The basic syntax for using ternary operator is like this:

(condition) ? (if_true) : (if_false)

For you case it is like this:

number < 0 ? bigInt.sign = 0 : bigInt.sign = 1;

Reverse a string in Python

original = "string"

rev_index = original[::-1]
rev_func = list(reversed(list(original))) #nsfw

print(original)
print(rev_index)
print(''.join(rev_func))

Combine two tables that have no common fields

why don't you use simple approach

    SELECT distinct *
    FROM 
    SUPPLIER full join 
    CUSTOMER on (
        CUSTOMER.OID = SUPPLIER.OID
    )

It gives you all columns from both tables and returns all records from customer and supplier if Customer has 3 records and supplier has 2 then supplier'll show NULL in all columns

Get first element in PHP stdObject

Update PHP 7.4

Curly brace access syntax is deprecated since PHP 7.4

Update 2019

Moving on to the best practices of OOPS, @MrTrick's answer must be marked as correct, although my answer provides a hacked solution its not the best method.

Simply iterate its using {}

Example:

$videos{0}->id

This way your object is not destroyed and you can easily iterate through object.

For PHP 5.6 and below use this

$videos{0}['id']

Both array() and the stdClass objects can be accessed using the current() key() next() prev() reset() end() functions.

So, if your object looks like

object(stdClass)#19 (3) {
  [0]=>
  object(stdClass)#20 (22) {
    ["id"]=>
    string(1) "123"
  etc...

Then you can just do;

$id = reset($obj)->id; //Gets the 'id' attr of the first entry in the object

If you need the key for some reason, you can do;

reset($obj); //Ensure that we're at the first element
$key = key($obj);

Hope that works for you. :-) No errors, even in super-strict mode, on PHP 5.4


2022 Update:
After PHP 7.4, using current(), end(), etc functions on objects is deprecated.

In newer versions of PHP, use the ArrayIterator class:

$objIterator = new ArrayIterator($obj);

$id = $objIterator->current()->id; // Gets the 'id' attr of the first entry in the object

$key = $objIterator->key(); // and gets the key

Can comments be used in JSON?

The practical answer for Visual Studio Code users in 2019 is to use the 'jsonc' extension.

It is practical, because that is the extension recognized by Visual Studio Code to indicate "JSON with comments". Please let me know about other editors/IDEs in the comments below.

It would be nice if Visual Studio Code and other editors would add native support for JSON5 as well, but for now Visual Studio Code only includes support for 'jsonc'.

(I searched through all the answers before posting this and none mention 'jsonc'.)

Tomcat 8 is not able to handle get request with '|' in query parameters?

The parameter tomcat.util.http.parser.HttpParser.requestTargetAllow is deprecated since Tomcat 8.5: tomcat official doc.

You can use relaxedQueryChars / relaxedPathChars in the connectors definition to allow these chars: tomcat official doc.

How do you kill all current connections to a SQL Server 2005 database?

These didn't work for me (SQL2008 Enterprise), I also couldn't see any running processes or users connected to the DB. Restarting the server (Right click on Sql Server in Management Studio and pick Restart) allowed me to restore the DB.

Java, List only subdirectories from a directory, not files

Here is solution for my code. I just did a litlle change from first answer. This will list all folders only in desired directory line by line:

try {
            File file = new File("D:\\admir\\MyBookLibrary");
            String[] directories = file.list(new FilenameFilter() {
              @Override
              public boolean accept(File current, String name) {
                return new File(current, name).isDirectory();
              }
            });
            for(int i = 0;i < directories.length;i++) {
                if(directories[i] != null) {
                    System.out.println(Arrays.asList(directories[i]));

                }
            }
        }catch(Exception e) {
            System.err.println("Error!");
        }

Vertical Menu in Bootstrap

here is vertical menu base on Bootstrap http://www.okvee.net/articles/okvee-bootstrap-sidebar-menu it is also support responsive design.

Delete last char of string

What about doing it this way

strgroupids = string.Join( ",", groupIds );

A lot cleaner.

It will append all elements inside groupIds with a ',' between each, but it will not put a ',' at the end.

How to remove class from all elements jquery

This just removes the highlight class from everything that has the edgetoedge class:

$(".edgetoedge").removeClass("highlight");

I think you want this:

$(".edgetoedge .highlight").removeClass("highlight");

The .edgetoedge .highlight selector will choose everything that is a child of something with the edgetoedge class and has the highlight class.

NSAttributedString add text alignment

I was searching for the same issue and was able to center align the text in a NSAttributedString this way:

NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc]init] ;
[paragraphStyle setAlignment:NSTextAlignmentCenter];

NSMutableAttributedString *attribString = [[NSMutableAttributedString alloc]initWithString:string];
[attribString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, [string length])];

JPA mapping: "QuerySyntaxException: foobar is not mapped..."

JPQL mostly is case-insensitive. One of the things that is case-sensitive is Java entity names. Change your query to:

"SELECT r FROM FooBar r"

Remove the last line from a file in Bash

I had trouble with all the answers here because I was working with a HUGE file (~300Gb) and none of the solutions scaled. Here's my solution:

dd if=/dev/null of=<filename> bs=1 seek=$(echo $(stat --format=%s <filename> ) - $( tail -n1 <filename> | wc -c) | bc )

In words: Find out the length of the file you want to end up with (length of file minus length of length of its last line, using bc) and, set that position to be the end of the file (by dding one byte of /dev/null onto it).

This is fast because tail starts reading from the end, and dd will overwrite the file in place rather than copy (and parse) every line of the file, which is what the other solutions do.

NOTE: This removes the line from the file in place! Make a backup or test on a dummy file before trying it out on your own file!

Convert SQL Server result set into string

This one works with NULL Values in Table and doesn't require substring operation at the end. COALESCE is not really well working with NULL values in table (if they will be there).

DECLARE @results VARCHAR(1000) = '' 
SELECT @results = @results + 
           ISNULL(CASE WHEN LEN(@results) = 0 THEN '' ELSE ',' END + [StudentId], '')
FROM Student WHERE condition = xyz

select @results

Strict Standards: Only variables should be assigned by reference PHP 5.4

It's because you're trying to assign an object by reference. Remove the ampersand and your script should work as intended.

Push item to associative array in PHP

If $new_input may contain more than just a 'name' element you may want to use array_merge.

$new_input = array('name'=>array(), 'details'=>array());
$new_input['name'] = array('type'=>'text', 'label'=>'First name'...);
$options['inputs'] = array_merge($options['inputs'], $new_input);

Tools to search for strings inside files without indexing

I'm a fan of the Find-In-Files dialog in Notepad++. Bonus: It's free.

enter image description here

How to set maximum height for table-cell?

This is what you want:

td {
   max-height: whatever;
   max-width: whatever;
   overflow: hidden;
}

What does the question mark and the colon (?: ternary operator) mean in objective-c?

It is ternary operator, like an if/else statement.

if(a > b) {
what to do;
}
else {
what to do;
}

In ternary operator it is like that: condition ? what to do if condition is true : what to do if it is false;

(a > b) ? what to do if true : what to do if false;

How to extract URL parameters from a URL with Ruby or Rails?

In your Controller, you should be able to access a dictionary (hash) called params. So, if you know what the names of each query parameter is, then just do params[:param1] to access it... If you don't know what the names of the parameters are, you could traverse the dictionary and get the keys.

Some simple examples here.

How to get the full path of running process?

Here is a reliable solution that works with both 32bit and 64bit applications.

Add these references:

using System.Diagnostics;

using System.Management;

Add this method to your project:

public static string GetProcessPath(int processId)
{
    string MethodResult = "";
    try
    {
        string Query = "SELECT ExecutablePath FROM Win32_Process WHERE ProcessId = " + processId;

        using (ManagementObjectSearcher mos = new ManagementObjectSearcher(Query))
        {
            using (ManagementObjectCollection moc = mos.Get())
            {
                string ExecutablePath = (from mo in moc.Cast<ManagementObject>() select mo["ExecutablePath"]).First().ToString();

                MethodResult = ExecutablePath;

            }

        }

    }
    catch //(Exception ex)
    {
        //ex.HandleException();
    }
    return MethodResult;
}

Now use it like so:

int RootProcessId = Process.GetCurrentProcess().Id;

GetProcessPath(RootProcessId);

Notice that if you know the id of the process, then this method will return the corresponding ExecutePath.

Extra, for those interested:

Process.GetProcesses() 

...will give you an array of all the currently running processes, and...

Process.GetCurrentProcess()

...will give you the current process, along with their information e.g. Id, etc. and also limited control e.g. Kill, etc.*

How to overcome "'aclocal-1.15' is missing on your system" warning?

The whole point of Autotools is to provide an arcane M4-macro-based language which ultimately compiles to a shell script called ./configure. You can ship this compiled shell script with the source code and that script should do everything to detect the environment and prepare the program for building. Autotools should only be required by someone who wants to tweak the tests and refresh that shell script.

It defeats the point of Autotools if GNU This and GNU That has to be installed on the system for it to work. Originally, it was invented to simplify the porting of programs to various Unix systems, which could not be counted on to have anything on them. Even the constructs used by the generated shell code in ./configure had to be very carefully selected to make sure they would work on every broken old shell just about everywhere.

The problem you're running into is due to some broken Makefile steps invented by people who simply don't understand what Autotools is for and the role of the final ./configure script.

As a workaround, you can go into the Makefile and make some changes to get this out of the way. As an example, I'm building the Git head of GNU Awk and running into this same problem. I applied this patch to Makefile.in, however, and I can sucessfully make gawk:

diff --git a/Makefile.in b/Makefile.in

index 5585046..b8b8588 100644
--- a/Makefile.in
+++ b/Makefile.in
@@ -312,12 +312,12 @@ distcleancheck_listfiles = find . -type f -print

 # Directory for gawk's data files. Automake supplies datadir.
 pkgdatadir = $(datadir)/awk
-ACLOCAL = @ACLOCAL@
+ACLOCAL = true
 AMTAR = @AMTAR@
 AM_DEFAULT_VERBOSITY = @AM_DEFAULT_VERBOSITY@
-AUTOCONF = @AUTOCONF@
-AUTOHEADER = @AUTOHEADER@
-AUTOMAKE = @AUTOMAKE@
+AUTOCONF = true
+AUTOHEADER = true
+AUTOMAKE = true
 AWK = @AWK@
 CC = @CC@
 CCDEPMODE = @CCDEPMODE@

Basically, I changed things so that the harmless true shell command is substituted for all the Auto-stuff programs.

The actual build steps for Gawk don't need the Auto-stuff! It's only involved in some rules that get invoked if parts of the Auto-stuff have changed and need to be re-processed. However, the Makefile is structured in such a way that it fails if the tools aren't present.

Before the above patch:

$ ./configure
[...]
$ make gawk
CDPATH="${ZSH_VERSION+.}:" && cd . && /bin/bash /home/kaz/gawk/missing aclocal-1.15 -I m4
/home/kaz/gawk/missing: line 81: aclocal-1.15: command not found
WARNING: 'aclocal-1.15' is missing on your system.
         You should only need it if you modified 'acinclude.m4' or
         'configure.ac' or m4 files included by 'configure.ac'.
         The 'aclocal' program is part of the GNU Automake package:
         <http://www.gnu.org/software/automake>
         It also requires GNU Autoconf, GNU m4 and Perl in order to run:
         <http://www.gnu.org/software/autoconf>
         <http://www.gnu.org/software/m4/>
         <http://www.perl.org/>
make: *** [aclocal.m4] Error 127

After the patch:

$ ./configure
[...]
$ make gawk
CDPATH="${ZSH_VERSION+.}:" && cd . && true -I m4
CDPATH="${ZSH_VERSION+.}:" && cd . && true
gcc -std=gnu99 -DDEFPATH='".:/usr/local/share/awk"' -DDEFLIBPATH="\"/usr/local/lib/gawk\"" -DSHLIBEXT="\"so"\" -DHAVE_CONFIG_H -DGAWK -DLOCALEDIR='"/usr/local/share/locale"' -I.     -g -O2 -DNDEBUG -MT array.o -MD -MP -MF .deps/array.Tpo -c -o array.o array.c 
[...]
gcc -std=gnu99  -g -O2 -DNDEBUG  -Wl,-export-dynamic -o gawk array.o awkgram.o builtin.o cint_array.o command.o debug.o dfa.o eval.o ext.o field.o floatcomp.o gawkapi.o gawkmisc.o getopt.o getopt1.o int_array.o io.o main.o mpfr.o msg.o node.o profile.o random.o re.o regex.o replace.o str_array.o symbol.o version.o      -ldl -lm
$ ./gawk --version
GNU Awk 4.1.60, API: 1.2
Copyright (C) 1989, 1991-2015 Free Software Foundation.
[...]

There we go. As you can see, the CDPATH= command lines there are where the Auto-stuff was being invoked, where you see the true commands. These report successful termination, and so it just falls through that junk to do the darned build, which is perfectly configured.

I did make gawk because there are some subdirectories that get built which fail; the trick has to be repeated for their respective Makefiles.

If you're running into this kind of thing with a pristine, official tarball of the program from its developers, then complain. It should just unpack, ./configure and make without you having to patch anything or install any Automake or Autoconf materials.

Ideally, a pull of their Git head should also behave that way.

Sorting JSON by values

Solution working with different types and with upper and lower cases.
For example, without the toLowerCase statement, "Goodyear" will come before "doe" with an ascending sort. Run the code snippet at the bottom of my answer to view the different behaviors.

JSON DATA:

var people = [
{
    "f_name" : "john",
    "l_name" : "doe", // lower case
    "sequence": 0 // int
},
{
    "f_name" : "michael",
    "l_name" : "Goodyear", // upper case
    "sequence" : 1 // int
}];

JSON Sort Function:

function sortJson(element, prop, propType, asc) {
  switch (propType) {
    case "int":
      element = element.sort(function (a, b) {
        if (asc) {
          return (parseInt(a[prop]) > parseInt(b[prop])) ? 1 : ((parseInt(a[prop]) < parseInt(b[prop])) ? -1 : 0);
        } else {
          return (parseInt(b[prop]) > parseInt(a[prop])) ? 1 : ((parseInt(b[prop]) < parseInt(a[prop])) ? -1 : 0);
        }
      });
      break;
    default:
      element = element.sort(function (a, b) {
        if (asc) {
          return (a[prop].toLowerCase() > b[prop].toLowerCase()) ? 1 : ((a[prop].toLowerCase() < b[prop].toLowerCase()) ? -1 : 0);
        } else {
          return (b[prop].toLowerCase() > a[prop].toLowerCase()) ? 1 : ((b[prop].toLowerCase() < a[prop].toLowerCase()) ? -1 : 0);
        }
      });
  }
}

Usage:

sortJson(people , "l_name", "string", true);
sortJson(people , "sequence", "int", true);

_x000D_
_x000D_
var people = [{_x000D_
  "f_name": "john",_x000D_
  "l_name": "doe",_x000D_
  "sequence": 0_x000D_
}, {_x000D_
  "f_name": "michael",_x000D_
  "l_name": "Goodyear",_x000D_
  "sequence": 1_x000D_
}, {_x000D_
  "f_name": "bill",_x000D_
  "l_name": "Johnson",_x000D_
  "sequence": 4_x000D_
}, {_x000D_
  "f_name": "will",_x000D_
  "l_name": "malone",_x000D_
  "sequence": 2_x000D_
}, {_x000D_
  "f_name": "tim",_x000D_
  "l_name": "Allen",_x000D_
  "sequence": 3_x000D_
}];_x000D_
_x000D_
function sortJsonLcase(element, prop, asc) {_x000D_
  element = element.sort(function(a, b) {_x000D_
    if (asc) {_x000D_
      return (a[prop] > b[prop]) ? 1 : ((a[prop] < b[prop]) ? -1 : 0);_x000D_
    } else {_x000D_
      return (b[prop] > a[prop]) ? 1 : ((b[prop] < a[prop]) ? -1 : 0);_x000D_
    }_x000D_
  });_x000D_
}_x000D_
_x000D_
function sortJson(element, prop, propType, asc) {_x000D_
  switch (propType) {_x000D_
    case "int":_x000D_
      element = element.sort(function(a, b) {_x000D_
        if (asc) {_x000D_
          return (parseInt(a[prop]) > parseInt(b[prop])) ? 1 : ((parseInt(a[prop]) < parseInt(b[prop])) ? -1 : 0);_x000D_
        } else {_x000D_
          return (parseInt(b[prop]) > parseInt(a[prop])) ? 1 : ((parseInt(b[prop]) < parseInt(a[prop])) ? -1 : 0);_x000D_
        }_x000D_
      });_x000D_
      break;_x000D_
    default:_x000D_
      element = element.sort(function(a, b) {_x000D_
        if (asc) {_x000D_
          return (a[prop].toLowerCase() > b[prop].toLowerCase()) ? 1 : ((a[prop].toLowerCase() < b[prop].toLowerCase()) ? -1 : 0);_x000D_
        } else {_x000D_
          return (b[prop].toLowerCase() > a[prop].toLowerCase()) ? 1 : ((b[prop].toLowerCase() < a[prop].toLowerCase()) ? -1 : 0);_x000D_
        }_x000D_
      });_x000D_
  }_x000D_
}_x000D_
_x000D_
function sortJsonString() {_x000D_
  sortJson(people, 'l_name', 'string', $("#chkAscString").prop("checked"));_x000D_
  display();_x000D_
}_x000D_
_x000D_
function sortJsonInt() {_x000D_
  sortJson(people, 'sequence', 'int', $("#chkAscInt").prop("checked"));_x000D_
  display();_x000D_
}_x000D_
_x000D_
function sortJsonUL() {_x000D_
  sortJsonLcase(people, 'l_name', $('#chkAsc').prop('checked'));_x000D_
  display();_x000D_
}_x000D_
_x000D_
function display() {_x000D_
  $("#data").empty();_x000D_
  $(people).each(function() {_x000D_
    $("#data").append("<div class='people'>" + this.l_name + "</div><div class='people'>" + this.f_name + "</div><div class='people'>" + this.sequence + "</div><br />");_x000D_
  });_x000D_
}
_x000D_
body {_x000D_
  font-family: Arial;_x000D_
}_x000D_
.people {_x000D_
  display: inline-block;_x000D_
  width: 100px;_x000D_
  border: 1px dotted black;_x000D_
  padding: 5px;_x000D_
  margin: 5px;_x000D_
}_x000D_
.buttons {_x000D_
  border: 1px solid black;_x000D_
  padding: 5px;_x000D_
  margin: 5px;_x000D_
  float: left;_x000D_
  width: 20%;_x000D_
}_x000D_
ul {_x000D_
  margin: 5px 0px;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div class="buttons" style="background-color: rgba(240, 255, 189, 1);">_x000D_
  Sort the JSON array <strong style="color: red;">with</strong> toLowerCase:_x000D_
  <ul>_x000D_
    <li>Type: string</li>_x000D_
    <li>Property: lastname</li>_x000D_
  </ul>_x000D_
  <button onclick="sortJsonString(); return false;">Sort JSON</button>_x000D_
  Asc Sort_x000D_
  <input id="chkAscString" type="checkbox" checked="checked" />_x000D_
</div>_x000D_
<div class="buttons" style="background-color: rgba(255, 214, 215, 1);">_x000D_
  Sort the JSON array <strong style="color: red;">without</strong> toLowerCase:_x000D_
  <ul>_x000D_
    <li>Type: string</li>_x000D_
    <li>Property: lastname</li>_x000D_
  </ul>_x000D_
  <button onclick="sortJsonUL(); return false;">Sort JSON</button>_x000D_
  Asc Sort_x000D_
  <input id="chkAsc" type="checkbox" checked="checked" />_x000D_
</div>_x000D_
<div class="buttons" style="background-color: rgba(240, 255, 189, 1);">_x000D_
  Sort the JSON array:_x000D_
  <ul>_x000D_
    <li>Type: int</li>_x000D_
    <li>Property: sequence</li>_x000D_
  </ul>_x000D_
  <button onclick="sortJsonInt(); return false;">Sort JSON</button>_x000D_
  Asc Sort_x000D_
  <input id="chkAscInt" type="checkbox" checked="checked" />_x000D_
</div>_x000D_
<br />_x000D_
<br />_x000D_
<div id="data" style="float: left; border: 1px solid black; width: 60%; margin: 5px;">Data</div>
_x000D_
_x000D_
_x000D_

Include files from parent or other directory

If your server is not resolving the file from the parent directory using

include '../somefilein_parent.php'

try this (using the parent directory relative to the script):

include __DIR__ . "/../somefilein_parent.php";

Assigning a function to a variable

The syntax

def x():
    print(20)

is basically the same as x = lambda: print(20) (there are some differences under the hood, but for most pratical purposes, the results the same).

The syntax

def y(t):
   return t**2

is basically the same as y= lambda t: t**2. When you define a function, you're creating a variable that has the function as its value. In the first example, you're setting x to be the function lambda: print(20). So x now refers to that function. x() is not the function, it's the call of the function. In python, functions are simply a type of variable, and can generally be used like any other variable. For example:

def power_function(power):
      return  lambda x : x**power
power_function(3)(2)

This returns 8. power_function is a function that returns a function as output. When it's called on 3, it returns a function that cubes the input, so when that function is called on the input 2, it returns 8. You could do cube = power_function(3), and now cube(2) would return 8.

Log4net rolling daily filename with date in the file name

For a RollingLogFileAppender you also need these elements and values:

<rollingStyle value="Date" />
<staticLogFileName value="false" />

An App ID with Identifier '' is not available. Please enter a different string

I had the same problem, when I use Xcode7.3 it. I solved the problem: I created a new profile select Ad Hoc, and then downloaded to Xcode.That‘s OK!

enter image description here

Using PropertyInfo.GetValue()

In your example propertyInfo.GetValue(this, null) should work. Consider altering GetNamesAndTypesAndValues() as follows:

public void GetNamesAndTypesAndValues()
{
  foreach (PropertyInfo propertyInfo in allClassProperties)
  {
    Console.WriteLine("{0} [type = {1}] [value = {2}]",
      propertyInfo.Name,
      propertyInfo.PropertyType,
      propertyInfo.GetValue(this, null));
  }
}

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

The root directory of a web application has a special significance and certain content can be present on in that folder. It can have a special file called as “Global.asax”. ASP.Net framework uses the content in the global.asax and creates a class at runtime which is inherited from HttpApplication. During the lifetime of an application, ASP.NET maintains a pool of Global.asax derived HttpApplication instances. When an application receives an http request, the ASP.Net page framework assigns one of these instances to process that request. That instance is responsible for managing the entire lifetime of the request it is assigned to and the instance can only be reused after the request has been completed when it is returned to the pool. The instance members in Global.asax cannot be used for sharing data across requests but static member can be. Global.asax can contain the event handlers of HttpApplication object and some other important methods which would execute at various points in a web application

iOS 7 status bar back to iOS 6 default style in iPhone app?

I have achieved status bar like iOS 6 in iOS 7.

Set UIViewControllerBasedStatusBarAppearance to NO in info.plist

Pase this code in - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions method

if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 7) {
    [application setStatusBarStyle:UIStatusBarStyleLightContent];
    self.window.clipsToBounds =YES;
    self.window.frame =  CGRectMake(0,20,self.window.frame.size.width,self.window.frame.size.height);

    //Added on 19th Sep 2013
    NSLog(@"%f",self.window.frame.size.height);
    self.window.bounds = CGRectMake(0,0, self.window.frame.size.width, self.window.frame.size.height);
}

It may push down all your views by 20 pixels.To over come that use following code in -(void)viewDidAppear:(BOOL)animated method

if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 7) {
    CGRect frame=self.view.frame;
    if (frame.size.height==[[NSUserDefaults standardUserDefaults] floatForKey:@"windowHeight"])
    {
        frame.size.height-=20;
    }
    self.view.frame=frame;
}

You have to set windowHeight Userdefaults value after window allocation in didFinishLauncing Method like

self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
[[NSUserDefaults standardUserDefaults] setFloat:self.window.frame.size.height forKey:@"windowHeight"];

How to add Google Maps Autocomplete search box?

Just copy and paste the sameple code below.

<!DOCTYPE html>
<html>
    <head>
        <script src="https://maps.googleapis.com/maps/api/jsvv=3.exp&sensor=false&libraries=places"></script>
    </head>
    <body>
        <label for="locationTextField">Location</label>
        <input id="locationTextField" type="text" size="50">

        <script>
            function init() {
                var input = document.getElementById('locationTextField');
                var autocomplete = new google.maps.places.Autocomplete(input);
            }

            google.maps.event.addDomListener(window, 'load', init);
        </script>
    </body>
</html>

Well formatted code can be found from this link. http://jon.kim/how-to-add-google-maps-autocomplete-search-box/

Customize the Authorization HTTP header

Kindly try below on postman :-

In header section example work for me..

Authorization : JWT eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyIkX18iOnsic3RyaWN0TW9kZSI6dHJ1ZSwiZ2V0dGVycyI6e30sIndhc1BvcHVsYXRlZCI6ZmFsc2UsImFjdGl2ZVBhdGhzIjp7InBhdGhzIjp7InBhc3N3b3JkIjoiaW5pdCIsImVtYWlsIjoiaW5pdCIsIl9fdiI6ImluaXQiLCJfaWQiOiJpbml0In0sInN0YXRlcyI6eyJpZ25vcmUiOnt9LCJkZWZhdWx0Ijp7fSwiaW5pdCI6eyJfX3YiOnRydWUsInBhc3N3b3JkIjp0cnVlLCJlbWFpbCI6dHJ1ZSwiX2lkIjp0cnVlfSwibW9kaWZ5Ijp7fSwicmVxdWlyZSI6e319LCJzdGF0ZU5hbWVzIjpbInJlcXVpcmUiLCJtb2RpZnkiLCJpbml0IiwiZGVmYXVsdCIsImlnbm9yZSJdfSwiZW1pdHRlciI6eyJkb21haW4iOm51bGwsIl9ldmVudHMiOnt9LCJfZXZlbnRzQ291bnQiOjAsIl9tYXhMaXN0ZW5lcnMiOjB9fSwiaXNOZXciOmZhbHNlLCJfZG9jIjp7Il9fdiI6MCwicGFzc3dvcmQiOiIkMmEkMTAkdTAybWNnWHFjWVQvdE41MlkzZ2l3dVROd3ZMWW9ZTlFXejlUcThyaDIwR09IMlhHY3haZWUiLCJlbWFpbCI6Im1hZGFuLmRhbGUxQGdtYWlsLmNvbSIsIl9pZCI6IjU5MjEzYzYyYWM2ODZlMGMyNzI2MjgzMiJ9LCJfcHJlcyI6eyIkX19vcmlnaW5hbF9zYXZlIjpbbnVsbCxudWxsLG51bGxdLCIkX19vcmlnaW5hbF92YWxpZGF0ZSI6W251bGxdLCIkX19vcmlnaW5hbF9yZW1vdmUiOltudWxsXX0sIl9wb3N0cyI6eyIkX19vcmlnaW5hbF9zYXZlIjpbXSwiJF9fb3JpZ2luYWxfdmFsaWRhdGUiOltdLCIkX19vcmlnaW5hbF9yZW1vdmUiOltdfSwiaWF0IjoxNDk1MzUwNzA5LCJleHAiOjE0OTUzNjA3ODl9.BkyB0LjKB4FIsCtnM5FcpcBLvKed_j7rCCxZddwiYnU

Reset local repository branch to be just like remote repository HEAD

The only solution that works in all cases that I've seen is to delete and reclone. Maybe there's another way, but obviously this way leaves no chance of old state being left there, so I prefer it. Bash one-liner you can set as a macro if you often mess things up in git:

REPO_PATH=$(pwd) && GIT_URL=$(git config --get remote.origin.url) && cd .. && rm -rf $REPO_PATH && git clone --recursive $GIT_URL $REPO_PATH && cd $REPO_PATH

* assumes your .git files aren't corrupt

How do I compare strings in GoLang?

For the Platform Independent Users or Windows users, what you can do is:

import runtime:

import (
    "runtime"
    "strings"
)

and then trim the string like this:

if runtime.GOOS == "windows" {
  input = strings.TrimRight(input, "\r\n")
} else {
  input = strings.TrimRight(input, "\n")
}

now you can compare it like that:

if strings.Compare(input, "a") == 0 {
  //....yourCode
}

This is a better approach when you're making use of STDIN on multiple platforms.

Explanation

This happens because on windows lines end with "\r\n" which is known as CRLF, but on UNIX lines end with "\n" which is known as LF and that's why we trim "\n" on unix based operating systems while we trim "\r\n" on windows.

parse html string with jquery

I'm not a 100% sure, but won't

$(data)

produce a jquery object with a DOM for that data, not connected anywhere? Or if it's already parsed as a DOM, you could just go $("#myImg", data), or whatever selector suits your needs.

EDIT
Rereading your question it appears your 'data' is already a DOM, which means you could just go (assuming there's only an img in your DOM, otherwise you'll need a more precise selector)

$("img", data).attr ("src")

if you want to access the src-attribute. If your data is just text, it would probably work to do

$("img", $(data)).attr ("src")

Iterating a JavaScript object's properties using jQuery

You can use each for objects too and not just for arrays:

var obj = {
    foo: "bar",
    baz: "quux"
};
jQuery.each(obj, function(name, value) {
    alert(name + ": " + value);
});

Creating a DateTime in a specific Time Zone in c#

I like Jon Skeet's answer, but would like to add one thing. I'm not sure if Jon was expecting the ctor to always be passed in the Local timezone. But I want to use it for cases where it's something other then local.

I'm reading values from a database, and I know what timezone that database is in. So in the ctor, I'll pass in the timezone of the database. But then I would like the value in local time. Jon's LocalTime does not return the original date converted into a local timezone date. It returns the date converted into the original timezone (whatever you had passed into the ctor).

I think these property names clear it up...

public DateTime TimeInOriginalZone { get { return TimeZoneInfo.ConvertTime(utcDateTime, timeZone); } }
public DateTime TimeInLocalZone    { get { return TimeZoneInfo.ConvertTime(utcDateTime, TimeZoneInfo.Local); } }
public DateTime TimeInSpecificZone(TimeZoneInfo tz)
{
    return TimeZoneInfo.ConvertTime(utcDateTime, tz);
}

Javascript: How to generate formatted easy-to-read JSON straight from an object?

JSON.stringify takes more optional arguments.

Try:

 JSON.stringify({a:1,b:2,c:{d:1,e:[1,2]}}, null, 4); // Indented 4 spaces
 JSON.stringify({a:1,b:2,c:{d:1,e:[1,2]}}, null, "\t"); // Indented with tab

From:

How can I beautify JSON programmatically?

Should work in modern browsers, and it is included in json2.js if you need a fallback for browsers that don't support the JSON helper functions. For display purposes, put the output in a <pre> tag to get newlines to show.

What are all the possible values for HTTP "Content-Type" header?

If you are using jaxrs or any other, then there will be a class called mediatype.User interceptor before sending the request and compare it against this.

Remote Procedure call failed with sql server 2008 R2

This error appears to happen when .mof files (Managed Object Format (MOF)) don’t get installed and registered correctly during set-up. To resolve this issue, I executed the following mofcomp command in command prompt to re-register the *.mof files:

mofcomp.exe "C:\Program Files (x86)\Microsoft SQL Server\100\Shared\sqlmgmproviderxpsp2up.mof"

This one worked for me

My prerelease app has been "processing" for over a week in iTunes Connect, what gives?

I got this message from App Store Developer Support (2016-01-02):

Be aware that it can take up to 24 hours for a build to fully process through our system and become available for use. If a build does not finish processing in 24 hours, this can typically be resolved by submitting the build again with a higher build number.

Not much of an answer (nothing about why it can take so long time), but it's the answer Apple is giving us.

iReport not starting using JRE 8

There's another way if you don't want to have older Java versions installed you can do the following:

1) Download the iReport-5.6.0.zip from https://sourceforge.net/projects/ireport/files/iReport/iReport-5.6.0/

2) Download jre-7u67-windows-x64.tar.gz (the one packed in a tar) from https://www.oracle.com/technetwork/java/javase/downloads/java-archive-downloads-javase7-521261.html

3) Extract the iReport and in the extracted folder that contains the bin and etc folders throw in the jre. For example if you unpack twice the jre-7u67-windows-x64.tar.gz you end up with a folder named jre1.7.0_67. Put that folder in the iReport-5.6.0 directory:

enter image description here

and then go into the etc folder and edit the file ireport.conf and add the following line into it:

For Windows jdkhome=".\jre1.7.0_67"

For Linux jdkhome="./jre1.7.0_67"

Note : jre version may change! according to your download of 1.7

enter image description here

now if you run the ireport_w.exe from the bin folder in the iReport directory it should load just fine.

Read file As String

It's very easy if you use Kotlin:

val textFile = File(cacheDir, "/text_file.txt")
val allText = textFile.readText()
println(allText)

From readText() docs:

Gets the entire content of this file as a String using UTF-8 or specified charset. This method is not recommended on huge files. It has an internal limitation of 2 GB file size.

Why isn't my Pandas 'apply' function referencing multiple columns working?

Let's say we want to apply a function add5 to columns 'a' and 'b' of DataFrame df

def add5(x):
    return x+5

df[['a', 'b']].apply(add5)

Asynchronous Requests with Python requests

from threading import Thread

threads=list()

for requestURI in requests:
    t = Thread(target=self.openURL, args=(requestURI,))
    t.start()
    threads.append(t)

for thread in threads:
    thread.join()

...

def openURL(self, requestURI):
    o = urllib2.urlopen(requestURI, timeout = 600)
    o...

Left align and right align within div in Bootstrap

Instead of using pull-right class, it is better to use text-right class in the column, because pull-right creates problems sometimes while resizing the page.

How to check if IsNumeric

I think you need something a bit more generic. Try this:

public static System.Boolean IsNumeric (System.Object Expression)
{
    if(Expression == null || Expression is DateTime)
        return false;

    if(Expression is Int16 || Expression is Int32 || Expression is Int64 || Expression is Decimal || Expression is Single || Expression is Double || Expression is Boolean)
        return true;

    try 
    {
        if(Expression is string)
            Double.Parse(Expression as string);
        else
            Double.Parse(Expression.ToString());
            return true;
        } catch {} // just dismiss errors but return false
        return false;
    }
}

Hope it helps!

Is mongodb running?

I find:

ps -ax | grep mongo

To be a lot more consistent. The value returned can be used to detect how many instances of mongod there are running

Converting 24 hour time to 12 hour time w/ AM & PM using Javascript

You could try this more generic function:

function to12HourFormat(date = (new Date)) {
  return {
    hours: ((date.getHours() + 11) % 12 + 1),
    minutes: date.getMinutes(),
    meridian: (date.getHours() >= 12) ? 'PM' : 'AM',
  };
}

Returns a flexible object format.

https://jsbin.com/vexejanovo/edit

Responsive dropdown navbar with angular-ui bootstrap (done in the correct angular kind of way)

Update 2015-06

Based on antoinepairet's comment/example:

Using uib-collapse attribute provides animations: http://plnkr.co/edit/omyoOxYnCdWJP8ANmTc6?p=preview

<nav class="navbar navbar-default" role="navigation">
    <div class="navbar-header">

        <!-- note the ng-init and ng-click here: -->
        <button type="button" class="navbar-toggle" ng-init="navCollapsed = true" ng-click="navCollapsed = !navCollapsed">
            <span class="sr-only">Toggle navigation</span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
        </button>
        <a class="navbar-brand" href="#">Brand</a>
    </div>

    <div class="collapse navbar-collapse" uib-collapse="navCollapsed">
        <ul class="nav navbar-nav">
        ...
        </ul>
    </div>
</nav>

Ancient..

I see that the question is framed around BS2, but I thought I'd pitch in with a solution for Bootstrap 3 using ng-class solution based on suggestions in ui.bootstrap issue 394:

The only variation from the official bootstrap example is the addition of ng- attributes noted by comments, below:

<nav class="navbar navbar-default" role="navigation">
  <div class="navbar-header">

    <!-- note the ng-init and ng-click here: -->
    <button type="button" class="navbar-toggle" ng-init="navCollapsed = true" ng-click="navCollapsed = !navCollapsed">
      <span class="sr-only">Toggle navigation</span>
      <span class="icon-bar"></span>
      <span class="icon-bar"></span>
      <span class="icon-bar"></span>
    </button>
    <a class="navbar-brand" href="#">Brand</a>
  </div>

  <!-- note the ng-class here -->
  <div class="collapse navbar-collapse" ng-class="{'in':!navCollapsed}">

    <ul class="nav navbar-nav">
    ...

Here is an updated working example: http://plnkr.co/edit/OlCCnbGlYWeO7Nxwfj5G?p=preview (hat tip Lars)

This seems to works for me in simple use cases, but you'll note in the example that the second dropdown is cut off… good luck!

How to update Python?

UPDATE: 2018-07-06

This post is now nearly 5 years old! Python-2.7 will stop receiving official updates from python.org in 2020. Also, Python-3.7 has been released. Check out Python-Future on how to make your Python-2 code compatible with Python-3. For updating conda, the documentation now recommends using conda update --all in each of your conda environments to update all packages and the Python executable for that version. Also, since they changed their name to Anaconda, I don't know if the Windows registry keys are still the same.

UPDATE: 2017-03-24

There have been no updates to Python(x,y) since June of 2015, so I think it's safe to assume it has been abandoned.

UPDATE: 2016-11-11

As @cxw comments below, these answers are for the same bit-versions, and by bit-version I mean 64-bit vs. 32-bit. For example, these answers would apply to updating from 64-bit Python-2.7.10 to 64-bit Python-2.7.11, ie: the same bit-version. While it is possible to install two different bit versions of Python together, it would require some hacking, so I'll save that exercise for the reader. If you don't want to hack, I suggest that if switching bit-versions, remove the other bit-version first.

UPDATES: 2016-05-16
  • Anaconda and MiniConda can be used with an existing Python installation by disabling the options to alter the Windows PATH and Registry. After extraction, create a symlink to conda in your bin or install conda from PyPI. Then create another symlink called conda-activate to activate in the Anaconda/Miniconda root bin folder. Now Anaconda/Miniconda is just like Ruby RVM. Just use conda-activate root to enable Anaconda/Miniconda.
  • Portable Python is no longer being developed or maintained.

TL;DR

  • Using Anaconda or miniconda, then just execute conda update --all to keep each conda environment updated,
  • same major version of official Python (e.g. 2.7.5), just install over old (e.g. 2.7.4),
  • different major version of official Python (e.g. 3.3), install side-by-side with old, set paths/associations to point to dominant (e.g. 2.7), shortcut to other (e.g. in BASH $ ln /c/Python33/python.exe python3).

The answer depends:

  1. If OP has 2.7.x and wants to install newer version of 2.7.x, then

    • if using MSI installer from the official Python website, just install over old version, installer will issue warning that it will remove and replace the older version; looking in "installed programs" in "control panel" before and after confirms that the old version has been replaced by the new version; newer versions of 2.7.x are backwards compatible so this is completely safe and therefore IMHO multiple versions of 2.7.x should never necessary.
    • if building from source, then you should probably build in a fresh, clean directory, and then point your path to the new build once it passes all tests and you are confident that it has been built successfully, but you may wish to keep the old build around because building from source may occasionally have issues. See my guide for building Python x64 on Windows 7 with SDK 7.0.
    • if installing from a distribution such as Python(x,y), see their website. Python(x,y) has been abandoned. I believe that updates can be handled from within Python(x,y) with their package manager, but updates are also included on their website. I could not find a specific reference so perhaps someone else can speak to this. Similar to ActiveState and probably Enthought, Python (x,y) clearly states it is incompatible with other installations of Python:

      It is recommended to uninstall any other Python distribution before installing Python(x,y)

    • Enthought Canopy uses an MSI and will install either into Program Files\Enthought or home\AppData\Local\Enthought\Canopy\App for all users or per user respectively. Newer installations are updated by using the built in update tool. See their documentation.
    • ActiveState also uses an MSI so newer installations can be installed on top of older ones. See their installation notes.

      Other Python 2.7 Installations On Windows, ActivePython 2.7 cannot coexist with other Python 2.7 installations (for example, a Python 2.7 build from python.org). Uninstall any other Python 2.7 installations before installing ActivePython 2.7.

    • Sage recommends that you install it into a virtual machine, and provides a Oracle VirtualBox image file that can be used for this purpose. Upgrades are handled internally by issuing the sage -upgrade command.
    • Anaconda can be updated by using the conda command:

      conda update --all
      

      Anaconda/Miniconda lets users create environments to manage multiple Python versions including Python-2.6, 2.7, 3.3, 3.4 and 3.5. The root Anaconda/Miniconda installations are currently based on either Python-2.7 or Python-3.5.

      Anaconda will likely disrupt any other Python installations. Installation uses MSI installer. [UPDATE: 2016-05-16] Anaconda and Miniconda now use .exe installers and provide options to disable Windows PATH and Registry alterations.

      Therefore Anaconda/Miniconda can be installed without disrupting existing Python installations depending on how it was installed and the options that were selected during installation. If the .exe installer is used and the options to alter Windows PATH and Registry are not disabled, then any previous Python installations will be disabled, but simply uninstalling the Anaconda/Miniconda installation should restore the original Python installation, except maybe the Windows Registry Python\PythonCore keys.

      Anaconda/Miniconda makes the following registry edits regardless of the installation options: HKCU\Software\Python\ContinuumAnalytics\ with the following keys: Help, InstallPath, Modules and PythonPath - official Python registers these keys too, but under Python\PythonCore. Also uninstallation info is registered for Anaconda\Miniconda. Unless you select the "Register with Windows" option during installation, it doesn't create PythonCore, so integrations like Python Tools for Visual Studio do not automatically see Anaconda/Miniconda. If the option to register Anaconda/Miniconda is enabled, then I think your existing Python Windows Registry keys will be altered and uninstallation will probably not restore them.

    • WinPython updates, I think, can be handled through the WinPython Control Panel.
    • PortablePython is no longer being developed. It had no update method. Possibly updates could be unzipped into a fresh directory and then App\lib\site-packages and App\Scripts could be copied to the new installation, but if this didn't work then reinstalling all packages might have been necessary. Use pip list to see what packages were installed and their versions. Some were installed by PortablePython. Use easy_install pip to install pip if it wasn't installed.
  2. If OP has 2.7.x and wants to install a different version, e.g. <=2.6.x or >=3.x.x, then installing different versions side-by-side is fine. You must choose which version of Python (if any) to associate with *.py files and which you want on your path, although you should be able to set up shells with different paths if you use BASH. AFAIK 2.7.x is backwards compatible with 2.6.x, so IMHO side-by-side installs is not necessary, however Python-3.x.x is not backwards compatible, so my recommendation would be to put Python-2.7 on your path and have Python-3 be an optional version by creating a shortcut to its executable called python3 (this is a common setup on Linux). The official Python default install path on Windows is

    • C:\Python33 for 3.3.x (latest 2013-07-29)
    • C:\Python32 for 3.2.x
    • &c.
    • C:\Python27 for 2.7.x (latest 2013-07-29)
    • C:\Python26 for 2.6.x
    • &c.
  3. If OP is not updating Python, but merely updating packages, they may wish to look into virtualenv to keep the different versions of packages specific to their development projects separate. Pip is also a great tool to update packages. If packages use binary installers I usually uninstall the old package before installing the new one.

I hope this clears up any confusion.

Deserialize JSON with C#

Serialization:

// Convert an object to JSON string format
string jsonData = JsonConvert.SerializeObject(obj);

Response.Write(jsonData);

Deserialization::

To deserialize a dynamic object

  string json = @"{
      'Name': 'name',
      'Description': 'des'
    }";

var res = JsonConvert.DeserializeObject< dynamic>(json);

Response.Write(res.Name);

If Browser is Internet Explorer: run an alternative script instead

var browserName=navigator.appName; if (browserName=="Microsoft Internet Explorer") { document.write("Your html for IE") }

Spring @ContextConfiguration how to put the right location for the xml

@RunWith(SpringJUnit4ClassRunner.class)@ContextConfiguration(locations = {"/Beans.xml"}) public class DemoTest{}

Error: No module named psycopg2.extensions

I used the extension after only importing psycopg2:

import psycopg2

...

psycopg2.extensions.AsIs(anap[i])

Slide up/down effect with ng-show and ng-animate

You should use Javascript animations for this - it is not possible in pure CSS, because you can't know the height of any element. Follow the instructions it has for you about javascript animation implementation, and copy slideUp and slideDown from jQuery's source.

How to make join queries using Sequelize on Node.js

While the accepted answer isn't technically wrong, it doesn't answer the original question nor the follow up question in the comments, which was what I came here looking for. But I figured it out, so here goes.

If you want to find all Posts that have Users (and only the ones that have users) where the SQL would look like this:

SELECT * FROM posts INNER JOIN users ON posts.user_id = users.id

Which is semantically the same thing as the OP's original SQL:

SELECT * FROM posts, users WHERE posts.user_id = users.id

then this is what you want:

Posts.findAll({
  include: [{
    model: User,
    required: true
   }]
}).then(posts => {
  /* ... */
});

Setting required to true is the key to producing an inner join. If you want a left outer join (where you get all Posts, regardless of whether there's a user linked) then change required to false, or leave it off since that's the default:

Posts.findAll({
  include: [{
    model: User,
//  required: false
   }]
}).then(posts => {
  /* ... */
});

If you want to find all Posts belonging to users whose birth year is in 1984, you'd want:

Posts.findAll({
  include: [{
    model: User,
    where: {year_birth: 1984}
   }]
}).then(posts => {
  /* ... */
});

Note that required is true by default as soon as you add a where clause in.

If you want all Posts, regardless of whether there's a user attached but if there is a user then only the ones born in 1984, then add the required field back in:

Posts.findAll({
  include: [{
    model: User,
    where: {year_birth: 1984}
    required: false,
   }]
}).then(posts => {
  /* ... */
});

If you want all Posts where the name is "Sunshine" and only if it belongs to a user that was born in 1984, you'd do this:

Posts.findAll({
  where: {name: "Sunshine"},
  include: [{
    model: User,
    where: {year_birth: 1984}
   }]
}).then(posts => {
  /* ... */
});

If you want all Posts where the name is "Sunshine" and only if it belongs to a user that was born in the same year that matches the post_year attribute on the post, you'd do this:

Posts.findAll({
  where: {name: "Sunshine"},
  include: [{
    model: User,
    where: ["year_birth = post_year"]
   }]
}).then(posts => {
  /* ... */
});

I know, it doesn't make sense that somebody would make a post the year they were born, but it's just an example - go with it. :)

I figured this out (mostly) from this doc:

The ORDER BY clause is invalid in views, inline functions, derived tables, subqueries, and common table expressions

You do not need to use ORDER BY in inner query after WHERE clause because you have already used it in ROW_NUMBER() OVER (ORDER BY VRDATE DESC).

SELECT 
    * 
FROM (
    SELECT 
        Stockmain.VRNOA, 
        item.description as item_description, 
        party.name as party_name, 
        stockmain.vrdate, 
        stockdetail.qty, 
        stockdetail.rate, 
        stockdetail.amount, 
        ROW_NUMBER() OVER (ORDER BY VRDATE DESC) AS RowNum  --< ORDER BY
    FROM StockMain 
    INNER JOIN StockDetail 
        ON StockMain.stid = StockDetail.stid 
    INNER JOIN party 
        ON party.party_id = stockmain.party_id 
    INNER JOIN item 
        ON item.item_id = stockdetail.item_id 
    WHERE stockmain.etype='purchase' 
) AS MyDerivedTable
WHERE 
    MyDerivedTable.RowNum BETWEEN 1 and 5 

SQL Server copy all rows from one table into another i.e duplicate table

This will work:

select * into DestinationDatabase.dbo.[TableName1] from (
Select * from sourceDatabase.dbo.[TableName1])Temp

How can I write a regex which matches non greedy?

The ? operand makes match non-greedy. E.g. .* is greedy while .*? isn't. So you can use something like <img.*?> to match the whole tag. Or <img[^>]*>.

But remember that the whole set of HTML can't be actually parsed with regular expressions.

Some dates recognized as dates, some dates not recognized. Why?

I come across this problem when I tried to convert to Australian date format in excel. I split the cell with delimiter and used the following code from split cells then altered the issue areas.

=date(dd,mm,yy)

Make a number a percentage

var percent = Math.floor(100 * number1 / number2 - 100) + ' %';

HTML Display Current date

var currentDate  = new Date(),
    currentDay   = currentDate.getDate() < 10 
                 ? '0' + currentDate.getDate() 
                 : currentDate.getDate(),
    currentMonth = currentDate.getMonth() < 9 
                 ? '0' + (currentDate.getMonth() + 1) 
                 : (currentDate.getMonth() + 1);

document.getElementById("date").innerHTML = currentDay + '/' + currentMonth + '/' +  currentDate.getFullYear();

You can read more about Date object

add elements to object array

I know this is old, but came across it looking for a simpler way, and this is how i do it, just create a new list of the same object and add it to the one you want to use e.g.

Subject[] subjectsList = {new Subject1{....}, new Subject2{....}, new Subject3{....}} 
univStudent.subjects = subjectsList ;

Download an SVN repository?

One the upper left in Google Code it has a link "Checkout"

Click that and you will get a command line suggestion:

Command-line access

Use this command to anonymously check out the latest project source code:

 Non-members may check out a read-only working copy anonymously over HTTP.
svn checkout http://yourfolder.googlecode.com/svn/trunk/ yourfolder-read-only

If you want a subfolder only then add it after trunk

If you are on linux & have SVN installed just CD to the folder where you want it installed first then run the above command - it will download fast

I tried all the other suggestions & this is the only thing that worked, couldnt do it with bazaar or svnDownloader app.

adb shell command to make Android package uninstall dialog appear

While the above answers work but in case you have multiple devices connected to your computer then the following command can be used to remove the app from one of them:

adb -s <device-serial> shell pm uninstall <app-package-name>

If you want to find out the device serial then use the following command:

adb devices -l

This will give you a list of devices attached. The left column shows the device serials.

Left Outer Join using + sign in Oracle 11g

There is some incorrect information in this thread. I copied and pasted the incorrect information:

LEFT OUTER JOIN

SELECT *
FROM A, B
WHERE A.column = B.column(+)

RIGHT OUTER JOIN

SELECT *
FROM A, B
WHERE B.column(+) = A.column

The above is WRONG!!!!! It's reversed. How I determined it's incorrect is from the following book:

Oracle OCP Introduction to Oracle 9i: SQL Exam Guide. Page 115 Table 3-1 has a good summary on this. I could not figure why my converted SQL was not working properly until I went old school and looked in a printed book!

Here is the summary from this book, copied line by line:

Oracle outer Join Syntax:

from tab_a a, tab_b b,                                       
where a.col_1 + = b.col_1                                     

ANSI/ISO Equivalent:

from tab_a a left outer join  
tab_b b on a.col_1 = b.col_1

Notice here that it's the reverse of what is posted above. I suppose it's possible for this book to have errata, however I trust this book more so than what is in this thread. It's an exam guide for crying out loud...

Native query with named parameter fails with "Not all named parameters have been set"

You are calling setProperty instead of setParameter. Change your code to

Query q = em.createNativeQuery("SELECT count(*) FROM mytable where username = :username");
em.setParameter("username", "test");
(int) q.getSingleResult();

and it should work.

docker command not found even though installed with apt-get

sudo apt-get install docker # DO NOT do this

is a different library on ubuntu.

Use sudo apt-get install docker-ce to install the correct docker.

How do I copy SQL Azure database to my local development server?

I think it is a lot easier now.

  1. Launch SQL Management Studio
  2. Right Click on "Databases" and select "Import Data-tier application..."
  3. The wizard will take you through the process of connecting to your Azure account, creating a BACPAC file and creating your database.

Additionally, I use Sql Backup and FTP (https://sqlbackupandftp.com/) to do daily backups to a secure FTP server. I simply pull a recent BACPAC file from there and it import it in the same dialog, which is faster and easier to create a local database.

Weird behavior of the != XPath operator

If $AccountNumber or $Balance is a node-set, then this behavior could easily happen. It's not because and is being treated as or.

For example, if $AccountNumber referred to nodes with the values 12345 and 66 and $Balance referred to nodes with the values 55 and 0, then $AccountNumber != '12345' would be true (because 66 is not equal to 12345) and $Balance != '0' would be true (because 55 is not equal to 0).

I'd suggest trying this instead:

<xsl:when test="not($AccountNumber = '12345' or $Balance = '0')">

$AccountNumber = '12345' or $Balance = '0' will be true any time there is an $AccountNumber with the value 12345 or there is a $Balance with the value 0, and if you apply not() to that, you will get a false result.

How do I find the absolute position of an element using jQuery?

Note that $(element).offset() tells you the position of an element relative to the document. This works great in most circumstances, but in the case of position:fixed you can get unexpected results.

If your document is longer than the viewport and you have scrolled vertically toward the bottom of the document, then your position:fixed element's offset() value will be greater than the expected value by the amount you have scrolled.

If you are looking for a value relative to the viewport (window), rather than the document on a position:fixed element, you can subtract the document's scrollTop() value from the fixed element's offset().top value. Example: $("#el").offset().top - $(document).scrollTop()

If the position:fixed element's offset parent is the document, you want to read parseInt($.css('top')) instead.

How to see query history in SQL Server Management Studio

Query history can be viewed using the system views:

  1. sys.dm_exec_query_stats
  2. sys.dm_exec_sql_text
  3. sys.dm_exec_query_plan

For example, using the following query:

select  top(100)
        creation_time,
        last_execution_time,
        execution_count,
        total_worker_time/1000 as CPU,
        convert(money, (total_worker_time))/(execution_count*1000)as [AvgCPUTime],
        qs.total_elapsed_time/1000 as TotDuration,
        convert(money, (qs.total_elapsed_time))/(execution_count*1000)as [AvgDur],
        total_logical_reads as [Reads],
        total_logical_writes as [Writes],
        total_logical_reads+total_logical_writes as [AggIO],
        convert(money, (total_logical_reads+total_logical_writes)/(execution_count + 0.0)) as [AvgIO],
        [sql_handle],
        plan_handle,
        statement_start_offset,
        statement_end_offset,
        plan_generation_num,
        total_physical_reads,
        convert(money, total_physical_reads/(execution_count + 0.0)) as [AvgIOPhysicalReads],
        convert(money, total_logical_reads/(execution_count + 0.0)) as [AvgIOLogicalReads],
        convert(money, total_logical_writes/(execution_count + 0.0)) as [AvgIOLogicalWrites],
        query_hash,
        query_plan_hash,
        total_rows,
        convert(money, total_rows/(execution_count + 0.0)) as [AvgRows],
        total_dop,
        convert(money, total_dop/(execution_count + 0.0)) as [AvgDop],
        total_grant_kb,
        convert(money, total_grant_kb/(execution_count + 0.0)) as [AvgGrantKb],
        total_used_grant_kb,
        convert(money, total_used_grant_kb/(execution_count + 0.0)) as [AvgUsedGrantKb],
        total_ideal_grant_kb,
        convert(money, total_ideal_grant_kb/(execution_count + 0.0)) as [AvgIdealGrantKb],
        total_reserved_threads,
        convert(money, total_reserved_threads/(execution_count + 0.0)) as [AvgReservedThreads],
        total_used_threads,
        convert(money, total_used_threads/(execution_count + 0.0)) as [AvgUsedThreads],
        case 
            when sql_handle IS NULL then ' '
            else(substring(st.text,(qs.statement_start_offset+2)/2,(
                case
                    when qs.statement_end_offset =-1 then len(convert(nvarchar(MAX),st.text))*2      
                    else qs.statement_end_offset    
                end - qs.statement_start_offset)/2  ))
        end as query_text,
        db_name(st.dbid) as database_name,
        object_schema_name(st.objectid, st.dbid)+'.'+object_name(st.objectid, st.dbid) as [object_name],
        sp.[query_plan]
from sys.dm_exec_query_stats as qs with(readuncommitted)
cross apply sys.dm_exec_sql_text(qs.[sql_handle]) as st
cross apply sys.dm_exec_query_plan(qs.[plan_handle]) as sp
WHERE st.[text] LIKE '%query%'

Current running queries can be seen using the following script:

select ES.[session_id]
      ,ER.[blocking_session_id]
      ,ER.[request_id]
      ,ER.[start_time]
      ,DateDiff(second, ER.[start_time], GetDate()) as [date_diffSec]
      , COALESCE(
                    CAST(NULLIF(ER.[total_elapsed_time] / 1000, 0) as BIGINT)
                   ,CASE WHEN (ES.[status] <> 'running' and isnull(ER.[status], '')  <> 'running') 
                            THEN  DATEDIFF(ss,0,getdate() - nullif(ES.[last_request_end_time], '1900-01-01T00:00:00.000'))
                    END
                ) as [total_time, sec]
      , CAST(NULLIF((CAST(ER.[total_elapsed_time] as BIGINT) - CAST(ER.[wait_time] AS BIGINT)) / 1000, 0 ) as bigint) as [work_time, sec]
      , CASE WHEN (ER.[status] <> 'running' AND ISNULL(ER.[status],'') <> 'running') 
                THEN  DATEDIFF(ss,0,getdate() - nullif(ES.[last_request_end_time], '1900-01-01T00:00:00.000'))
        END as [sleep_time, sec] --????? ??? ? ???
      , NULLIF( CAST((ER.[logical_reads] + ER.[writes]) * 8 / 1024 as numeric(38,2)), 0) as [IO, MB]
      , CASE  ER.transaction_isolation_level
        WHEN 0 THEN 'Unspecified'
        WHEN 1 THEN 'ReadUncommited'
        WHEN 2 THEN 'ReadCommited'
        WHEN 3 THEN 'Repetable'
        WHEN 4 THEN 'Serializable'
        WHEN 5 THEN 'Snapshot'
        END as [transaction_isolation_level_desc]
      ,ER.[status]
      ,ES.[status] as [status_session]
      ,ER.[command]
      ,ER.[percent_complete]
      ,DB_Name(coalesce(ER.[database_id], ES.[database_id])) as [DBName]
      , SUBSTRING(
                    (select top(1) [text] from sys.dm_exec_sql_text(ER.[sql_handle]))
                  , ER.[statement_start_offset]/2+1
                  , (
                        CASE WHEN ((ER.[statement_start_offset]<0) OR (ER.[statement_end_offset]<0))
                                THEN DATALENGTH ((select top(1) [text] from sys.dm_exec_sql_text(ER.[sql_handle])))
                             ELSE ER.[statement_end_offset]
                        END
                        - ER.[statement_start_offset]
                    )/2 +1
                 ) as [CURRENT_REQUEST]
      ,(select top(1) [text] from sys.dm_exec_sql_text(ER.[sql_handle])) as [TSQL]
      ,(select top(1) [objectid] from sys.dm_exec_sql_text(ER.[sql_handle])) as [objectid]
      ,(select top(1) [query_plan] from sys.dm_exec_query_plan(ER.[plan_handle])) as [QueryPlan]
      ,NULL as [event_info]--(select top(1) [event_info] from sys.dm_exec_input_buffer(ES.[session_id], ER.[request_id])) as [event_info]
      ,ER.[wait_type]
      ,ES.[login_time]
      ,ES.[host_name]
      ,ES.[program_name]
      ,cast(ER.[wait_time]/1000 as decimal(18,3)) as [wait_timeSec]
      ,ER.[wait_time]
      ,ER.[last_wait_type]
      ,ER.[wait_resource]
      ,ER.[open_transaction_count]
      ,ER.[open_resultset_count]
      ,ER.[transaction_id]
      ,ER.[context_info]
      ,ER.[estimated_completion_time]
      ,ER.[cpu_time]
      ,ER.[total_elapsed_time]
      ,ER.[scheduler_id]
      ,ER.[task_address]
      ,ER.[reads]
      ,ER.[writes]
      ,ER.[logical_reads]
      ,ER.[text_size]
      ,ER.[language]
      ,ER.[date_format]
      ,ER.[date_first]
      ,ER.[quoted_identifier]
      ,ER.[arithabort]
      ,ER.[ansi_null_dflt_on]
      ,ER.[ansi_defaults]
      ,ER.[ansi_warnings]
      ,ER.[ansi_padding]
      ,ER.[ansi_nulls]
      ,ER.[concat_null_yields_null]
      ,ER.[transaction_isolation_level]
      ,ER.[lock_timeout]
      ,ER.[deadlock_priority]
      ,ER.[row_count]
      ,ER.[prev_error]
      ,ER.[nest_level]
      ,ER.[granted_query_memory]
      ,ER.[executing_managed_code]
      ,ER.[group_id]
      ,ER.[query_hash]
      ,ER.[query_plan_hash]
      ,EC.[most_recent_session_id]
      ,EC.[connect_time]
      ,EC.[net_transport]
      ,EC.[protocol_type]
      ,EC.[protocol_version]
      ,EC.[endpoint_id]
      ,EC.[encrypt_option]
      ,EC.[auth_scheme]
      ,EC.[node_affinity]
      ,EC.[num_reads]
      ,EC.[num_writes]
      ,EC.[last_read]
      ,EC.[last_write]
      ,EC.[net_packet_size]
      ,EC.[client_net_address]
      ,EC.[client_tcp_port]
      ,EC.[local_net_address]
      ,EC.[local_tcp_port]
      ,EC.[parent_connection_id]
      ,EC.[most_recent_sql_handle]
      ,ES.[host_process_id]
      ,ES.[client_version]
      ,ES.[client_interface_name]
      ,ES.[security_id]
      ,ES.[login_name]
      ,ES.[nt_domain]
      ,ES.[nt_user_name]
      ,ES.[memory_usage]
      ,ES.[total_scheduled_time]
      ,ES.[last_request_start_time]
      ,ES.[last_request_end_time]
      ,ES.[is_user_process]
      ,ES.[original_security_id]
      ,ES.[original_login_name]
      ,ES.[last_successful_logon]
      ,ES.[last_unsuccessful_logon]
      ,ES.[unsuccessful_logons]
      ,ES.[authenticating_database_id]
      ,ER.[sql_handle]
      ,ER.[statement_start_offset]
      ,ER.[statement_end_offset]
      ,ER.[plan_handle]
      ,NULL as [dop]--ER.[dop]
      ,coalesce(ER.[database_id], ES.[database_id]) as [database_id]
      ,ER.[user_id]
      ,ER.[connection_id]
from sys.dm_exec_requests ER with(readuncommitted)
right join sys.dm_exec_sessions ES with(readuncommitted)
on ES.session_id = ER.session_id 
left join sys.dm_exec_connections EC  with(readuncommitted)
on EC.session_id = ES.session_id
where ER.[status] in ('suspended', 'running', 'runnable')
or exists (select top(1) 1 from sys.dm_exec_requests as ER0 where ER0.[blocking_session_id]=ES.[session_id])

This request displays all active requests and all those requests that explicitly block active requests.

All these and other useful scripts are implemented as representations in the SRV database, which is distributed freely. For example, the first script came from the view [inf].[vBigQuery], and the second came from view [inf].[vRequests].

There are also various third-party solutions for query history. I use Query Manager from Dbeaver: enter image description here and Query Execution History from SQL Tools, which is embedded in SSMS: enter image description here

How to make php display \t \n as tab and new line instead of characters

You can use HTML,

foreach(...)
echo $data1 . '&nbsp' . $data2 . '&nbsp' . $data3 . '<br/>';

Could not insert new outlet connection: Could not find any information for the class named

For me it worked when on the right tab > Localization, I checked English check box. Initially only Base was checked. After that I had no more problems. Hope this helps!

How to get index using LINQ?

myCars.TakeWhile(car => !myCondition(car)).Count();

It works! Think about it. The index of the first matching item equals the number of (not matching) item before it.

Story time

I too dislike the horrible standard solution you already suggested in your question. Like the accepted answer I went for a plain old loop although with a slight modification:

public static int FindIndex<T>(this IEnumerable<T> items, Predicate<T> predicate) {
    int index = 0;
    foreach (var item in items) {
        if (predicate(item)) break;
        index++;
    }
    return index;
}

Note that it will return the number of items instead of -1 when there is no match. But let's ignore this minor annoyance for now. In fact the horrible standard solution crashes in that case and I consider returning an index that is out-of-bounds superior.

What happens now is ReSharper telling me Loop can be converted into LINQ-expression. While most of the time the feature worsens readability, this time the result was awe-inspiring. So Kudos to the JetBrains.

Analysis

Pros

  • Concise
  • Combinable with other LINQ
  • Avoids newing anonymous objects
  • Only evaluates the enumerable until the predicate matches for the first time

Therefore I consider it optimal in time and space while remaining readable.

Cons

  • Not quite obvious at first
  • Does not return -1 when there is no match

Of course you can always hide it behind an extension method. And what to do best when there is no match heavily depends on the context.

Replace "\\" with "\" in a string in C#

in case someone got stuck with this and none of the answers above worked, below is what worked for me. Hope it helps.

var oldString = "\\r|\\n";

// None of these worked for me
// var newString = oldString(@"\\", @"\");
// var newString = oldString.Replace("\\\\", "\\");
// var newString = oldString.Replace("\\u5b89", "\u5b89");
// var newString = Regex.Replace(oldString , @"\\", @"\");

// This is what worked
var newString = Regex.Unescape(oldString);
// newString is now "\r|\n"

Saving an Object (Data persistence)

You can use anycache to do the job for you. It considers all the details:

  • It uses dill as backend, which extends the python pickle module to handle lambda and all the nice python features.
  • It stores different objects to different files and reloads them properly.
  • Limits cache size
  • Allows cache clearing
  • Allows sharing of objects between multiple runs
  • Allows respect of input files which influence the result

Assuming you have a function myfunc which creates the instance:

from anycache import anycache

class Company(object):
    def __init__(self, name, value):
        self.name = name
        self.value = value

@anycache(cachedir='/path/to/your/cache')    
def myfunc(name, value)
    return Company(name, value)

Anycache calls myfunc at the first time and pickles the result to a file in cachedir using an unique identifier (depending on the function name and its arguments) as filename. On any consecutive run, the pickled object is loaded. If the cachedir is preserved between python runs, the pickled object is taken from the previous python run.

For any further details see the documentation

How to measure height, width and distance of object using camera?

If you think about it, a body XRay scan (at the medical center) too needs this kind of measurement for estimating size of tumors. So they place a 1 Dollar Coin on the body, to do a comparative measurement.

Even newspaper is printed with some marks on the corners.

You need a reference to measure. May be you can get your person to wear a cap which has a few bright green circles. Once you recognize the size of the circle you can comparatively measure the remaining.

Or you can create a transparent 1 inch circle which will superimpose on the face, move the camera toward/away the face, aim your superimposed circle on that bright green circle on the cap. Then on your photo will be as per scale.

SQL Server Text type vs. varchar data type

In SQL server 2005 new datatypes were introduced: varchar(max) and nvarchar(max) They have the advantages of the old text type: they can contain op to 2GB of data, but they also have most of the advantages of varchar and nvarchar. Among these advantages are the ability to use string manipulation functions such as substring().

Also, varchar(max) is stored in the table's (disk/memory) space while the size is below 8Kb. Only when you place more data in the field, it's is stored out of the table's space. Data stored in the table's space is (usually) retrieved quicker.

In short, never use Text, as there is a better alternative: (n)varchar(max). And only use varchar(max) when a regular varchar is not big enough, ie if you expect teh string that you're going to store will exceed 8000 characters.

As was noted, you can use SUBSTRING on the TEXT datatype,but only as long the TEXT fields contains less than 8000 characters.

How to split a comma-separated value to columns

This worked for me

CREATE FUNCTION [dbo].[SplitString](
    @delimited NVARCHAR(MAX),
    @delimiter NVARCHAR(100)
) RETURNS @t TABLE ( val NVARCHAR(MAX))
AS
BEGIN
    DECLARE @xml XML
    SET @xml = N'<t>' + REPLACE(@delimited,@delimiter,'</t><t>') + '</t>'
    INSERT INTO @t(val)
    SELECT  r.value('.','varchar(MAX)') as item
    FROM  @xml.nodes('/t') as records(r)
    RETURN
END

HQL Hibernate INNER JOIN

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;

@Entity
@Table(name="empTable")
public class Employee implements Serializable{
private static final long serialVersionUID = 1L;
private int id;
private String empName;

List<Address> addList=new ArrayList<Address>();


@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name="emp_id")
public int getId() {
    return id;
}
public void setId(int id) {
    this.id = id;
}
public String getEmpName() {
    return empName;
}
public void setEmpName(String empName) {
    this.empName = empName;
}

@OneToMany(mappedBy="employee",cascade=CascadeType.ALL)
public List<Address> getAddList() {
    return addList;
}

public void setAddList(List<Address> addList) {
    this.addList = addList;
}
}

We have two entities Employee and Address with One to Many relationship.

import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;

@Entity
@Table(name="address")
public class Address implements Serializable{

private static final long serialVersionUID = 1L;

private int address_id;
private String address;
Employee employee;

@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
public int getAddress_id() {
    return address_id;
}
public void setAddress_id(int address_id) {
    this.address_id = address_id;
}
public String getAddress() {
    return address;
}
public void setAddress(String address) {
    this.address = address;
}

@ManyToOne
@JoinColumn(name="emp_id")
public Employee getEmployee() {
    return employee;
}
public void setEmployee(Employee employee) {
    this.employee = employee;
}
}

By this way we can implement inner join between two tables

import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;

public class Main {

public static void main(String[] args) {
    saveEmployee();

    retrieveEmployee();

}

private static void saveEmployee() {
    Employee employee=new Employee();
    Employee employee1=new Employee();
    Employee employee2=new Employee();
    Employee employee3=new Employee();

    Address address=new Address();
    Address address1=new Address();
    Address address2=new Address();
    Address address3=new Address();

    address.setAddress("1485,Sector 42 b");
    address1.setAddress("1485,Sector 42 c");
    address2.setAddress("1485,Sector 42 d");
    address3.setAddress("1485,Sector 42 a");

    employee.setEmpName("Varun");
    employee1.setEmpName("Krishan");
    employee2.setEmpName("Aasif");
    employee3.setEmpName("Dut");

    address.setEmployee(employee);
    address1.setEmployee(employee1);
    address2.setEmployee(employee2);
    address3.setEmployee(employee3);

    employee.getAddList().add(address);
    employee1.getAddList().add(address1);
    employee2.getAddList().add(address2);
    employee3.getAddList().add(address3);

    Session session=HibernateUtil.getSessionFactory().openSession();

    session.beginTransaction();

    session.save(employee);
    session.save(employee1);
    session.save(employee2);
    session.save(employee3);
    session.getTransaction().commit();
    session.close();
}

private static void retrieveEmployee() {
    try{

    String sqlQuery="select e from Employee e inner join e.addList";

    Session session=HibernateUtil.getSessionFactory().openSession();

    Query query=session.createQuery(sqlQuery);

    List<Employee> list=query.list();

     list.stream().forEach((p)->{System.out.println(p.getEmpName());});     
    session.close();
    }catch(Exception e){
        e.printStackTrace();
    }
}
}

I have used Java 8 for loop for priting the names. Make sure you have jdk 1.8 with tomcat 8. Also add some more records for better understanding.

 public class HibernateUtil {
 private static SessionFactory sessionFactory ;
 static {
    Configuration configuration = new Configuration();

    configuration.addAnnotatedClass(Employee.class);
    configuration.addAnnotatedClass(Address.class);
                  configuration.setProperty("connection.driver_class","com.mysql.jdbc.Driver");
    configuration.setProperty("hibernate.connection.url", "jdbc:mysql://localhost:3306/hibernate");                                
    configuration.setProperty("hibernate.connection.username", "root");     
    configuration.setProperty("hibernate.connection.password", "root");
    configuration.setProperty("dialect", "org.hibernate.dialect.MySQLDialect");
    configuration.setProperty("hibernate.hbm2ddl.auto", "update");
    configuration.setProperty("hibernate.show_sql", "true");
    configuration.setProperty(" hibernate.connection.pool_size", "10");


   // configuration
    StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties());
    sessionFactory = configuration.buildSessionFactory(builder.build());
 }
public static SessionFactory getSessionFactory() {
    return sessionFactory;
}
} 

Detecting touch screen devices with Javascript

I use:

if(jQuery.support.touch){
    alert('Touch enabled');
}

in jQuery mobile 1.0.1

How can I write variables inside the tasks file in ansible

NOTE: Using set_fact as described below sets a fact/variable onto the remote servers that the task is running against. This fact/variable will then persist across subsequent tasks for the entire duration of your playbook.

Also, these facts are immutable (for the duration of the playbook), and cannot be changed once set.


ORIGINAL ANSWER

Use set_fact before your task to set facts which seem interchangeable with variables:

- name: Set Apache URL
  set_fact:
    apache_url: 'http://example.com/apache'

- name: Download Apache
  shell: wget {{ apache_url }}

See http://docs.ansible.com/set_fact_module.html for the official word.

Best way to store time (hh:mm) in a database

DATETIME start DATETIME end

I implore you to use two DATETIME values instead, labelled something like event_start and event_end.

Time is a complex business

Most of the world has now adopted the denery based metric system for most measurements, rightly or wrongly. This is good overall, because at least we can all agree that a g, is a ml, is a cubic cm. At least approximately so. The metric system has many flaws, but at least it's internationally consistently flawed.

With time however, we have; 1000 milliseconds in a second, 60 seconds to a minute, 60 minutes to an hour, 12 hours for each half a day, approximately 30 days per month which vary by the month and even year in question, each country has its time offset from others, the way time is formatted in each country vary.

It's a lot to digest, but the long and short of it is impossible for such a complex scenario to have a simple solution.

Some corners can be cut, but there are those where it is wiser not to

Although the top answer here suggests that you store an integer of minutes past midnight might seem perfectly reasonable, I have learned to avoid doing so the hard way.

The reasons to implement two DATETIME values are for an increase in accuracy, resolution and feedback.

These are all very handy for when the design produces undesirable results.

Am I storing more data than required?

It might initially appear like more information is being stored than I require, but there is a good reason to take this hit.

Storing this extra information almost always ends up saving me time and effort in the long-run, because I inevitably find that when somebody is told how long something took, they'll additionally want to know when and where the event took place too.

It's a huge planet

In the past, I have been guilty of ignoring that there are other countries on this planet aside from my own. It seemed like a good idea at the time, but this has ALWAYS resulted in problems, headaches and wasted time later on down the line. ALWAYS consider all time zones.

C#

A DateTime renders nicely to a string in C#. The ToString(string Format) method is compact and easy to read.

E.g.

new TimeSpan(EventStart.Ticks - EventEnd.Ticks).ToString("h'h 'm'm 's's'")

SQL server

Also if you're reading your database seperate to your application interface, then dateTimes are pleasnat to read at a glance and performing calculations on them are straightforward.

E.g.

SELECT DATEDIFF(MINUTE, event_start, event_end)

ISO8601 date standard

If using SQLite then you don't have this, so instead use a Text field and store it in ISO8601 format eg.

"2013-01-27T12:30:00+0000"

Notes:

  • This uses 24 hour clock*

  • The time offset (or +0000) part of the ISO8601 maps directly to longitude value of a GPS coordiate (not taking into account daylight saving or countrywide).

E.g.

TimeOffset=(±Longitude.24)/360 

...where ± refers to east or west direction.

It is therefore worth considering if it would be worth storing longitude, latitude and altitude along with the data. This will vary in application.

  • ISO8601 is an international format.

  • The wiki is very good for further details at http://en.wikipedia.org/wiki/ISO_8601.

  • The date and time is stored in international time and the offset is recorded depending on where in the world the time was stored.

In my experience there is always a need to store the full date and time, regardless of whether I think there is when I begin the project. ISO8601 is a very good, futureproof way of doing it.

Additional advice for free

It is also worth grouping events together like a chain. E.g. if recording a race, the whole event could be grouped by racer, race_circuit, circuit_checkpoints and circuit_laps.

In my experience, it is also wise to identify who stored the record. Either as a seperate table populated via trigger or as an additional column within the original table.

The more you put in, the more you get out

I completely understand the desire to be as economical with space as possible, but I would rarely do so at the expense of losing information.

A rule of thumb with databases is as the title says, a database can only tell you as much as it has data for, and it can be very costly to go back through historical data, filling in gaps.

The solution is to get it correct first time. This is certainly easier said than done, but you should now have a deeper insight of effective database design and subsequently stand a much improved chance of getting it right the first time.

The better your initial design, the less costly the repairs will be later on.

I only say all this, because if I could go back in time then it is what I'd tell myself when I got there.

Taking the record with the max date

Justin Cave answer is the best, but if you want antoher option, try this:

select A,col_date
from (select A,col_date
    from tablename 
      order by col_date desc)
      where rownum<2

How to scroll the page when a modal dialog is longer than the screen?

I wanted to add my pure CSS answer to this problem of modals with dynamic width and height. The following code also works with the following requirements:

  1. Place modal in center of screen
  2. If modal is higher than viewport, scroll dimmer (not modal content)

HTML:

<div class="modal">
    <div class="modal__content">
        (Long) Content
    </div>
</div>

CSS/LESS:

.modal {
    position: fixed;
    display: flex;
    align-items: center;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    padding: @qquad;
    overflow-y: auto;
    background: rgba(0, 0, 0, 0.7);
    z-index: @zindex-modal;

    &__content {
        width: 900px;
        margin: auto;
        max-width: 90%;
        padding: @quad;
        background: white;
        box-shadow: 0 0 5px 0 rgba(0, 0, 0, 0.75);
    }
}

This way the modal is always within the viewport. The width and height of the modal are as flexible as you like. I removed my close icon from this for simplicity.

Difference between window.location.href and top.location.href

top object makes more sense inside frames. Inside a frame, window refers to current frame's window while top refers to the outermost window that contains the frame(s). So:

window.location.href = 'somepage.html'; means loading somepage.html inside the frame.

top.location.href = 'somepage.html'; means loading somepage.html in the main browser window.

Two other interesting objects are self and parent.

Using Composer's Autoload

The composer documentation states that:

After adding the autoload field, you have to re-run install to re-generate the vendor/autoload.php file.

Assuming your "src" dir resides at the same level as "vendor" dir:

  • src
    • AppName
  • vendor
  • composer.json

the following config is absolutely correct:

{
    "autoload": {
        "psr-0": {"AppName": "src/"}
    }
}

but you must re-update/install dependencies to make it work for you, i.e. run:

php composer.phar update

This command will get the latest versions of the dependencies and update the file "vendor/composer/autoload_namespaces.php" to match your configuration.

Also as noted by @Dom, you can use composer dump-autoload to update the autoloader without having to go through an update.

Counting the number of option tags in a select tag in jQuery

The best form is this

$('#example option').length

How to wait until WebBrowser is completely loaded in VB.NET?

Salvete! I needed, simply, a function I could call to make the code wait for the page to load before it continued. After scouring the web for answers, and fiddling around for several hours, I came up with this to solve for myself, the exact dilemma you present. I know I am late in the game with an answer, but I wish to post this for anyone else who comes along.

usage: just call WaitForPageLoad() just after a call to navigation:

whatbrowser.Navigate("http://www.google.com")
WaitForPageLoad()

another example we don't combine the navigate feature with the page load, because sometimes you need to wait for a load without also navigating, for example, you might need to wait for a page to load that was started with an invokemember event:

whatbrowser.Document.GetElementById("UserName").InnerText = whatusername
whatbrowser.Document.GetElementById("Password").InnerText = whatpassword
whatbrowser.Document.GetElementById("LoginButton").InvokeMember("click")
WaitForPageLoad()

Here is the code: You need both subs plus the accessible variable, pageready. First, make sure to fix the variable called whatbrowser to be your webbrowser control

Now, somewhere in your module or class, place this:

Private Property pageready As Boolean = False

#Region "Page Loading Functions"
    Private Sub WaitForPageLoad()
        AddHandler whatbrowser.DocumentCompleted, New WebBrowserDocumentCompletedEventHandler(AddressOf PageWaiter)
        While Not pageready
            Application.DoEvents()
        End While
        pageready = False
    End Sub

    Private Sub PageWaiter(ByVal sender As Object, ByVal e As WebBrowserDocumentCompletedEventArgs)
        If whatbrowser.ReadyState = WebBrowserReadyState.Complete Then
            pageready = True
            RemoveHandler whatbrowser.DocumentCompleted, New WebBrowserDocumentCompletedEventHandler(AddressOf PageWaiter)
        End If
    End Sub

#End Region

Get width/height of SVG element

This is the consistent cross-browser way I found:

var heightComponents = ['height', 'paddingTop', 'paddingBottom', 'borderTopWidth', 'borderBottomWidth'],
    widthComponents = ['width', 'paddingLeft', 'paddingRight', 'borderLeftWidth', 'borderRightWidth'];

var svgCalculateSize = function (el) {

    var gCS = window.getComputedStyle(el), // using gCS because IE8- has no support for svg anyway
        bounds = {
            width: 0,
            height: 0
        };

    heightComponents.forEach(function (css) { 
        bounds.height += parseFloat(gCS[css]);
    });
    widthComponents.forEach(function (css) {
        bounds.width += parseFloat(gCS[css]);
    });
    return bounds;
};

Convert a row of a data frame to vector

Columns of data frames are already vectors, you just have to pull them out. Note that you place the column you want after the comma, not before it:

> newV <- df[,1]
> newV
[1] 1 2 4 2

If you actually want a row, then do what Ben said and please use words correctly in the future.

Running Selenium Webdriver with a proxy in Python

try running tor service, add the following function to your code.

def connect_tor(port):

socks.set_default_proxy(socks.PROXY_TYPE_SOCKS5, '127.0.0.1', port, True)
socket.socket = socks.socksocket

def main():

connect_tor()
driver = webdriver.Firefox()

Get original URL referer with PHP?

Store it in a cookie that only lasts for the current browsing session

Split by comma and strip whitespace in Python

Just remove the white space from the string before you split it.

mylist = my_string.replace(' ','').split(',')

How to change max_allowed_packet size

For those running wamp mysql server

Wamp tray Icon -> MySql -> my.ini

[wampmysqld]
port        = 3306
socket      = /tmp/mysql.sock
key_buffer_size = 16M
max_allowed_packet = 16M        // --> changing this wont solve
sort_buffer_size = 512K

Scroll down to the end until u find

[mysqld]
port=3306
explicit_defaults_for_timestamp = TRUE

Add the line of packet_size in between

[mysqld]
port=3306
max_allowed_packet = 16M
explicit_defaults_for_timestamp = TRUE

Check whether it worked with this query

Select @@global.max_allowed_packet;

Check table exist or not before create it in Oracle

Any solution which relies on testing before creation can run into a 'race' condition where another process creates the table between you testing that it does not exists and creating it. - Minor point I know.

How to enter quotes in a Java string?

Not sure what language you're using (you didn't specify), but you should be able to "escape" the quotation mark character with a backslash: "\"ROM\""

disable a hyperlink using jQuery

Try:

$(this).prop( "disabled", true );

How can I send a file document to the printer and have it print?

System.Diagnostics.Process.Start can be used to print a document. Set UseShellExecute to True and set the Verb to "print".

How to call base.base.method()?

The answer (which I know is not what you're looking for) is:

class SpecialDerived : Base
{
    public override void Say()
    {
        Console.WriteLine("Called from Special Derived.");
        base.Say();
    }
}

The truth is, you only have direct interaction with the class you inherit from. Think of that class as a layer - providing as much or as little of it or its parent's functionality as it desires to its derived classes.

EDIT:

Your edit works, but I think I would use something like this:

class Derived : Base
{
    protected bool _useBaseSay = false;

    public override void Say()
    {
        if(this._useBaseSay)
            base.Say();
        else
            Console.WriteLine("Called from Derived");
    }
}

Of course, in a real implementation, you might do something more like this for extensibility and maintainability:

class Derived : Base
{
    protected enum Mode
    {
        Standard,
        BaseFunctionality,
        Verbose
        //etc
    }

    protected Mode Mode
    {
        get; set;
    }

    public override void Say()
    {
        if(this.Mode == Mode.BaseFunctionality)
            base.Say();
        else
            Console.WriteLine("Called from Derived");
    }
}

Then, derived classes can control their parents' state appropriately.

Binding ng-model inside ng-repeat loop in AngularJS

For each iteration of the ng-repeat loop, line is a reference to an object in your array. Therefore, to preview the value, use {{line.text}}.

Similarly, to databind to the text, databind to the same: ng-model="line.text". You don't need to use value when using ng-model (actually you shouldn't).

Fiddle.

For a more in-depth look at scopes and ng-repeat, see What are the nuances of scope prototypal / prototypical inheritance in AngularJS?, section ng-repeat.

How to use Git Revert

Use git revert like so:

git revert <insert bad commit hash here>

git revert creates a new commit with the changes that are rolled back. git reset erases your git history instead of making a new commit.

The steps after are the same as any other commit.

How to set an environment variable only for the duration of the script?

Just put

export HOME=/blah/whatever

at the point in the script where you want the change to happen. Since each process has its own set of environment variables, this definition will automatically cease to have any significance when the script terminates (and with it the instance of bash that has a changed environment).

How to assign the output of a command to a Makefile variable

Here's a bit more complicated example with piping and variable assignment inside recipe:

getpodname:
    # Getting pod name
    @eval $$(minikube docker-env) ;\
    $(eval PODNAME=$(shell sh -c "kubectl get pods | grep profile-posts-api | grep Running" | awk '{print $$1}'))
    echo $(PODNAME)