Programs & Examples On #Gio

Safe Area of Xcode 9

Safe Area is a layout guide (Safe Area Layout Guide).
The layout guide representing the portion of your view that is unobscured by bars and other content. In iOS 11+, Apple is deprecating the top and bottom layout guides and replacing them with a single safe area layout guide.

When the view is visible onscreen, this guide reflects the portion of the view that is not covered by other content. The safe area of a view reflects the area covered by navigation bars, tab bars, toolbars, and other ancestors that obscure a view controller's view. (In tvOS, the safe area incorporates the screen's bezel, as defined by the overscanCompensationInsets property of UIScreen.) It also covers any additional space defined by the view controller's additionalSafeAreaInsets property. If the view is not currently installed in a view hierarchy, or is not yet visible onscreen, the layout guide always matches the edges of the view.

For the view controller's root view, the safe area in this property represents the entire portion of the view controller's content that is obscured, and any additional insets that you specified. For other views in the view hierarchy, the safe area reflects only the portion of that view that is obscured. For example, if a view is entirely within the safe area of its view controller's root view, the edge insets in this property are 0.

According to Apple, Xcode 9 - Release note
Interface Builder uses UIView.safeAreaLayoutGuide as a replacement for the deprecated Top and Bottom layout guides in UIViewController. To use the new safe area, select Safe Area Layout Guides in the File inspector for the view controller, and then add constraints between your content and the new safe area anchors. This prevents your content from being obscured by top and bottom bars, and by the overscan region on tvOS. Constraints to the safe area are converted to Top and Bottom when deploying to earlier versions of iOS.

enter image description here


Here is simple reference as a comparison (to make similar visual effect) between existing (Top & Bottom) Layout Guide and Safe Area Layout Guide.

Safe Area Layout: enter image description here

AutoLayout

enter image description here


How to work with Safe Area Layout?

Follow these steps to find solution:

  • Enable 'Safe Area Layout', if not enabled.
  • Remove 'all constraint' if they shows connection with with Super view and re-attach all with safe layout anchor. OR Double click on a constraint and edit connection from super view to SafeArea anchor

Here is sample snapshot, how to enable safe area layout and edit constraint.

enter image description here

Here is result of above changes

enter image description here


Layout Design with SafeArea
When designing for iPhone X, you must ensure that layouts fill the screen and aren't obscured by the device's rounded corners, sensor housing, or the indicator for accessing the Home screen.

enter image description here

Most apps that use standard, system-provided UI elements like navigation bars, tables, and collections automatically adapt to the device's new form factor. Background materials extend to the edges of the display and UI elements are appropriately inset and positioned.

enter image description here

For apps with custom layouts, supporting iPhone X should also be relatively easy, especially if your app uses Auto Layout and adheres to safe area and margin layout guides.

enter image description here


Here is sample code (Ref from: Safe Area Layout Guide):
If you create your constraints in code use the safeAreaLayoutGuide property of UIView to get the relevant layout anchors. Let’s recreate the above Interface Builder example in code to see how it looks:

Assuming we have the green view as a property in our view controller:

private let greenView = UIView()

We might have a function to set up the views and constraints called from viewDidLoad:

private func setupView() {
  greenView.translatesAutoresizingMaskIntoConstraints = false
  greenView.backgroundColor = .green
  view.addSubview(greenView)
}

Create the leading and trailing margin constraints as always using the layoutMarginsGuide of the root view:

 let margins = view.layoutMarginsGuide
    NSLayoutConstraint.activate([
      greenView.leadingAnchor.constraint(equalTo: margins.leadingAnchor),
      greenView.trailingAnchor.constraint(equalTo: margins.trailingAnchor)
 ])

Now unless you are targeting iOS 11 only you will need to wrap the safe area layout guide constraints with #available and fall back to top and bottom layout guides for earlier iOS versions:

if #available(iOS 11, *) {
  let guide = view.safeAreaLayoutGuide
  NSLayoutConstraint.activate([
   greenView.topAnchor.constraintEqualToSystemSpacingBelow(guide.topAnchor, multiplier: 1.0),
   guide.bottomAnchor.constraintEqualToSystemSpacingBelow(greenView.bottomAnchor, multiplier: 1.0)
   ])

} else {
   let standardSpacing: CGFloat = 8.0
   NSLayoutConstraint.activate([
   greenView.topAnchor.constraint(equalTo: topLayoutGuide.bottomAnchor, constant: standardSpacing),
   bottomLayoutGuide.topAnchor.constraint(equalTo: greenView.bottomAnchor, constant: standardSpacing)
   ])
}


Result:

enter image description here


Following UIView extension, make it easy for you to work with SafeAreaLayout programatically.

extension UIView {

  // Top Anchor
  var safeAreaTopAnchor: NSLayoutYAxisAnchor {
    if #available(iOS 11.0, *) {
      return self.safeAreaLayoutGuide.topAnchor
    } else {
      return self.topAnchor
    }
  }

  // Bottom Anchor
  var safeAreaBottomAnchor: NSLayoutYAxisAnchor {
    if #available(iOS 11.0, *) {
      return self.safeAreaLayoutGuide.bottomAnchor
    } else {
      return self.bottomAnchor
    }
  }

  // Left Anchor
  var safeAreaLeftAnchor: NSLayoutXAxisAnchor {
    if #available(iOS 11.0, *) {
      return self.safeAreaLayoutGuide.leftAnchor
    } else {
      return self.leftAnchor
    }
  }

  // Right Anchor
  var safeAreaRightAnchor: NSLayoutXAxisAnchor {
    if #available(iOS 11.0, *) {
      return self.safeAreaLayoutGuide.rightAnchor
    } else {
      return self.rightAnchor
    }
  }

}

Here is sample code in Objective-C:


Here is Apple Developer Official Documentation for Safe Area Layout Guide


Safe Area is required to handle user interface design for iPhone-X. Here is basic guideline for How to design user interface for iPhone-X using Safe Area Layout

Is there a way to list all resources in AWS

You can use the Tag Editor.

  1. Go to AWS Console
  2. In the TOP Navigation Pane, click Resource Groups Dropdown
  3. Click Tag Editor AWS list all resources across all regions

Here we can select either a particular region in which we want to search or select all regions from the dropdown. Then we can select actual resources which we want to search or we can also click on individual resources.

enter image description here

Error: the entity type requires a primary key

This exception message doesn't mean it requires a primary key to be defined in your database, it means it requires a primary key to be defined in your class.

Although you've attempted to do so:

private Guid _id;
[Key]
public Guid ID
{
    get { return _id; }
}

This has no effect, as Entity Framework ignores read-only properties. It has to: when it retrieves a Fruits record from the database, it constructs a Fruit object, and then calls the property setters for each mapped property. That's never going to work for read-only properties.

You need Entity Framework to be able to set the value of ID. This means the property needs to have a setter.

Typescript : Property does not exist on type 'object'

If your object could contain any key/value pairs, you could declare an interface called keyable like :

interface keyable {
    [key: string]: any  
}

then use it as follows :

let countryProviders: keyable[];

or

let countryProviders: Array<keyable>;

Add Legend to Seaborn point plot

I tried using Adam B's answer, however, it didn't work for me. Instead, I found the following workaround for adding legends to pointplots.

import matplotlib.patches as mpatches
red_patch = mpatches.Patch(color='#bb3f3f', label='Label1')
black_patch = mpatches.Patch(color='#000000', label='Label2')

In the pointplots, the color can be specified as mentioned in previous answers. Once these patches corresponding to the different plots are set up,

plt.legend(handles=[red_patch, black_patch])

And the legend ought to appear in the pointplot.

Package signatures do not match the previously installed version

This happens when you have installed app with diffrent versions on your mobile/emulator phone.

Simply uninstall existing app will solve the problem

Print Html template in Angular 2 (ng-print in Angular 2)

Use the library ngx-print.

Installing:

yarn add ngx-print
or
npm install ngx-print --save

Change your module:

import {NgxPrintModule} from 'ngx-print';
...
imports: [
    NgxPrintModule,
...

Template:

<div id="print-section">
  // print content
</div>
<button ngxPrint printSectionId="print-section">Print</button>

More details

Maximum call stack size exceeded on npm install

Try removing package-lock.json and the node_modules folder:

rm package-lock.json
rm -r node_modules

boto3 client NoRegionError: You must specify a region error only sometimes

One way or another you must tell boto3 in which region you wish the kms client to be created. This could be done explicitly using the region_name parameter as in:

kms = boto3.client('kms', region_name='us-west-2')

or you can have a default region associated with your profile in your ~/.aws/config file as in:

[default]
region=us-west-2

or you can use an environment variable as in:

export AWS_DEFAULT_REGION=us-west-2

but you do need to tell boto3 which region to use.

React Native: Possible unhandled promise rejection

Adding here my experience that hopefully might help somebody.

I was experiencing the same issue on Android emulator in Linux with hot reload. The code was correct as per accepted answer and the emulator could reach the internet (I needed a domain name).

Refreshing manually the app made it work. So maybe it has something to do with the hot reloading.

How to write to a CSV line by line?

I would simply write each line to a file, since it's already in a CSV format:

write_file = "output.csv"
with open(write_file, "w") as output:
    for line in text:
        output.write(line + '\n')

I can't recall how to write lines with line-breaks at the moment, though :p

Also, you might like to take a look at this answer about write(), writelines(), and '\n'.

AWS Lambda import module error in python

Error was due to file name of the lambda function. While creating the lambda function it will ask for Lambda function handler. You have to name it as your Python_File_Name.Method_Name. In this scenario I named it as lambda.lambda_handler (lambda.py is the file name).

Please find below the snapshot. enter image description here

Can't push image to Amazon ECR - fails with "no basic auth credentials"

After run this command:

(aws ecr get-login --no-include-email --region us-west-2)

just run the docker login command from the output

docker login -u AWS -p epJ....

is the way that docker login into ECR

Checking for multiple conditions using "when" on single task in ansible

Also you can use default() filter. Or just a shortcut d()

- name: Generating a new SSH key for the current user it's not exists already
  local_action:
    module: user
    name: "{{ login_user.stdout }}"
    generate_ssh_key: yes 
    ssh_key_bits: 2048
  when: 
    - sshkey_result.rc == 1
    - github_username | d('none') | lower == 'none'

Compute row average in pandas

You can specify a new column. You also need to compute the mean along the rows, so use axis=1.

df['mean'] = df.mean(axis=1)
>>> df
       Y1961      Y1962      Y1963      Y1964      Y1965 Region       mean
0  82.567307  83.104757  83.183700  83.030338  82.831958     US  82.943612
1   2.699372   2.610110   2.587919   2.696451   2.846247     US   2.688020
2  14.131355  13.690028  13.599516  13.649176  13.649046     US  13.743824
3   0.048589   0.046982   0.046583   0.046225   0.051750     US   0.048026
4   0.553377   0.548123   0.582282   0.577811   0.620999     US   0.576518

HikariCP - connection is not available

I managed to fix it finally. The problem is not related to HikariCP. The problem persisted because of some complex methods in REST controllers executing multiple changes in DB through JPA repositories. For some reasons calls to these interfaces resulted in a growing number of "freezed" active connections, exhausting the pool. Either annotating these methods as @Transactional or enveloping all the logic in a single call to transactional service method seem to solve the problem.

What are the integrity and crossorigin attributes?

Both attributes have been added to Bootstrap CDN to implement Subresource Integrity.

Subresource Integrity defines a mechanism by which user agents may verify that a fetched resource has been delivered without unexpected manipulation Reference

Integrity attribute is to allow the browser to check the file source to ensure that the code is never loaded if the source has been manipulated.

Crossorigin attribute is present when a request is loaded using 'CORS' which is now a requirement of SRI checking when not loaded from the 'same-origin'. More info on crossorigin

More detail on Bootstrap CDNs implementation

How can I switch word wrap on and off in Visual Studio Code?

wrappingColumn has been deprecated in favour of wordWrap.

Add this line to settings.json to set wordWrap on by default:

"editor.wordWrap": "on" 

or open user settings:

Mac: ? + ,

Windows: Ctrl + ,

Then search for "wordWrap" or scroll through the 'Commonly Used' settings to find it and select 'on'

enter image description here

When do I use path params vs. query params in a RESTful API?

The fundamental way to think about this subject is as follows:

A URI is a resource identifier that uniquely identifies a specific instance of a resource TYPE. Like everything else in life, every object (which is an instance of some type), have set of attributes that are either time-invariant or temporal.

In the example above, a car is a very tangible object that has attributes like make, model and VIN - that never changes, and color, suspension etc. that may change over time. So if we encode the URI with attributes that may change over time (temporal), we may end up with multiple URIs for the same object:

GET /cars/honda/civic/coupe/{vin}/{color=red}

And years later, if the color of this very same car is changed to black:

GET /cars/honda/civic/coupe/{vin}/{color=black}

Note that the car instance itself (the object) has not changed - it's just the color that changed. Having multiple URIs pointing to the same object instance will force you to create multiple URI handlers - this is not an efficient design, and is of course not intuitive.

Therefore, the URI should only consist of parts that will never change and will continue to uniquely identify that resource throughout its lifetime. Everything that may change should be reserved for query parameters, as such:

GET /cars/honda/civic/coupe/{vin}?color={black}

Bottom line - think polymorphism.

AWS S3 - How to fix 'The request signature we calculated does not match the signature' error?

I am getting the same error Due to following reason.

I have entered right credentials but with copy-paste. So that may b issue of junk characters insertion while copy paste. I have entered manually and ran the code and now its working fine

Thank You

Calling Web API from MVC controller

well, you can do it a lot of ways... one of them is to create a HttpRequest. I would advise you against calling your own webapi from your own MVC (the idea is redundant...) but, here's a end to end tutorial.

Error You must specify a region when running command aws ecs list-container-instances

"You must specify a region" is a not an ECS specific error, it can happen with any AWS API/CLI/SDK command.

For the CLI, either set the AWS_DEFAULT_REGION environment variable. e.g.

export AWS_DEFAULT_REGION=us-east-1

or add it into the command (you will need this every time you use a region-specific command)

AWS_DEFAULT_REGION=us-east-1 aws ecs list-container-instances --cluster default

or set it in the CLI configuration file: ~/.aws/config

[default]
region=us-east-1

or pass/override it with the CLI call:

aws ecs list-container-instances --cluster default --region us-east-1

How to convert a pymongo.cursor.Cursor into a dict?

The MongoDB find method does not return a single result, but a list of results in the form of a Cursor. This latter is an iterator, so you can go through it with a for loop.

For your case, just use the findOne method instead of find. This will returns you a single document as a dictionary.

Open web in new tab Selenium + Python

Strangely, so many answers, and all of them are using surrogates like JS and keyboard shortcuts instead of just using a selenium feature:

def newTab(driver, url="about:blank"):
    wnd = driver.execute(selenium.webdriver.common.action_chains.Command.NEW_WINDOW)
    handle = wnd["value"]["handle"]
    driver.switch_to.window(handle)
    driver.get(url) # changes the handle
    return driver.current_window_handle

python 3.x ImportError: No module named 'cStringIO'

I had the same issue because my file was called email.py. I renamed the file and the issue disappeared.

Concatenate strings from several rows using Pandas groupby

You can groupby the 'name' and 'month' columns, then call transform which will return data aligned to the original df and apply a lambda where we join the text entries:

In [119]:

df['text'] = df[['name','text','month']].groupby(['name','month'])['text'].transform(lambda x: ','.join(x))
df[['name','text','month']].drop_duplicates()
Out[119]:
    name         text  month
0  name1       hej,du     11
2  name1        aj,oj     12
4  name2     fin,katt     11
6  name2  mycket,lite     12

I sub the original df by passing a list of the columns of interest df[['name','text','month']] here and then call drop_duplicates

EDIT actually I can just call apply and then reset_index:

In [124]:

df.groupby(['name','month'])['text'].apply(lambda x: ','.join(x)).reset_index()

Out[124]:
    name  month         text
0  name1     11       hej,du
1  name1     12        aj,oj
2  name2     11     fin,katt
3  name2     12  mycket,lite

update

the lambda is unnecessary here:

In[38]:
df.groupby(['name','month'])['text'].apply(','.join).reset_index()

Out[38]: 
    name  month         text
0  name1     11           du
1  name1     12        aj,oj
2  name2     11     fin,katt
3  name2     12  mycket,lite

Removing NA in dplyr pipe

I don't think desc takes an na.rm argument... I'm actually surprised it doesn't throw an error when you give it one. If you just want to remove NAs, use na.omit (base) or tidyr::drop_na:

outcome.df %>%
  na.omit() %>%
  group_by(Hospital, State) %>%
  arrange(desc(HeartAttackDeath)) %>%
  head()

library(tidyr)
outcome.df %>%
  drop_na() %>%
  group_by(Hospital, State) %>%
  arrange(desc(HeartAttackDeath)) %>%
  head()

If you only want to remove NAs from the HeartAttackDeath column, filter with is.na, or use tidyr::drop_na:

outcome.df %>%
  filter(!is.na(HeartAttackDeath)) %>%
  group_by(Hospital, State) %>%
  arrange(desc(HeartAttackDeath)) %>%
  head()

outcome.df %>%
  drop_na(HeartAttackDeath) %>%
  group_by(Hospital, State) %>%
  arrange(desc(HeartAttackDeath)) %>%
  head()

As pointed out at the dupe, complete.cases can also be used, but it's a bit trickier to put in a chain because it takes a data frame as an argument but returns an index vector. So you could use it like this:

outcome.df %>%
  filter(complete.cases(.)) %>%
  group_by(Hospital, State) %>%
  arrange(desc(HeartAttackDeath)) %>%
  head()

The authorization mechanism you have provided is not supported. Please use AWS4-HMAC-SHA256

For thumbor-aws, that used boto config, i needed to put this to the $AWS_CONFIG_FILE

[default]
aws_access_key_id = (your ID)
aws_secret_access_key = (your secret key)
s3 =
    signature_version = s3

So anything that used boto directly without changes, this may be useful

How to use Python to execute a cURL command?

import requests
url = "https://www.googleapis.com/qpxExpress/v1/trips/search?key=mykeyhere"
data = requests.get(url).json

maybe?

if you are trying to send a file

files = {'request_file': open('request.json', 'rb')}
r = requests.post(url, files=files)
print r.text, print r.json

ahh thanks @LukasGraf now i better understand what his original code is doing

import requests,json
url = "https://www.googleapis.com/qpxExpress/v1/trips/search?key=mykeyhere"
my_json_data = json.load(open("request.json"))
req = requests.post(url,data=my_json_data)
print req.text
print 
print req.json # maybe? 

AWS S3: The bucket you are attempting to access must be addressed using the specified endpoint

After a long search, I found a working solution. The issue was because of the wrong region-code.

below is the list of region-codes, set the appropriate one and your issue will be solved.

Code                         Name
US East (Ohio)               us-east-2

US East (N. Virginia)       us-east-1

US West (N. California)     us-west-1

US West (Oregon)            us-west-2

Asia Pacific (Hong Kong)    ap-east-1

Asia Pacific (Mumbai)       ap-south-1

Asia Pacific (Osaka-Local)  ap-northeast-3

Asia Pacific (Seoul)        ap-northeast-2

Asia Pacific (Singapore)    ap-southeast-1

Asia Pacific (Sydney)       ap-southeast-2

Asia Pacific (Tokyo)        ap-northeast-1

Canada (Central)            ca-central-1

Europe (Frankfurt)          eu-central-1

Europe (Ireland)            eu-west-1

Europe (London)             eu-west-2

Europe (Paris)             eu-west-3

Europe (Stockholm)         eu-north-1

Middle East (Bahrain)      me-south-1

South America (São Paulo)   sa-east-1

You can find your region-code on click of bucket name right corner.

enter image description here

For mode details Click

Store a closure as a variable in Swift

Closures can be declared as typealias as below

typealias Completion = (Bool, Any, Error) -> Void

If you want to use in your function anywhere in code; you can write like normal variable

func xyz(with param1: String, completion: Completion) {
}

How can prevent a PowerShell window from closing so I can see the error?

this will make the powershell window to wait until you press any key:

pause

Update One

Thanks to Stein. it is the Enter key not any key.

Spring Data JPA find by embedded object property

If you are using BookId as an combined primary key, then remember to change your interface from:

public interface QueuedBookRepo extends JpaRepository<QueuedBook, Long> {

to:

public interface QueuedBookRepo extends JpaRepository<QueuedBook, BookId> {

And change the annotation @Embedded to @EmbeddedId, in your QueuedBook class like this:

public class QueuedBook implements Serializable {

@EmbeddedId
@NotNull
private BookId bookId;

...

Validate date in dd/mm/yyyy format using JQuery Validate

This will also checks in leap year. This is pure regex, so it's faster than any lib (also faster than moment.js). But if you gonna use a lot of dates in ur code, I do recommend to use moment.js

var dateRegex = /^(?=\d)(?:(?:31(?!.(?:0?[2469]|11))|(?:30|29)(?!.0?2)|29(?=.0?2.(?:(?:(?:1[6-9]|[2-9]\d)?(?:0[48]|[2468][048]|[13579][26])|(?:(?:16|[2468][048]|[3579][26])00)))(?:\x20|$))|(?:2[0-8]|1\d|0?[1-9]))([-.\/])(?:1[012]|0?[1-9])\1(?:1[6-9]|[2-9]\d)?\d\d(?:(?=\x20\d)\x20|$))?(((0?[1-9]|1[012])(:[0-5]\d){0,2}(\x20[AP]M))|([01]\d|2[0-3])(:[0-5]\d){1,2})?$/;

console.log(dateRegex.test('21/01/1986'));

enter image description here

http://regexper.com/....

How to draw a rectangle around a region of interest in python

please don't try with the old cv module, use cv2:

import cv2

cv2.rectangle(img, (x1, y1), (x2, y2), (255,0,0), 2)


x1,y1 ------
|          |
|          |
|          |
--------x2,y2

[edit] to append the follow-up questions below:

cv2.imwrite("my.png",img)

cv2.imshow("lalala", img)
k = cv2.waitKey(0) # 0==wait forever

SQL Server: use CASE with LIKE

SELECT Lname, Cods, CASE WHEN Lname LIKE '% HN%' THEN SUBSTRING(Lname, 
CHARINDEX(' ', Lname) - 50, 50) WHEN Lname LIKE 'HN%' THEN Lname ELSE 
Lname END AS LnameTrue FROM dbo.____Fname_Lname

Extracting text OpenCV

Python Implementation for @dhanushka's solution:

def process_rgb(rgb):
    hasText = False
    gray = cv2.cvtColor(rgb, cv2.COLOR_BGR2GRAY)
    morphKernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (3,3))
    grad = cv2.morphologyEx(gray, cv2.MORPH_GRADIENT, morphKernel)
    # binarize
    _, bw = cv2.threshold(grad, 0.0, 255.0, cv2.THRESH_BINARY | cv2.THRESH_OTSU)
    # connect horizontally oriented regions
    morphKernel = cv2.getStructuringElement(cv2.MORPH_RECT, (9, 1))
    connected = cv2.morphologyEx(bw, cv2.MORPH_CLOSE, morphKernel)
    # find contours
    mask = np.zeros(bw.shape[:2], dtype="uint8")
    _,contours, hierarchy = cv2.findContours(connected, cv2.RETR_CCOMP, cv2.CHAIN_APPROX_SIMPLE)
    # filter contours
    idx = 0
    while idx >= 0:
        x,y,w,h = cv2.boundingRect(contours[idx])
        # fill the contour
        cv2.drawContours(mask, contours, idx, (255, 255, 255), cv2.FILLED)
        # ratio of non-zero pixels in the filled region
        r = cv2.contourArea(contours[idx])/(w*h)
        if(r > 0.45 and h > 5 and w > 5 and w > h):
            cv2.rectangle(rgb, (x,y), (x+w,y+h), (0, 255, 0), 2)
            hasText = True
        idx = hierarchy[0][idx][0]
    return hasText, rgb

python - if not in list

if I got it right, you can try

for item in [x for x in checklist if x not in mylist]:
    print (item)

Failed to build gem native extension (installing Compass)

Hi it was a challenge to get it work on Mac so anyway here is a solution

  1. Install macports
  2. Install rvm
  3. Restart Terminal
  4. Run rvm requirements then run rvm install 2.1
  5. And last step to run gem install compass --pre

I'm not sure but ruby version on Mavericks doesn't support native extensions etc... so if you point to other ruby version like I did "2.1" it works fine.

Python Script to convert Image into Byte array

Use bytearray:

with open("img.png", "rb") as image:
  f = image.read()
  b = bytearray(f)
  print b[0]

You can also have a look at struct which can do many conversions of that kind.

Running powershell script within python script, how to make python print the powershell output while it is running

  1. Make sure you can run powershell scripts (it is disabled by default). Likely you have already done this. http://technet.microsoft.com/en-us/library/ee176949.aspx

    Set-ExecutionPolicy RemoteSigned
    
  2. Run this python script on your powershell script helloworld.py:

    # -*- coding: iso-8859-1 -*-
    import subprocess, sys
    
    p = subprocess.Popen(["powershell.exe", 
                  "C:\\Users\\USER\\Desktop\\helloworld.ps1"], 
                  stdout=sys.stdout)
    p.communicate()
    

This code is based on python3.4 (or any 3.x series interpreter), though it should work on python2.x series as well.

C:\Users\MacEwin\Desktop>python helloworld.py
Hello World

Simple working Example of json.net in VB.net

In Place of using this

MsgBox(json.SelectToken("Venue").SelectToken("ID"))

You can also use

MsgBox(json.SelectToken("Venue.ID"))

allowing only alphabets in text box using java script

You can use HTML5 pattern attribute to do this:

<form>
    <input type='text' pattern='[A-Za-z\\s]*'/>
</form>

If the user enters an input that conflicts with the pattern, it will show an error dialogue automatically.

How to deal with SettingWithCopyWarning in Pandas

To remove any doubt, my solution was to make a deep copy of the slice instead of a regular copy. This may not be applicable depending on your context (Memory constraints / size of the slice, potential for performance degradation - especially if the copy occurs in a loop like it did for me, etc...)

To be clear, here is the warning I received:

/opt/anaconda3/lib/python3.6/site-packages/ipykernel/__main__.py:54:
SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame
See the caveats in the documentation:
http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy

Illustration

I had doubts that the warning was thrown because of a column I was dropping on a copy of the slice. While not technically trying to set a value in the copy of the slice, that was still a modification of the copy of the slice. Below are the (simplified) steps I have taken to confirm the suspicion, I hope it will help those of us who are trying to understand the warning.

Example 1: dropping a column on the original affects the copy

We knew that already but this is a healthy reminder. This is NOT what the warning is about.

>> data1 = {'A': [111, 112, 113], 'B':[121, 122, 123]}
>> df1 = pd.DataFrame(data1)
>> df1

    A   B
0   111 121
1   112 122
2   113 123


>> df2 = df1
>> df2

A   B
0   111 121
1   112 122
2   113 123

# Dropping a column on df1 affects df2
>> df1.drop('A', axis=1, inplace=True)
>> df2
    B
0   121
1   122
2   123

It is possible to avoid changes made on df1 to affect df2. Note: you can avoid importing copy.deepcopy by doing df.copy() instead.

>> data1 = {'A': [111, 112, 113], 'B':[121, 122, 123]}
>> df1 = pd.DataFrame(data1)
>> df1

A   B
0   111 121
1   112 122
2   113 123

>> import copy
>> df2 = copy.deepcopy(df1)
>> df2
A   B
0   111 121
1   112 122
2   113 123

# Dropping a column on df1 does not affect df2
>> df1.drop('A', axis=1, inplace=True)
>> df2
    A   B
0   111 121
1   112 122
2   113 123

Example 2: dropping a column on the copy may affect the original

This actually illustrates the warning.

>> data1 = {'A': [111, 112, 113], 'B':[121, 122, 123]}
>> df1 = pd.DataFrame(data1)
>> df1

    A   B
0   111 121
1   112 122
2   113 123

>> df2 = df1
>> df2

    A   B
0   111 121
1   112 122
2   113 123

# Dropping a column on df2 can affect df1
# No slice involved here, but I believe the principle remains the same?
# Let me know if not
>> df2.drop('A', axis=1, inplace=True)
>> df1

B
0   121
1   122
2   123

It is possible to avoid changes made on df2 to affect df1

>> data1 = {'A': [111, 112, 113], 'B':[121, 122, 123]}
>> df1 = pd.DataFrame(data1)
>> df1

    A   B
0   111 121
1   112 122
2   113 123

>> import copy
>> df2 = copy.deepcopy(df1)
>> df2

A   B
0   111 121
1   112 122
2   113 123

>> df2.drop('A', axis=1, inplace=True)
>> df1

A   B
0   111 121
1   112 122
2   113 123

Cheers!

Deciding between HttpClient and WebClient

Firstly, I am not an authority on WebClient vs. HttpClient, specifically. Secondly, from your comments above, it seems to suggest that WebClient is Sync ONLY whereas HttpClient is both.

I did a quick performance test to find how WebClient (Sync calls), HttpClient (Sync and Async) perform. and here are the results.

I see that as a huge difference when thinking for future, i.e. long running processes, responsive GUI, etc. (add to the benefit you suggest by framework 4.5 - which in my actual experience is hugely faster on IIS)

Overlay normal curve to histogram in R

This is an implementation of aforementioned StanLe's anwer, also fixing the case where his answer would produce no curve when using densities.

This replaces the existing but hidden hist.default() function, to only add the normalcurve parameter (which defaults to TRUE).

The first three lines are to support roxygen2 for package building.

#' @noRd
#' @exportMethod hist.default
#' @export
hist.default <- function(x,
                         breaks = "Sturges",
                         freq = NULL,
                         include.lowest = TRUE,
                         normalcurve = TRUE,
                         right = TRUE,
                         density = NULL,
                         angle = 45,
                         col = NULL,
                         border = NULL,
                         main = paste("Histogram of", xname),
                         ylim = NULL,
                         xlab = xname,
                         ylab = NULL,
                         axes = TRUE,
                         plot = TRUE,
                         labels = FALSE,
                         warn.unused = TRUE,
                         ...)  {

  # https://stackoverflow.com/a/20078645/4575331
  xname <- paste(deparse(substitute(x), 500), collapse = "\n")

  suppressWarnings(
    h <- graphics::hist.default(
      x = x,
      breaks = breaks,
      freq = freq,
      include.lowest = include.lowest,
      right = right,
      density = density,
      angle = angle,
      col = col,
      border = border,
      main = main,
      ylim = ylim,
      xlab = xlab,
      ylab = ylab,
      axes = axes,
      plot = plot,
      labels = labels,
      warn.unused = warn.unused,
      ...
    )
  )

  if (normalcurve == TRUE & plot == TRUE) {
    x <- x[!is.na(x)]
    xfit <- seq(min(x), max(x), length = 40)
    yfit <- dnorm(xfit, mean = mean(x), sd = sd(x))
    if (isTRUE(freq) | (is.null(freq) & is.null(density))) {
      yfit <- yfit * diff(h$mids[1:2]) * length(x)
    }
    lines(xfit, yfit, col = "black", lwd = 2)
  }

  if (plot == TRUE) {
    invisible(h)
  } else {
    h
  }
}

Quick example:

hist(g)

enter image description here

For dates it's bit different. For reference:

#' @noRd
#' @exportMethod hist.Date
#' @export
hist.Date <- function(x,
                      breaks = "months",
                      format = "%b",
                      normalcurve = TRUE,
                      xlab = xname,
                      plot = TRUE,
                      freq = NULL,
                      density = NULL,
                      start.on.monday = TRUE,
                      right = TRUE,
                      ...)  {

  # https://stackoverflow.com/a/20078645/4575331
  xname <- paste(deparse(substitute(x), 500), collapse = "\n")

  suppressWarnings(
    h <- graphics:::hist.Date(
      x = x,
      breaks = breaks,
      format = format,
      freq = freq,
      density = density,
      start.on.monday = start.on.monday,
      right = right,
      xlab = xlab,
      plot = plot,
      ...
    )
  )

  if (normalcurve == TRUE & plot == TRUE) {
    x <- x[!is.na(x)]
    xfit <- seq(min(x), max(x), length = 40)
    yfit <- dnorm(xfit, mean = mean(x), sd = sd(x))
    if (isTRUE(freq) | (is.null(freq) & is.null(density))) {
      yfit <- as.double(yfit) * diff(h$mids[1:2]) * length(x)
    }
    lines(xfit, yfit, col = "black", lwd = 2)
  }

  if (plot == TRUE) {
    invisible(h)
  } else {
    h
  }
}

How to select option in drop down protractorjs e2e tests

We wanted to use the elegant solution up there using angularjs material but it didnt work because there are actually no option / md-option tags in the DOM until the md-select has been clicked. So the "elegant" way didn't work for us (note angular material!) Here is what we did for it instead, don't know if its the best way but its definately working now

element.all(by.css('md-select')).each(function (eachElement, index) {
    eachElement.click();                    // select the <select>
    browser.driver.sleep(500);              // wait for the renderings to take effect
    element(by.css('md-option')).click();   // select the first md-option
    browser.driver.sleep(500);              // wait for the renderings to take effect
});

We needed to have 4 selects selected and while the select is open, there is an overlay in the way of selecting the next select. thats why we need to wait 500ms to make sure we don't get into trouble with the material effects still being in action.

Wait on the Database Engine recovery handle failed. Check the SQL server error log for potential causes

Below worked for me:

When you come to Server Configuration Screen, Change the Account Name of Database Engine Service to NT AUTHORITY\NETWORK SERVICE and continue installation and it will successfully install all components without any error. - See more at: https://superpctricks.com/sql-install-error-database-engine-recovery-handle-failed/

Renaming Column Names in Pandas Groupby function

For the first question I think answer would be:

<your DataFrame>.rename(columns={'count':'Total_Numbers'})

or

<your DataFrame>.columns = ['ID', 'Region', 'Total_Numbers']

As for second one I'd say the answer would be no. It's possible to use it like 'df.ID' because of python datamodel:

Attribute references are translated to lookups in this dictionary, e.g., m.x is equivalent to m.dict["x"]

An internal error occurred during: "Updating Maven Project". java.lang.NullPointerException

I encountered this same symptom and none of the solutions above were helpful. I finally got a stack trace of the problem by importing the ear project again to eclipse, and was able to trace this down to the org.eclipse.m2e.wtp.MavenDeploymentDescriptorManagement which was trying to delete a directory in windows' temp directory called ".mavenDeploymentDescriptorManagement", which caused an irrational NullPointerException from the java.io.File.exists() method, particularly because the code already had successfully done the same thing in a previous method with the same variable, then called file.isFile() without problem.

Checking this out on the file system revealed that the file could only be accessed with administrator privileges. Apparently I had at some point launched eclipse from an administrator console by mistake. In the end I just made hidden files visible in windows explorer and deleted the temporary file manually, which solved the problem.

AngularJS resource promise

If you're looking to get promise in resource call, you should use

Regions.query().$q.then(function(){ .... })

Update : the promise syntax is changed in current versions which reads

Regions.query().$promise.then(function(){ ..... })

Those who have downvoted don't know what it was and who first added this promise to resource object. I used this feature in late 2012 - yes 2012.

Web API Put Request generates an Http 405 Method Not Allowed error

Your client application and server application must be under same domain, for example :

client - localhost

server - localhost

and not :

client - localhost:21234

server - localhost

Bootstrap 3: Scroll bars

You need to use overflow option like below:

.nav{
    max-height: 300px;
    overflow-y: scroll; 
}

Change the height according to amount of items you need to show

Read a zipped file as a pandas DataFrame

If you want to read a zipped or a tar.gz file into pandas dataframe, the read_csv methods includes this particular implementation.

df = pd.read_csv('filename.zip')

Or the long form:

df = pd.read_csv('filename.zip', compression='zip', header=0, sep=',', quotechar='"')

Description of the compression argument from the docs:

compression : {‘infer’, ‘gzip’, ‘bz2’, ‘zip’, ‘xz’, None}, default ‘infer’ For on-the-fly decompression of on-disk data. If ‘infer’ and filepath_or_buffer is path-like, then detect compression from the following extensions: ‘.gz’, ‘.bz2’, ‘.zip’, or ‘.xz’ (otherwise no decompression). If using ‘zip’, the ZIP file must contain only one data file to be read in. Set to None for no decompression.

New in version 0.18.1: support for ‘zip’ and ‘xz’ compression.

where to place CASE WHEN column IS NULL in this query

That looks like it might belong in the select statement:

SELECT id, col1, col2, col3, (CASE WHEN table3.col3 IS NULL THEN table2.col3 AS col4 ELSE table3.col3 as col4 END)
FROM table1
LEFT OUTER JOIN table2
ON table1.id = table2.id
LEFT OUTER JOIN table3
ON table1.id = table3.id

Merging cells in Excel using Apache POI

You can use sheet.addMergedRegion(rowFrom,rowTo,colFrom,colTo);

example sheet.addMergedRegion(new CellRangeAddress(1,1,1,4)); will merge from B2 to E2. Remember it is zero based indexing (ex. POI version 3.12).

for detail refer BusyDeveloper's Guide

Git Extensions: Win32 error 487: Couldn't reserve space for cygwin's heap, Win32 error 0

Cygwin uses persistent shared memory sections, which can on occasion become corrupted. The symptom of this is that some Cygwin programs begin to fail, but other applications are unaffected. Since these shared memory sections are persistent, often a system reboot is needed to clear them out before the problem can be resolved.

Test method is inconclusive: Test wasn't run. Error?

In my case my test method was private I changed it to public and it worked.

Regarding Java switch statements - using return and omitting breaks in each case

Nope, what you have is fine. You could also do this as a formula (sliderVal < 5 ? (1.0 - 0.1 * sliderVal) : 1.0) or use a Map<Integer,Double>, but what you have is fine.

Python Pandas Error tokenizing data

following sequence of commands works (I lose the first line of the data -no header=None present-, but at least it loads):

df = pd.read_csv(filename, usecols=range(0, 42)) df.columns = ['YR', 'MO', 'DAY', 'HR', 'MIN', 'SEC', 'HUND', 'ERROR', 'RECTYPE', 'LANE', 'SPEED', 'CLASS', 'LENGTH', 'GVW', 'ESAL', 'W1', 'S1', 'W2', 'S2', 'W3', 'S3', 'W4', 'S4', 'W5', 'S5', 'W6', 'S6', 'W7', 'S7', 'W8', 'S8', 'W9', 'S9', 'W10', 'S10', 'W11', 'S11', 'W12', 'S12', 'W13', 'S13', 'W14']

Following does NOT work:

df = pd.read_csv(filename, names=['YR', 'MO', 'DAY', 'HR', 'MIN', 'SEC', 'HUND', 'ERROR', 'RECTYPE', 'LANE', 'SPEED', 'CLASS', 'LENGTH', 'GVW', 'ESAL', 'W1', 'S1', 'W2', 'S2', 'W3', 'S3', 'W4', 'S4', 'W5', 'S5', 'W6', 'S6', 'W7', 'S7', 'W8', 'S8', 'W9', 'S9', 'W10', 'S10', 'W11', 'S11', 'W12', 'S12', 'W13', 'S13', 'W14'], usecols=range(0, 42))

CParserError: Error tokenizing data. C error: Expected 53 fields in line 1605634, saw 54 Following does NOT work:

df = pd.read_csv(filename, header=None)

CParserError: Error tokenizing data. C error: Expected 53 fields in line 1605634, saw 54

Hence, in your problem you have to pass usecols=range(0, 2)

npm install errors with Error: ENOENT, chmod

None of the above worked for me. But yarn install worked, then npm i started working. Not sure what yarn fixed, but quick and easy solution!

Excel VBA Automation Error: The object invoked has disconnected from its clients

You must have used the object, released it ("disconnect"), and used it again. Release object only after you're finished with it, or when calling Form_Closing.

R: "Unary operator error" from multiline ggplot2 command

Try to consolidate the syntax in a single line. this will clear the error

Simple VBA selection: Selecting 5 cells to the right of the active cell

This example selects a new Range of Cells defined by the current cell to a cell 5 to the right.

Note that .Offset takes arguments of Offset(row, columns) and can be quite useful.


Sub testForStackOverflow()
    Range(ActiveCell, ActiveCell.Offset(0, 5)).Copy
End Sub

Extract code country from phone number [libphonenumber]

Here is a solution to get the country based on an international phone number without using the Google library.

Let me explain first why it is so difficult to figure out the country. The country code of few countries is 1 digit, 2, 3 or 4 digits. That would be simple enough. But the country code 1 is not just used for US, but also for Canada and some smaller places:

1339 USA
1340 Virgin Islands (Caribbean Islands)
1341 USA
1342 not used
1343 Canada

Digits 2..4 decide, if it is US or Canada or ... There is no easy way to figure out the country, like the first xxx are Canada, the rest US.

For my code, I defined a class which holds information for ever digit:

public class DigitInfo {
  public char Digit;
  public Country? Country;
  public DigitInfo?[]? Digits;
}

A first array holds the DigitInfos for the first digit in the number. The second digit is used as an index into DigitInfo.Digits. One travels down that Digits chain, until Digits is empty. If Country is defined (i.e. not null) that value gets returned, otherwise any Country defined earlier gets returned:

country code 1: byPhone[1].Country is US  
country code 1236: byPhone[1].Digits[2].Digits[3].Digits[6].Country is Canada  
country code 1235: byPhone[1].Digits[2].Digits[3].Digits[5].Country is null. Since   
                   byPhone[1].Country is US, also 1235 is US, because no other   
                   country was found in the later digits

Here is the method which returns the country based on the phone number:

/// <summary>
/// Returns the Country based on an international dialing code.
/// </summary>
public static Country? GetCountry(ReadOnlySpan<char> phoneNumber) {
  if (phoneNumber.Length==0) return null;

  var isFirstDigit = true;
  DigitInfo? digitInfo = null;
  Country? country = null;
  foreach (var digitChar in phoneNumber) {
    var digitIndex = digitChar - '0';
    if (isFirstDigit) {
      isFirstDigit = false;
      digitInfo = ByPhone[digitIndex];
    } else {
      if (digitInfo!.Digits is null) return country;

      digitInfo = digitInfo.Digits[digitIndex];
    }
    if (digitInfo is null) return country;

    country = digitInfo.Country??country;
  }
  return country;
}

The rest of the code (digitInfos for every country of the world, test code, ...) is too big to be posted here, but it can be found on Github: https://github.com/PeterHuberSg/WpfWindowsLib/blob/master/WpfWindowsLib/CountryCode.cs

The code is part of a WPF TextBox and the library contains also other controls for email addresses, etc. A more detailed description is on CodeProject: International Phone Number Validation Explained in Detail

Read a Csv file with powershell and capture corresponding data

What you should be looking at is Import-Csv

Once you import the CSV you can use the column header as the variable.

Example CSV:

Name  | Phone Number | Email
Elvis | 867.5309     | [email protected]
Sammy | 555.1234     | [email protected]

Now we will import the CSV, and loop through the list to add to an array. We can then compare the value input to the array:

$Name = @()
$Phone = @()

Import-Csv H:\Programs\scripts\SomeText.csv |`
    ForEach-Object {
        $Name += $_.Name
        $Phone += $_."Phone Number"
    }

$inputNumber = Read-Host -Prompt "Phone Number"

if ($Phone -contains $inputNumber)
    {
    Write-Host "Customer Exists!"
    $Where = [array]::IndexOf($Phone, $inputNumber)
    Write-Host "Customer Name: " $Name[$Where]
    }

And here is the output:

I Found Sammy

JSONDecodeError: Expecting value: line 1 column 1 (char 0)

Be sure to remember to invoke json.loads() on the contents of the file, as opposed to the file path of that JSON:

json_file_path = "/path/to/example.json"

with open(json_file_path, 'r') as j:
     contents = json.loads(j.read())

I think a lot of people are guilty of doing this every once in a while (myself included):

contents = json.loads(json_file_path)

Tkinter scrollbar for frame

We can add scroll bar even without using Canvas. I have read it in many other post we can't add vertical scroll bar in frame directly etc etc. But after doing many experiment found out way to add vertical as well as horizontal scroll bar :). Please find below code which is used to create scroll bar in treeView and frame.

f = Tkinter.Frame(self.master,width=3)
f.grid(row=2, column=0, columnspan=8, rowspan=10, pady=30, padx=30)
f.config(width=5)
self.tree = ttk.Treeview(f, selectmode="extended")
scbHDirSel =tk.Scrollbar(f, orient=Tkinter.HORIZONTAL, command=self.tree.xview)
scbVDirSel =tk.Scrollbar(f, orient=Tkinter.VERTICAL, command=self.tree.yview)
self.tree.configure(yscrollcommand=scbVDirSel.set, xscrollcommand=scbHDirSel.set)           
self.tree["columns"] = (self.columnListOutput)
self.tree.column("#0", width=40)
self.tree.heading("#0", text='SrNo', anchor='w')
self.tree.grid(row=2, column=0, sticky=Tkinter.NSEW,in_=f, columnspan=10, rowspan=10)
scbVDirSel.grid(row=2, column=10, rowspan=10, sticky=Tkinter.NS, in_=f)
scbHDirSel.grid(row=14, column=0, rowspan=2, sticky=Tkinter.EW,in_=f)
f.rowconfigure(0, weight=1)
f.columnconfigure(0, weight=1)

Maven is not working in Java 8 when Javadoc tags are incomplete

The best solution would be to fix the javadoc errors. If for some reason that is not possible (ie: auto generated source code) then you can disable this check.

DocLint is a new feature in Java 8, which is summarized as:

Provide a means to detect errors in Javadoc comments early in the development cycle and in a way that is easily linked back to the source code.

This is enabled by default, and will run a whole lot of checks before generating Javadocs. You need to turn this off for Java 8 as specified in this thread. You'll have to add this to your maven configuration:

<profiles>
  <profile>
    <id>java8-doclint-disabled</id>
    <activation>
      <jdk>[1.8,)</jdk>
    </activation>
    <properties>
      <javadoc.opts>-Xdoclint:none</javadoc.opts>
    </properties>
  </profile>
</profiles>
<build>
  <plugins>
    <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-javadoc-plugin</artifactId>
        <version>2.9</version>
        <executions>
            <execution>
                <id>attach-javadocs</id>
                <goals>
                    <goal>jar</goal>
                </goals>
                <configuration>
                    <additionalparam>${javadoc.opts}</additionalparam>
                </configuration>
            </execution>
        </executions>
    </plugin>
    <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-site-plugin</artifactId>
        <version>3.3</version>
        <configuration>
          <reportPlugins>
            <plugin>
              <groupId>org.apache.maven.plugins</groupId>
              <artifactId>maven-javadoc-plugin</artifactId>
              <configuration>
                <additionalparam>${javadoc.opts}</additionalparam>
              </configuration>
            </plugin>
          </reportPlugins>
        </configuration>
      </plugin>
   </plugins>
</build>

For maven-javadoc-plugin 3.0.0+: Replace

<additionalparam>-Xdoclint:none</additionalparam>

with

<doclint>none</doclint>

Using LINQ to group by multiple properties and sum

Use the .Select() after grouping:

var agencyContracts = _agencyContractsRepository.AgencyContracts
    .GroupBy(ac => new
                   {
                       ac.AgencyContractID, // required by your view model. should be omited
                                            // in most cases because group by primary key
                                            // makes no sense.
                       ac.AgencyID,
                       ac.VendorID,
                       ac.RegionID
                   })
    .Select(ac => new AgencyContractViewModel
                   {
                       AgencyContractID = ac.Key.AgencyContractID,
                       AgencyId = ac.Key.AgencyID,
                       VendorId = ac.Key.VendorID,
                       RegionId = ac.Key.RegionID,
                       Amount = ac.Sum(acs => acs.Amount),
                       Fee = ac.Sum(acs => acs.Fee)
                   });

fatal error LNK1169: one or more multiply defined symbols found in game programming

You can't put variable definitions in header files, as these will then be a part of all source file you include the header into.

The #pragma once is just to protect against multiple inclusions in the same source file, not against multiple inclusions in multiple source files.

You could declare the variables as extern in the header file, and then define them in a single source file. Or you could declare the variables as const in the header file and then the compiler and linker will manage it.

How to convert ActiveRecord results into an array of hashes

as_json

You should use as_json method which converts ActiveRecord objects to Ruby Hashes despite its name

tasks_records = TaskStoreStatus.all
tasks_records = tasks_records.as_json

# You can now add new records and return the result as json by calling `to_json`

tasks_records << TaskStoreStatus.last.as_json
tasks_records << { :task_id => 10, :store_name => "Koramanagala", :store_region => "India" }
tasks_records.to_json

serializable_hash

You can also convert any ActiveRecord objects to a Hash with serializable_hash and you can convert any ActiveRecord results to an Array with to_a, so for your example :

tasks_records = TaskStoreStatus.all
tasks_records.to_a.map(&:serializable_hash)

And if you want an ugly solution for Rails prior to v2.3

JSON.parse(tasks_records.to_json) # please don't do it

How to handle floats and decimal separators with html5 input type number

When you call $("#my_input").val(); it returns as string variable. So use parseFloat and parseIntfor converting. When you use parseFloat your desktop or phone ITSELF understands the meaning of variable.

And plus you can convert a float to string by using toFixed which has an argument the count of digits as below:

var i = 0.011;
var ss = i.toFixed(2); //It returns 0.01

UL has margin on the left

by default <UL/> contains default padding

therefore try adding style to padding:0px in css class or inline css

Way to read first few lines for pandas dataframe

I think you can use the nrows parameter. From the docs:

nrows : int, default None

    Number of rows of file to read. Useful for reading pieces of large files

which seems to work. Using one of the standard large test files (988504479 bytes, 5344499 lines):

In [1]: import pandas as pd

In [2]: time z = pd.read_csv("P00000001-ALL.csv", nrows=20)
CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
Wall time: 0.00 s

In [3]: len(z)
Out[3]: 20

In [4]: time z = pd.read_csv("P00000001-ALL.csv")
CPU times: user 27.63 s, sys: 1.92 s, total: 29.55 s
Wall time: 30.23 s

How to change line width in ggplot?

Whilst @Didzis has the correct answer, I will expand on a few points

Aesthetics can be set or mapped within a ggplot call.

  • An aesthetic defined within aes(...) is mapped from the data, and a legend created.

  • An aesthetic may also be set to a single value, by defining it outside aes().

As far as I can tell, what you want is to set size to a single value, not map within the call to aes()

When you call aes(size = 2) it creates a variable called `2` and uses that to create the size, mapping it from a constant value as it is within a call to aes (thus it appears in your legend).

Using size = 1 (and without reg_labeller which is perhaps defined somewhere in your script)

Figure29 +
    geom_line(aes(group=factor(tradlib)),size=1) +
    facet_grid(regionsFull~., scales="free_y") +
    scale_colour_brewer(type = "div") +
    theme(axis.text.x = element_text(
          colour = 'black', angle = 90, size = 13,
          hjust = 0.5, vjust = 0.5),axis.title.x=element_blank()) +
    ylab("FSI (%Change)") +
    theme(axis.text.y = element_text(colour = 'black', size = 12), 
          axis.title.y = element_text(size = 12, 
          hjust = 0.5, vjust = 0.2)) + 
    theme(strip.text.y = element_text(size = 11, hjust = 0.5,
          vjust =    0.5, face = 'bold'))

enter image description here

and with size = 2

 Figure29 + 
     geom_line(aes(group=factor(tradlib)),size=2) +
     facet_grid(regionsFull~., scales="free_y") + 
     scale_colour_brewer(type = "div") +
     theme(axis.text.x = element_text(colour = 'black', angle = 90,
          size = 13, hjust = 0.5, vjust = 
          0.5),axis.title.x=element_blank()) + 
     ylab("FSI (%Change)") +
     theme(axis.text.y = element_text(colour = 'black', size = 12),
          axis.title.y = element_text(size = 12,
          hjust = 0.5, vjust = 0.2)) + 
      theme(strip.text.y = element_text(size = 11, hjust = 0.5,
          vjust = 0.5, face = 'bold'))

enter image description here

You can now define the size to work appropriately with the final image size and device type.

Saving to CSV in Excel loses regional date format

A not so scalable fix that I used for this is to copy the data to a plain text editor, convert the cells to text and then copy the data back to the spreadsheet.

Can I add background color only for padding?

You can't set colour of the padding.

You will have to create a wrapper element with the desired background colour. Add border to this element and set it's padding.

Look here for an example: http://jsbin.com/abanek/1/edit

error code 1292 incorrect date value mysql

I happened to be working in localhost , in windows 10, using WAMP, as it turns out, Wamp has a really accessible configuration interface to change the MySQL configuration. You just need to go to the Wamp panel, then to MySQL, then to settings and change the mode to sql-mode: none.(essentially disabling the strict mode) The following picture illustrates this.

enter image description here

Exception is: InvalidOperationException - The current type, is an interface and cannot be constructed. Are you missing a type mapping?

I had this problem, and the cause was that I had not added the Microsoft.Owin.Host.SystemWeb NuGet package to my project. Although the code in my startup class was correct, it was not being executed.

So if you're trying to solve this problem, put a breakpoint in the code where you do the Unity registrations. If you don't hit it, your dependency injection isn't going to work.

Making interface implementations async

Neither of these options is correct. You're trying to implement a synchronous interface asynchronously. Don't do that. The problem is that when DoOperation() returns, the operation won't be complete yet. Worse, if an exception happens during the operation (which is very common with IO operations), the user won't have a chance to deal with that exception.

What you need to do is to modify the interface, so that it is asynchronous:

interface IIO
{
    Task DoOperationAsync(); // note: no async here
}

class IOImplementation : IIO
{
    public async Task DoOperationAsync()
    {
        // perform the operation here
    }
}

This way, the user will see that the operation is async and they will be able to await it. This also pretty much forces the users of your code to switch to async, but that's unavoidable.

Also, I assume using StartNew() in your implementation is just an example, you shouldn't need that to implement asynchronous IO. (And new Task() is even worse, that won't even work, because you don't Start() the Task.)

Codeigniter unset session

answering to your question:

How can I destroy or unset the value of the session?

I can help you by this:

$this->session->unset_userdata('some_name');

and for multiple data you can:

$array_items = array('username' => '', 'email' => '');

$this->session->unset_userdata($array_items);

and to destroy the session:

$this->session->sess_destroy();

Now for the on page change part (on the top of my mind):

you can set the config "anchor_class" of the paginator equal to the classname you want.

after that just check it with jquery onclick for that class which will send a head up to the controller function that will unset the user session.

Google Maps v2 - set both my location and zoom in

You also could set both parameters like,

mMap.moveCamera( CameraUpdateFactory.newLatLngZoom(new LatLng(21.000000, -101.400000) ,4) );

This locates your map on a specific position and zoom. I use this on the setting up my map.

Visual Studio Expand/Collapse keyboard shortcuts

As you can see, there are several ways to achieve this.

I personally use:

Expand all: CTRL + M + L

Collapse all: CTRL + M + O

Bonus:

Expand/Collapse on cursor location: CTRL + M + M

java.lang.ClassNotFoundException: oracle.jdbc.driver.OracleDriver

I had the same problem but was able to fix it by doing the following:

Right-click on the project -> Properties, then add the JAR (odjbc6 or 14) file in the deployment assembly.

AngularJS - value attribute for select

If the model specified for the drop down does not exist then angular will generate an empty options element. So you will have to explicitly specify the model on the select like this:

<select ng-model="regions[index]" ng-options="....">

Refer to the following as it has been answered before:

Why does AngularJS include an empty option in select? and this fiddle

Update: Try this instead:

<select ng-model="regions[index].code" ng-options="i.code as i.name for i in regions">
</select>

or

<select ng-model="regions[2]" ng-options="r.name for r in regions">
</select>

Note that there is no empty options element in the select.

Find number of decimal places in decimal value regardless of culture

I use the following mechanism in my code

  public static int GetDecimalLength(string tempValue)
    {
        int decimalLength = 0;
        if (tempValue.Contains('.') || tempValue.Contains(','))
        {
            char[] separator = new char[] { '.', ',' };
            string[] tempstring = tempValue.Split(separator);

            decimalLength = tempstring[1].Length;
        }
        return decimalLength;
    }

decimal input=3.376; var instring=input.ToString();

call GetDecimalLength(instring)

Array String Declaration

As Tr?n Si Long suggested, use

String[] mStrings = new String[title.length];

And replace string concatation with proper parenthesis.

mStrings[i] = (urlbase + (title[i].replaceAll("[^a-zA-Z]", ""))).toLowerCase() + imgSel;

Try this. If it's problem due to concatation, it will be resolved with proper brackets. Hope it helps.

If my interface must return Task what is the best way to have a no-operation implementation?

Task.Delay(0) as in the accepted answer was a good approach, as it is a cached copy of a completed Task.

As of 4.6 there's now Task.CompletedTask which is more explicit in its purpose, but not only does Task.Delay(0) still return a single cached instance, it returns the same single cached instance as does Task.CompletedTask.

The cached nature of neither is guaranteed to remain constant, but as implementation-dependent optimisations that are only implementation-dependent as optimisations (that is, they'd still work correctly if the implementation changed to something that was still valid) the use of Task.Delay(0) was better than the accepted answer.

Plot yerr/xerr as shaded region rather than error bars

This is basically the same answer provided by Evert, but extended to show-off some cool options of fill_between

enter image description here

from matplotlib import pyplot as pl
import numpy as np

pl.clf()
pl.hold(1)

x = np.linspace(0, 30, 100)
y = np.sin(x) * 0.5
pl.plot(x, y, '-k')


x = np.linspace(0, 30, 30)
y = np.sin(x/6*np.pi)
error = np.random.normal(0.1, 0.02, size=y.shape) +.1
y += np.random.normal(0, 0.1, size=y.shape)

pl.plot(x, y, 'k', color='#CC4F1B')
pl.fill_between(x, y-error, y+error,
    alpha=0.5, edgecolor='#CC4F1B', facecolor='#FF9848')

y = np.cos(x/6*np.pi)    
error = np.random.rand(len(y)) * 0.5
y += np.random.normal(0, 0.1, size=y.shape)
pl.plot(x, y, 'k', color='#1B2ACC')
pl.fill_between(x, y-error, y+error,
    alpha=0.2, edgecolor='#1B2ACC', facecolor='#089FFF',
    linewidth=4, linestyle='dashdot', antialiased=True)



y = np.cos(x/6*np.pi)  + np.sin(x/3*np.pi)  
error = np.random.rand(len(y)) * 0.5
y += np.random.normal(0, 0.1, size=y.shape)
pl.plot(x, y, 'k', color='#3F7F4C')
pl.fill_between(x, y-error, y+error,
    alpha=1, edgecolor='#3F7F4C', facecolor='#7EFF99',
    linewidth=0)



pl.show()

Saving image to file

You can save image , save the file in your current directory application and move the file to any directory .

 Bitmap btm = new Bitmap(image.width,image.height);
    Image img = btm;
                        img.Save(@"img_" + x + ".jpg", System.Drawing.Imaging.ImageFormat.Jpeg);
                        FileInfo img__ = new FileInfo(@"img_" + x + ".jpg");
                        img__.MoveTo("myVideo\\img_" + x + ".jpg");

How can I iterate JSONObject to get individual items

How about this?

JSONObject jsonObject = new JSONObject           (YOUR_JSON_STRING);
JSONObject ipinfo     = jsonObject.getJSONObject ("ipinfo");
String     ip_address = ipinfo.getString         ("ip_address");
JSONObject location   = ipinfo.getJSONObject     ("Location");
String     latitude   = location.getString       ("latitude");
System.out.println (latitude);

This sample code using "org.json.JSONObject"

How to ignore the certificate check when ssl

Expressed explicitly ...

ServicePointManager.ServerCertificateValidationCallback += new System.Net.Security.RemoteCertificateValidationCallback(CertCheck);

private static bool CertCheck(object sender, X509Certificate cert,
X509Chain chain, System.Net.Security.SslPolicyErrors error)
{
    return true;
}

Redirect form to different URL based on select option element

you can use this simple way

<select onchange="location = this.value;">
                <option value="/finished">Finished</option>
                <option value="/break">Break</option>
                <option value="/issue">Issues</option>
                <option value="/downtime">Downtime</option>
</select>

will redirect to route url you can direct to .html page or direct to some link just change value in option.

How to select all instances of selected region in Sublime Text

Even though there are multiple answers, there is an issue using this approach. It selects all the text that matches, not only the whole words like variables.

As per "Sublime Text: Select all instances of a variable and edit variable name" and the answer in "Sublime Text: Select all instances of a variable and edit variable name", we have to start with a empty selection. That is, start using the shortcut Alt+F3 which would help selecting only the whole words.

StringIO in Python3

I hope this will meet your requirement

import PyPDF4
import io

pdfFile = open(r'test.pdf', 'rb')
pdfReader = PyPDF4.PdfFileReader(pdfFile)
pageObj = pdfReader.getPage(1)
pagetext = pageObj.extractText()

for line in io.StringIO(pagetext):
    print(line)

How to set a default Value of a UIPickerView

I too had this problem. But apparently there is an issue of the order of method calls. You must call:

[self.picker selectRow:2 inComponent:0 animated:YES];

after calling

[self.view addSubview:self.picker];

When to use @QueryParam vs @PathParam

As theon noted, REST is not a standard. However, if you are looking to implement a standards based URI convention, you might consider the oData URI convention. Ver 4 has been approved as an OASIS standard and libraries exists for oData for various languages including Java via Apache Olingo. Don't let the fact that it's a spawn from Microsoft put you off since it's gained support from other industry player's as well, which include Red Hat, Citrix, IBM, Blackberry, Drupal, Netflix Facebook and SAP

More adopters are listed here

How do I replace text in a selection?

You can use ctrl+F to find the text.
ctrl+h to enter the replacement text. Then ctrl+shift+h to replace the current selected text and move to next matched text.

This is for windows. But you can check in mac also for which you might want to check the key bindings under Preferences.

How do I trigger a macro to run after a new mail is received in Outlook?

Try something like this inside ThisOutlookSession:

Private Sub Application_NewMail()
    Call Your_main_macro
End Sub

My outlook vba just fired when I received an email and had that application event open.

Edit: I just tested a hello world msg box and it ran after being called in the application_newmail event when an email was received.

Using JsonConvert.DeserializeObject to deserialize Json to a C# POCO class

You could create a JsonConverter. See here for an example thats similar to your question.

How to convert a NumPy array to PIL image applying matplotlib colormap

Quite a busy one-liner, but here it is:

  1. First ensure your NumPy array, myarray, is normalised with the max value at 1.0.
  2. Apply the colormap directly to myarray.
  3. Rescale to the 0-255 range.
  4. Convert to integers, using np.uint8().
  5. Use Image.fromarray().

And you're done:

from PIL import Image
from matplotlib import cm
im = Image.fromarray(np.uint8(cm.gist_earth(myarray)*255))

with plt.savefig():

Enter image description here

with im.save():

Enter image description here

Error message "Forbidden You don't have permission to access / on this server"

Check exactly where you are putting your files, don't nest them in the Documents folder.

For instance I made the mistake of putting my code in the Documents folder of as mentioned this isn't going to work because Documents is explicitly only available to YOU and not APACHE. Try moving it up one directory and you may not see this issue.

Move folder from:

/Users/YOURUSERNAME/Documents/code

To here: /Users/YOURUSERNAME/code

Make a table fill the entire window

Try using

<html style="height: 100%;">
    <body style="height: 100%;">
        <table style="height: 100%;">
        ...

in order to force all parents of the table element to expand over the available vertical space (which will eliminate the need to use absolute positioning).

Works in Firefox 28, IE 11 and Chromium 34 (and hence probably Google Chrome as well)

Source: http://www.dailycoding.com/posts/howtoset100tableheightinhtml.aspx

What does this GCC error "... relocation truncated to fit..." mean?

I ran into this problem while building a program that requires a huge amount of stack space (over 2 GiB). The solution was to add the flag -mcmodel=medium, which is supported by both GCC and Intel compilers.

Get JSONArray without array name?

Here is a solution under 19API lvl:

  • First of all. Make a Gson obj. --> Gson gson = new Gson();

  • Second step is get your jsonObj as String with StringRequest(instead of JsonObjectRequest)

  • The last step to get JsonArray...

YoursObjArray[] yoursObjArray = gson.fromJson(response, YoursObjArray[].class);

In SQL Server, what does "SET ANSI_NULLS ON" mean?

Set ANSI NULLS OFF will make NULL = NULL comparision return true. EG :

        SET ANSI_NULLS OFF
        select * from sys.tables
        where principal_id = Null

will return some result as displayed below: zcwInvoiceDeliveryType 744547 NULL zcExpenseRptStatusTrack 2099048 NULL ZCVendorPermissions 2840564 NULL ZCWOrgLevelClientFee 4322525 NULL

While this query will not return any results:

        SET ANSI_NULLS ON 
        select * from sys.tables
        where principal_id = Null

The calling thread cannot access this object because a different thread owns it

I also found that System.Windows.Threading.Dispatcher.CurrentDispatcher.Invoke() is not always dispatcher of target control, just as dotNet wrote in his answer. I didn't had access to control's own dispatcher, so I used Application.Current.Dispatcher and it solved the problem.

How is TeamViewer so fast?

A bit late answer, but I suggest you have a look at a not well known project on codeplex called ConferenceXP

ConferenceXP is an open source research platform that provides simple, flexible, and extensible conferencing and collaboration using high-bandwidth networks and the advanced multimedia capabilities of Microsoft Windows. ConferenceXP helps researchers and educators develop innovative applications and solutions that feature broadcast-quality audio and video in support of real-time distributed collaboration and distance learning environments.

Full source (it's huge!) is provided. It implements the RTP protocol.

ORA-01882: timezone region not found

I had this problem when running automated tests from a continuous integration server. I tried adding the VM argument "-Duser.timezone=GMT" to the build parameters, but that didn't solve the problem. However, adding the environment variable "TZ=GMT" did fix it for me.

YouTube Video Embedded via iframe Ignoring z-index?

wmode=opaque or transparent at the beginning of my query string didnt solve anything. This issue for me only occurs on Chrome, and not across even all computers. Just one cpu. It occurs in vimeo embeds as well, and possibly others.

My solution to to attach to the 'shown' and 'hidden' event of the bootstrap modals I am using, add a class which sets the iframe to 1x1 pixels, and remove the class when the modal closes. Seems like it works and is simple to implement.

How do I free memory in C?

You have to free() the allocated memory in exact reverse order of how it was allocated using malloc().

Note that You should free the memory only after you are done with your usage of the allocated pointers.

memory allocation for 1D arrays:

    buffer = malloc(num_items*sizeof(double));

memory deallocation for 1D arrays:

    free(buffer);

memory allocation for 2D arrays:

    double **cross_norm=(double**)malloc(150 * sizeof(double *));
    for(i=0; i<150;i++)
    {
        cross_norm[i]=(double*)malloc(num_items*sizeof(double));
    }

memory deallocation for 2D arrays:

    for(i=0; i<150;i++)
    {
        free(cross_norm[i]);
    }

    free(cross_norm);

Installed Ruby 1.9.3 with RVM but command line doesn't show ruby -v

You have broken version of RVM. Ubuntu does something to RVM that produces lots of errors, the only safe way of fixing for now is to:

sudo apt-get --purge remove ruby-rvm
sudo rm -rf /usr/share/ruby-rvm /etc/rvmrc /etc/profile.d/rvm.sh

open new terminal and validate environment is clean from old RVM settings (should be no output):

env | grep rvm

if there was output, try to open new terminal, if it does not help then restart your computer.

install RVM:

\curl -L https://get.rvm.io | 
  bash -s stable --ruby --autolibs=enable --auto-dotfiles

If you find you need some hand-holding, take a look at Installing Ruby on Ubuntu 12.04, which gives a bit more explanation.

How to insert data to MySQL having auto incremented primary key?

Check out this post

According to it

No value was specified for the AUTO_INCREMENT column, so MySQL assigned sequence numbers automatically. You can also explicitly assign NULL or 0 to the column to generate sequence numbers.

Best way to resolve file path too long exception

You can create a symbolic link with a shorter directory. First open command line for example by Shift + RightClick in your desired folder with a shorter path (you may have to run it as administrator).

Then type with relative or absolute paths:

mklink ShortPath\To\YourLinkedSolution C:\Path\To\Your\Solution /D

And then start the Solution from the shorter path. The advantage here is: You don't have to move anything.

Execute Python script via crontab

Put your script in a file foo.py starting with

#!/usr/bin/python

Then give execute permission to that script using

chmod a+x foo.py

and use the full path of your foo.py file in your crontab.

See documentation of execve(2) which is handling the shebang.

Get latitude and longitude automatically using php, API

//add urlencode to your address
$address = urlencode("technopark, Trivandrun, kerala,India");
$region = "IND";
$json = file_get_contents("http://maps.google.com/maps/api/geocode/json?address=$address&sensor=false&region=$region");

echo $json;

$decoded = json_decode($json);

print_r($decoded);

MySQL select statement with CASE or IF ELSEIF? Not sure how to get the result

Try this query -

SELECT 
  t2.company_name,
  t2.expose_new,
  t2.expose_used,
  t1.title,
  t1.seller,
  t1.status,
  CASE status
      WHEN 'New' THEN t2.expose_new
      WHEN 'Used' THEN t2.expose_used
      ELSE NULL
  END as 'expose'
FROM
  `products` t1
JOIN manufacturers t2
  ON
    t2.id = t1.seller
WHERE
  t1.seller = 4238

Why are elementwise additions much faster in separate loops than in a combined loop?

The second loop involves a lot less cache activity, so it's easier for the processor to keep up with the memory demands.

How to crop a CvMat in OpenCV?

I know this question is already solved.. but there is a very easy way to crop. you can just do it in one line-

Mat cropedImage = fullImage(Rect(X,Y,Width,Height));

String Pattern Matching In Java

That's just a matter of String.contains:

if (input.contains("{item}"))

If you need to know where it occurs, you can use indexOf:

int index = input.indexOf("{item}");
if (index != -1) // -1 means "not found"
{
    ...
}

That's fine for matching exact strings - if you need real patterns (e.g. "three digits followed by at most 2 letters A-C") then you should look into regular expressions.

EDIT: Okay, it sounds like you do want regular expressions. You might want something like this:

private static final Pattern URL_PATTERN =
    Pattern.compile("/\\{[a-zA-Z0-9]+\\}/");

...

if (URL_PATTERN.matches(input).find())

Validation failed for one or more entities. See 'EntityValidationErrors' property for more details

The answer from @Slauma is really great but I found that it didnt't work when a ComplexType property was invalid.

For example, say you have a property Phone of the complex type PhoneNumber. If the AreaCode property is invalid, the property name in ve.PropertyNames is "Phone.AreaCode". This causes the call to eve.Entry.CurrentValues<object>(ve.PropertyName) to fail.

To fix this, you can split the property name at each ., then recurse through the resulting array of property names. Finally, when you arrive at the bottom of the chain, you can simply return the value of the property.

Below is @Slauma's FormattedDbEntityValidationException class with support for ComplexTypes.

Enjoy!

[Serializable]
public class FormattedDbEntityValidationException : Exception
{
    public FormattedDbEntityValidationException(DbEntityValidationException innerException) :
        base(null, innerException)
    {
    }

    public override string Message
    {
        get
        {
            var innerException = InnerException as DbEntityValidationException;
            if (innerException == null) return base.Message;

            var sb = new StringBuilder();

            sb.AppendLine();
            sb.AppendLine();
            foreach (var eve in innerException.EntityValidationErrors)
            {
                sb.AppendLine(string.Format("- Entity of type \"{0}\" in state \"{1}\" has the following validation errors:",
                    eve.Entry.Entity.GetType().FullName, eve.Entry.State));
                foreach (var ve in eve.ValidationErrors)
                {
                    object value;
                    if (ve.PropertyName.Contains("."))
                    {
                        var propertyChain = ve.PropertyName.Split('.');
                        var complexProperty = eve.Entry.CurrentValues.GetValue<DbPropertyValues>(propertyChain.First());
                        value = GetComplexPropertyValue(complexProperty, propertyChain.Skip(1).ToArray());
                    }
                    else
                    {
                        value = eve.Entry.CurrentValues.GetValue<object>(ve.PropertyName);
                    }
                    sb.AppendLine(string.Format("-- Property: \"{0}\", Value: \"{1}\", Error: \"{2}\"",
                        ve.PropertyName,
                        value,
                        ve.ErrorMessage));
                }
            }
            sb.AppendLine();

            return sb.ToString();
        }
    }

    private static object GetComplexPropertyValue(DbPropertyValues propertyValues, string[] propertyChain)
    {
        var propertyName = propertyChain.First();
        return propertyChain.Count() == 1 
            ? propertyValues[propertyName] 
            : GetComplexPropertyValue((DbPropertyValues)propertyValues[propertyName], propertyChain.Skip(1).ToArray());
    }
}

How to set a DateTime variable in SQL Server 2008?

You Should Try This Way :

  DECLARE @TEST DATE
  SET @TEST =  '05/09/2013'
  PRINT @TEST

Oracle SQL: Use sequence in insert with Select Statement

I tested and the script run ok!

INSERT INTO HISTORICAL_CAR_STATS (HISTORICAL_CAR_STATS_ID, YEAR,MONTH,MAKE,MODEL,REGION,AVG_MSRP,COUNT) 
WITH DATA AS
(
    SELECT '2010' YEAR,'12' MONTH ,'ALL' MAKE,'ALL' MODEL,REGION,sum(AVG_MSRP*COUNT)/sum(COUNT) AVG_MSRP,sum(Count) COUNT
    FROM HISTORICAL_CAR_STATS
    WHERE YEAR = '2010' AND MONTH = '12'
    AND MAKE != 'ALL' GROUP BY REGION
)
SELECT MY_SEQ.NEXTVAL, YEAR,MONTH,MAKE,MODEL,REGION,AVG_MSRP,COUNT
FROM DATA;

you can read this article to understand more! http://www.orafaq.com/wiki/ORA-02287

How to find Control in TemplateField of GridView?

Try this:

foreach(GridViewRow row in GridView1.Rows) {
    if(row.RowType == DataControlRowType.DataRow) {
        HyperLink myHyperLink = row.FindControl("myHyperLinkID") as HyperLink;
    }
}

If you are handling RowDataBound event, it's like this:

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if(e.Row.RowType == DataControlRowType.DataRow)
    {
        HyperLink myHyperLink = e.Row.FindControl("myHyperLinkID") as HyperLink;
    }
}

Creating a singleton in Python

Using a function attribute is also very simple

def f():
    if not hasattr(f, 'value'):
        setattr(f, 'value', singletonvalue)
    return f.value

How to create an array for JSON using PHP?

Simple: Just create a (nested) PHP array and call json_encode on it. Numeric arrays translate into JSON lists ([]), associative arrays and PHP objects translate into objects ({}). Example:

$a = array(
        array('foo' => 'bar'),
        array('foo' => 'baz'));
$json = json_encode($a);

Gives you:

[{"foo":"bar"},{"foo":"baz"}]

Convert SVG to PNG in Python

Try this: http://cairosvg.org/

The site says:

CairoSVG is written in pure python and only depends on Pycairo. It is known to work on Python 2.6 and 2.7.

Update November 25, 2016:

2.0.0 is a new major version, its changelog includes:

  • Drop Python 2 support

ggplot2 plot without axes, legends, etc

As per my comment in Chase's answer, you can remove a lot of this stuff using element_blank:

dat <- data.frame(x=runif(10),y=runif(10))

p <- ggplot(dat, aes(x=x, y=y)) + 
        geom_point() +
        scale_x_continuous(expand=c(0,0)) + 
        scale_y_continuous(expand=c(0,0))   

p + theme(axis.line=element_blank(),axis.text.x=element_blank(),
          axis.text.y=element_blank(),axis.ticks=element_blank(),
          axis.title.x=element_blank(),
          axis.title.y=element_blank(),legend.position="none",
          panel.background=element_blank(),panel.border=element_blank(),panel.grid.major=element_blank(),
          panel.grid.minor=element_blank(),plot.background=element_blank())

It looks like there's still a small margin around the edge of the resulting .png when I save this. Perhaps someone else knows how to remove even that component.

(Historical note: Since ggplot2 version 0.9.2, opts has been deprecated. Instead use theme() and replace theme_blank() with element_blank().)

Using grep to search for hex strings in a file

I just used this:

grep -c $'\x0c' filename

To search for and count a page control character in the file..

So to include an offset in the output:

grep -b -o $'\x0c' filename | less

I am just piping the result to less because the character I am greping for does not print well and the less displays the results cleanly. Output example:

21:^L
23:^L
2005:^L

Remove an entire column from a data.frame in R

With this you can remove the column and store variable into another variable.

df = subset(data, select = -c(genome) )

XPath using starts-with function

Try this

//ITEM/*[starts-with(text(),'2552')]/following-sibling::*

GDB: Listing all mapped memory regions for a crashed process

In GDB 7.2:

(gdb) help info proc
Show /proc process information about any running process.
Specify any process id, or use the program being debugged by default.
Specify any of the following keywords for detailed info:
  mappings -- list of mapped memory regions.
  stat     -- list a bunch of random process info.
  status   -- list a different bunch of random process info.
  all      -- list all available /proc info.

You want info proc mappings, except it doesn't work when there is no /proc (such as during pos-mortem debugging).

Try maintenance info sections instead.

To compare two elements(string type) in XSLT?

First of all, the provided long code:

    <xsl:choose>
        <xsl:when test="OU_NAME='OU_ADDR1'">   --comparing two elements coming from XML             
            <!--remove if  adrees already contain  operating unit name <xsl:value-of select="OU_NAME"/> <fo:block/>-->
            <xsl:if test="OU_ADDR1 !='' ">
                <xsl:value-of select="OU_ADDR1"/>
                <fo:block/>
            </xsl:if>
            <xsl:if test="LE_ADDR2 !='' ">
                <xsl:value-of select="OU_ADDR2"/>
                <fo:block/>
            </xsl:if>
            <xsl:if test="LE_ADDR3 !='' ">
                <xsl:value-of select="OU_ADDR3"/>
                <fo:block/>
            </xsl:if>
            <xsl:if test="OU_TOWN_CITY !=''">
                <xsl:value-of select="OU_TOWN_CITY"/>,
                <fo:leader leader-pattern="space" leader-length="2.0pt"/>
            </xsl:if>
            <xsl:value-of select="OU_REGION2"/>
            <fo:leader leader-pattern="space" leader-length="3.0pt"/>
            <xsl:value-of select="OU_POSTALCODE"/>
            <fo:block/>
            <xsl:value-of select="OU_COUNTRY"/>
        </xsl:when>
        <xsl:otherwise>
            <xsl:value-of select="OU_NAME"/>
            <fo:block/>
            <xsl:if test="OU_ADDR1 !='' ">
                <xsl:value-of select="OU_ADDR1"/>
                <fo:block/>
            </xsl:if>
            <xsl:if test="LE_ADDR2 !='' ">
                <xsl:value-of select="OU_ADDR2"/>
                <fo:block/>
            </xsl:if>
            <xsl:if test="LE_ADDR3 !='' ">
                <xsl:value-of select="OU_ADDR3"/>
                <fo:block/>
            </xsl:if>
            <xsl:if test="OU_TOWN_CITY !=''">
                <xsl:value-of select="OU_TOWN_CITY"/>,
                <fo:leader leader-pattern="space" leader-length="2.0pt"/>
            </xsl:if>
            <xsl:value-of select="OU_REGION2"/>
            <fo:leader leader-pattern="space" leader-length="3.0pt"/>
            <xsl:value-of select="OU_POSTALCODE"/>
            <fo:block/>
            <xsl:value-of select="OU_COUNTRY"/>
        </xsl:otherwise>
    </xsl:choose>

is equivalent to this, much shorter code:

<xsl:if test="not(OU_NAME='OU_ADDR1)'">
              <xsl:value-of select="OU_NAME"/>
        </xsl:if>
            <xsl:if test="OU_ADDR1 !='' ">
                <xsl:value-of select="OU_ADDR1"/>
                <fo:block/>
            </xsl:if>
            <xsl:if test="LE_ADDR2 !='' ">
                <xsl:value-of select="OU_ADDR2"/>
                <fo:block/>
            </xsl:if>
            <xsl:if test="LE_ADDR3 !='' ">
                <xsl:value-of select="OU_ADDR3"/>
                <fo:block/>
            </xsl:if>
            <xsl:if test="OU_TOWN_CITY !=''">
                <xsl:value-of select="OU_TOWN_CITY"/>,
                <fo:leader leader-pattern="space" leader-length="2.0pt"/>
            </xsl:if>
            <xsl:value-of select="OU_REGION2"/>
            <fo:leader leader-pattern="space" leader-length="3.0pt"/>
            <xsl:value-of select="OU_POSTALCODE"/>
            <fo:block/>
            <xsl:value-of select="OU_COUNTRY"/>

Now, to your question:

how to compare two elements coming from xml as string

In Xpath 1.0 strings can be compared only for equality (or inequality), using the operator = and the function not() together with the operator =.

$str1 = $str2

evaluates to true() exactly when the string $str1 is equal to the string $str2.

not($str1 = $str2)

evaluates to true() exactly when the string $str1 is not equal to the string $str2.

There is also the != operator. It generally should be avoided because it has anomalous behavior whenever one of its operands is a node-set.

Now, the rules for comparing two element nodes are similar:

$el1 = $el2

evaluates to true() exactly when the string value of $el1 is equal to the string value of $el2.

not($el1 = $el2)

evaluates to true() exactly when the string value of $el1 is not equal to the string value of $el2.

However, if one of the operands of = is a node-set, then

 $ns = $str

evaluates to true() exactly when there is at least one node in the node-set $ns1, whose string value is equal to the string $str

$ns1 = $ns2

evaluates to true() exactly when there is at least one node in the node-set $ns1, whose string value is equal to the string value of some node from $ns2

Therefore, the expression:

OU_NAME='OU_ADDR1'

evaluates to true() only when there is at least one element child of the current node that is named OU_NAME and whose string value is the string 'OU_ADDR1'.

This is obviously not what you want!

Most probably you want:

OU_NAME=OU_ADDR1

This expression evaluates to true exactly there is at least one OU_NAME child of the current node and one OU_ADDR1 child of the current node with the same string value.

Finally, in XPath 2.0, strings can be compared also using the value comparison operators lt, le, eq, gt, ge and the inherited from XPath 1.0 general comparison operator =.

Trying to evaluate a value comparison operator when one or both of its arguments is a sequence of more than one item results in error.

How to view UTF-8 Characters in VIM or Gvim

On Windows gvim just select "Lucida Console" font.

UnicodeEncodeError: 'ascii' codec can't encode character u'\xef' in position 0: ordinal not in range(128)

The problem is that you're trying to print an unicode character to a possibly non-unicode terminal. You need to encode it with the 'replace option before printing it, e.g. print ch.encode(sys.stdout.encoding, 'replace').

How to load images dynamically (or lazily) when users scrolls them into view

There is a pretty nice infinite scroll plugin here

I've never programmed one myself, but I would imagine this is how it works.

  1. An event is bound to the the window scrolling

    $(window).scroll(myInfinteScrollFunction);
    
  2. The called function checks if scroll top is greater than the window size

    function myInfiniteScrollFunction() {  
        if($(window).scrollTop() == $(window).height())  
        makeAjaxRequest();  
    }
    
  3. An AJAX request is made, specifying which result # to start at, how many to grab, and any other parameters necessary for the data pull.

    $.ajax({
        type: "POST",
        url:  "myAjaxFile.php",
        data: {"resultNum": 30, "numPerPage": 50, "query": "interesting%20icons" },
        success: myInfiniteLoadFunction(msg)
    });
    
  4. The ajax returns some (most-likely JSON formatted) content, and passes them into the loadnig function.

Hope that makes sense.

Replace Div with another Div

HTML

<div id="replaceMe">i need to be replaced</div>
<div id="iamReplacement">i am replacement</div>

JavaScript

jQuery('#replaceMe').replaceWith(jQuery('#iamReplacement'));

Mutex example / tutorial?

I stumbled upon this post recently and think that it needs an updated solution for the standard library's c++11 mutex (namely std::mutex).

I've pasted some code below (my first steps with a mutex - I learned concurrency on win32 with HANDLE, SetEvent, WaitForMultipleObjects etc).

Since it's my first attempt with std::mutex and friends, I'd love to see comments, suggestions and improvements!

#include <condition_variable>
#include <mutex>
#include <algorithm>
#include <thread>
#include <queue>
#include <chrono>
#include <iostream>


int _tmain(int argc, _TCHAR* argv[])
{   
    // these vars are shared among the following threads
    std::queue<unsigned int>    nNumbers;

    std::mutex                  mtxQueue;
    std::condition_variable     cvQueue;
    bool                        m_bQueueLocked = false;

    std::mutex                  mtxQuit;
    std::condition_variable     cvQuit;
    bool                        m_bQuit = false;


    std::thread thrQuit(
        [&]()
        {
            using namespace std;            

            this_thread::sleep_for(chrono::seconds(5));

            // set event by setting the bool variable to true
            // then notifying via the condition variable
            m_bQuit = true;
            cvQuit.notify_all();
        }
    );


    std::thread thrProducer(
        [&]()
        {
            using namespace std;

            int nNum = 13;
            unique_lock<mutex> lock( mtxQuit );

            while ( ! m_bQuit )
            {
                while( cvQuit.wait_for( lock, chrono::milliseconds(75) ) == cv_status::timeout )
                {
                    nNum = nNum + 13 / 2;

                    unique_lock<mutex> qLock(mtxQueue);
                    cout << "Produced: " << nNum << "\n";
                    nNumbers.push( nNum );
                }
            }
        }   
    );

    std::thread thrConsumer(
        [&]()
        {
            using namespace std;
            unique_lock<mutex> lock(mtxQuit);

            while( cvQuit.wait_for(lock, chrono::milliseconds(150)) == cv_status::timeout )
            {
                unique_lock<mutex> qLock(mtxQueue);
                if( nNumbers.size() > 0 )
                {
                    cout << "Consumed: " << nNumbers.front() << "\n";
                    nNumbers.pop();
                }               
            }
        }
    );

    thrQuit.join();
    thrProducer.join();
    thrConsumer.join();

    return 0;
}

Zooming MKMapView to fit annotation pins?

I use this this code and works fine for me:

-(void)zoomToFitMapAnnotations:(MKMapView*)aMapView
{
    if([aMapView.annotations count] == 0)
        return;

    CLLocationCoordinate2D topLeftCoord;
    topLeftCoord.latitude = -90;
    topLeftCoord.longitude = 180;

    CLLocationCoordinate2D bottomRightCoord;
    bottomRightCoord.latitude = 90;
    bottomRightCoord.longitude = -180;

    for(MapViewAnnotation *annotation in mapView.annotations)
    {
        topLeftCoord.longitude = fmin(topLeftCoord.longitude, annotation.coordinate.longitude);
        topLeftCoord.latitude = fmax(topLeftCoord.latitude, annotation.coordinate.latitude);

        bottomRightCoord.longitude = fmax(bottomRightCoord.longitude, annotation.coordinate.longitude);
        bottomRightCoord.latitude = fmin(bottomRightCoord.latitude, annotation.coordinate.latitude);
    }

    MKCoordinateRegion region;
    region.center.latitude = topLeftCoord.latitude - (topLeftCoord.latitude - bottomRightCoord.latitude) * 0.5;
    region.center.longitude = topLeftCoord.longitude + (bottomRightCoord.longitude - topLeftCoord.longitude) * 0.5;
    region.span.latitudeDelta = fabs(topLeftCoord.latitude - bottomRightCoord.latitude) * 1.1; // Add a little extra space on the sides
    region.span.longitudeDelta = fabs(bottomRightCoord.longitude - topLeftCoord.longitude) * 1.1; // Add a little extra space on the sides

    region = [aMapView regionThatFits:region];
    [mapView setRegion:region animated:YES];
}

What is the meaning of CTOR?

It's just shorthand for "constructor" - and it's what the constructor is called in IL, too. For example, open up Reflector and look at a type and you'll see members called .ctor for the various constructors.

Why doesn't Mockito mock static methods?

If you need to mock a static method, it is a strong indicator for a bad design. Usually, you mock the dependency of your class-under-test. If your class-under-test refers to a static method - like java.util.Math#sin for example - it means the class-under-test needs exactly this implementation (of accuracy vs. speed for example). If you want to abstract from a concrete sinus implementation you probably need an Interface (you see where this is going to)?

sql server #region

Another option is

if your purpose is analyse your query, Notepad+ has useful automatic wrapper for Sql.

How to deserialize a list using GSON or another JSON library in Java?

Be careful using the answer provide by @DevNG. Arrays.asList() returns internal implementation of ArrayList that doesn't implement some useful methods like add(), delete(), etc. If you call them an UnsupportedOperationException will be thrown. In order to get real ArrayList instance you need to write something like this:

List<Video> = new ArrayList<>(Arrays.asList(videoArray));

How to get datas from List<Object> (Java)?

System.out.println("Element "+i+list.get(0));}

Should be

System.out.println("Element "+i+list.get(i));}

To use the JSF tags, you give the dataList value attribute a reference to your list of elements, and the var attribute is a local name for each element of that list in turn. Inside the dataList, you use properties of the object (getters) to output the information about that individual object:

<t:dataList id="myDataList" value="#{houseControlList}" var="element" rows="3" >
...
<t:outputText id="houseId" value="#{element.houseId}"/>
...
</t:dataList>

Google Maps: how to get country, state/province/region, city given a lat/long value?

 <div id="location"></div>
        <script>
            window.onload = function () {
                var startPos;
                var geoOptions = {
                    maximumAge: 5 * 60 * 1000,
                    timeout: 10 * 1000,
                    enableHighAccuracy: true
                }


                var geoSuccess = function (position) {
                    startPos = position;
                    geocodeLatLng(startPos.coords.latitude, startPos.coords.longitude);

                };
                var geoError = function (error) {
                    console.log('Error occurred. Error code: ' + error.code);
                    // error.code can be:
                    //   0: unknown error
                    //   1: permission denied
                    //   2: position unavailable (error response from location provider)
                    //   3: timed out
                };

                navigator.geolocation.getCurrentPosition(geoSuccess, geoError, geoOptions);
            };
            function geocodeLatLng(lat, lng) {
                var geocoder = new google.maps.Geocoder;
                var latlng = {lat: parseFloat(lat), lng: parseFloat(lng)};
                geocoder.geocode({'location': latlng}, function (results, status) {
                    if (status === 'OK') {
                        console.log(results)
                        if (results[0]) {
                            document.getElementById('location').innerHTML = results[0].formatted_address;
                            var street = "";
                            var city = "";
                            var state = "";
                            var country = "";
                            var zipcode = "";
                            for (var i = 0; i < results.length; i++) {
                                if (results[i].types[0] === "locality") {
                                    city = results[i].address_components[0].long_name;
                                    state = results[i].address_components[2].long_name;

                                }
                                if (results[i].types[0] === "postal_code" && zipcode == "") {
                                    zipcode = results[i].address_components[0].long_name;

                                }
                                if (results[i].types[0] === "country") {
                                    country = results[i].address_components[0].long_name;

                                }
                                if (results[i].types[0] === "route" && street == "") {

                                    for (var j = 0; j < 4; j++) {
                                        if (j == 0) {
                                            street = results[i].address_components[j].long_name;
                                        } else {
                                            street += ", " + results[i].address_components[j].long_name;
                                        }
                                    }

                                }
                                if (results[i].types[0] === "street_address") {
                                    for (var j = 0; j < 4; j++) {
                                        if (j == 0) {
                                            street = results[i].address_components[j].long_name;
                                        } else {
                                            street += ", " + results[i].address_components[j].long_name;
                                        }
                                    }

                                }
                            }
                            if (zipcode == "") {
                                if (typeof results[0].address_components[8] !== 'undefined') {
                                    zipcode = results[0].address_components[8].long_name;
                                }
                            }
                            if (country == "") {
                                if (typeof results[0].address_components[7] !== 'undefined') {
                                    country = results[0].address_components[7].long_name;
                                }
                            }
                            if (state == "") {
                                if (typeof results[0].address_components[6] !== 'undefined') {
                                    state = results[0].address_components[6].long_name;
                                }
                            }
                            if (city == "") {
                                if (typeof results[0].address_components[5] !== 'undefined') {
                                    city = results[0].address_components[5].long_name;
                                }
                            }

                            var address = {
                                "street": street,
                                "city": city,
                                "state": state,
                                "country": country,
                                "zipcode": zipcode,
                            };

                            document.getElementById('location').innerHTML = document.getElementById('location').innerHTML + "<br/>Street : " + address.street + "<br/>City : " + address.city + "<br/>State : " + address.state + "<br/>Country : " + address.country + "<br/>zipcode : " + address.zipcode;
                            console.log(address);
                        } else {
                            window.alert('No results found');
                        }
                    } else {
                        window.alert('Geocoder failed due to: ' + status);
                    }
                });
            }
        </script>

        <script async defer
                src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY">
        </script>

AttributeError: 'module' object has no attribute 'urlopen'

To get 'dataX = urllib.urlopen(url).read()' working in python3 (this would have been correct for python2) you must just change 2 little things.

1: The urllib statement itself (add the .request in the middle):

dataX = urllib.request.urlopen(url).read()

2: The import statement preceding it (change from 'import urlib' to:

import urllib.request

And it should work in python3 :)

Peak detection in a 2D array

I am not sure this answers the question, but it seems like you can just look for the n highest peaks that don't have neighbors.

Here is the gist. Note that it's in Ruby, but the idea should be clear.

require 'pp'

NUM_PEAKS = 5
NEIGHBOR_DISTANCE = 1

data = [[1,2,3,4,5],
        [2,6,4,4,6],
        [3,6,7,4,3],
       ]

def tuples(matrix)
  tuples = []
  matrix.each_with_index { |row, ri|
    row.each_with_index { |value, ci|
      tuples << [value, ri, ci]
    }
  }
  tuples
end

def neighbor?(t1, t2, distance = 1)
  [1,2].each { |axis|
    return false if (t1[axis] - t2[axis]).abs > distance
  }
  true
end

# convert the matrix into a sorted list of tuples (value, row, col), highest peaks first
sorted = tuples(data).sort_by { |tuple| tuple.first }.reverse

# the list of peaks that don't have neighbors
non_neighboring_peaks = []

sorted.each { |candidate|
  # always take the highest peak
  if non_neighboring_peaks.empty?
    non_neighboring_peaks << candidate
    puts "took the first peak: #{candidate}"
  else
    # check that this candidate doesn't have any accepted neighbors
    is_ok = true
    non_neighboring_peaks.each { |accepted|
      if neighbor?(candidate, accepted, NEIGHBOR_DISTANCE)
        is_ok = false
        break
      end
    }
    if is_ok
      non_neighboring_peaks << candidate
      puts "took #{candidate}"
    else
      puts "denied #{candidate}"
    end
  end
}

pp non_neighboring_peaks

Class is inaccessible due to its protection level

It may also be the case that the library containing the class in question is not properly signed with a strong name.

How to extract text from a PDF?

Since today I know it: the best thing for text extraction from PDFs is TET, the text extraction toolkit. TET is part of the PDFlib.com family of products.

PDFlib.com is Thomas Merz's company. In case you don't recognize his name: Thomas Merz is the author of the "PostScript and PDF Bible".

TET's first incarnation is a library. That one can probably do everything Budda006 wanted, including positional information about every element on the page. Oh, and it can also extract images. It recombines images which are fragmented into pieces.

pdflib.com also offers another incarnation of this technology, the TET plugin for Acrobat. And the third incarnation is the PDFlib TET iFilter. This is a standalone tool for user desktops. Both these are free (as in beer) to use for private, non-commercial purposes.

And it's really powerful. Way better than Adobe's own text extraction. It extracted text for me where other tools (including Adobe's) do spit out garbage only.

I just tested the desktop standalone tool, and what they say on their webpage is true. It has a very good commandline. Some of my "problematic" PDF test files the tool handled to my full satisfaction.

This thing will from now on be my recommendation for every sophisticated and challenging PDF text extraction requirements.

TET is simply awesome. It detects tables. Inside tables, it identifies cells spanning multiple columns. It identifies table rows and contents of each table cell separately. It deals very well with hyphenations: it removes hyphens and restores complete words. It supports non-ASCII languages (including CJK, Arabic and Hebrew). When encountering ligatures, it restores the original characters...

Give it a try.

How to set limits for axes in ggplot2 R plots?

Quick note: if you're also using coord_flip() to flip the x and the y axis, you won't be able to set range limits using coord_cartesian() because those two functions are exclusive (see here).

Fortunately, this is an easy fix; set your limits within coord_flip() like so:

p + coord_flip(ylim = c(3,5), xlim = c(100, 400))

This just alters the visible range (i.e. doesn't remove data points).

Python base64 data decode

Well, I assume you are not on Interactive Mode and you used this code to decode your string:

import base64
your_string = 'Q5YACgAAAABDlgAbAAAAAEOWAC0AAAAAQ5YAPwAAAABDlgdNAAAAAEOWB18AAAAAQ5YHcAAAAABDlgeCAAAAAEOWB5QAAAAAQ5YHpkNx8H9Dlge4REqBx0OWB8pEpZ10Q5YH3ES2lxFDlgfuRIuPbEOWB/9EA9SqQ5YIEUIFJtxDlggjAAAAAEOWCDVDDMm3Q5YIR0N5wOtDlghZQ4GkeEOWCGtDD0CbQ5YIfQAAAABDlgiOAAAAAEOWCKAAAAAAQ5YIsgAAAABDlob5AAAAAEOWhwsAAAAAQ5aHHQAAAABDlocvAAAAAEOWh0FBC+dQQ5aHU0NJ9WdDlodlQ9RK6kOWh3dEDRdFQ5aHiUQARjZDloebQ5xn3kOWh61C1TYMQ5aHvwAAAABDlofRAAAAAEOWh+MAAAAAQ5aH9QAAAABDnFl9AAAAAEOcWZAAAAAAQ5xZpAAAAABDnFm3AAAAAEOcWctDH72jQ5xZ3kNDentDnFnxQ0QCp0OcWgVDK52XQ5xaGEMDUuNDnFosAAAAAEOcWj8AAAAAQ5xaUwAAAABDnFpmAAAAAEOcWnkAAAAAQ5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SEOyObBERYmGQ6D0xkRFicRDUY2nREWKAkIfGvhERYpAAAAAAERFin4AAAAAREWKvAAAAABERYr6AAAAAERFjiAAAAAAREWOXgAAAABERY6cAAAAAERFjtoAAAAAREWPGEK9GuBERY9WQ2Ml50RFj5RDoK7UREWP0kOl+WhERZAQQ22uP0RFkE5Coc28REWQjAAAAABERZDKAAAAAERFkQgAAAAAREWRRgAAAABER8aUAAAAAERHxtQAAAAAREfHEwAAAABER8dTAAAAAERHx5JDh8FaREfH0UO9DJBER8gRQ9bfKERHyFBDzkoWREfIkEOuMHxER8jPAAAAAERHyQ4AAAAAREfJTgAAAABER8mNAAAAAERIbk4AAAAAREhujgAAAABESG7OAAAAAERIbw4AAAAAREhvTkMM9UlESG+NQ083Y0RIb81DOgL9REhwDUK2XghESHBNAAAAAERIcI0AAAAAREhwzQAAAABESHEMAAAAAERKh+IAAAAAREqIIwAAAABESohkAAAAAERKiKYAAAAAREqI50Lh96RESokoQ35MV0RKiWlDnMTYREqJqkNxeg9ESonrQr2M/kRKii0AAAAAREqKbgAAAABESoqvAAAAAERKivAAAAAAREvFtwAAAABES8X5AAAAAERLxjsAAAAAREvGfQAAAABES8a/QwTfiURLxwFDcL+ZREvHQ0OJfrJES8eFQ2HTSURLx8dDAQzpREvICQAAAABES8hLAAAAAERLyI0AAAAAREvIzwAAAABES8wpAAAAAERLzGsAAAAAREvMrQAAAABES8zvAAAAAERLzTFC78e2REvNc0NWbJ9ES821Q5QpeERLzfdDbnPBREvOOUJOhwhES857AAAAAERLzrwAAAAAREvO/gAAAABES89AAAAAAERMDGoAAAAAREwMrQAAAABETAzvAAAAAERMDTEAAAAAREwNc0MbaL1ETA21Q4XDPkRMDfdDlMa4REwOOkNYuqFETA58QoUC7kRMDr4AAAAAREwPAAAAAABETA9CAAAAAERMD4QAAAAARE+u2AAAAABET68dAAAAAERPr2EAAAAARE+vpgAAAABET6/qQyyLhURPsC9DWN/HRE+wc0NkY0tET7C4QxkM20RPsPwAAAAARE+xQQAAAABET7GFAAAAAERPscoAAAAARFAOCQAAAABEUA5OAAAAAERQDpMAAAAARFAO1wAAAABEUA8cQwDAqURQD2FDdvAjRFAPpkOL1RJEUA/qQ0OKJURQEC9CXTp0RFAQdAAAAABEUBC5AAAAAERQEP4AAAAARFARQgAAAABEVcuoAAAAAERVy/AAAAAARFXMOQAAAABEVcyCAAAAAERVzMpCzsoORFXNE0NaGXFEVc1bQ3R5C0RVzaRDKbY/RFXN7QAAAABEVc41AAAAAERVzn4AAAAARFXOxwAAAABEV5BlAAAAAERXkK4AAAAARFeQ+AAAAABEV5FCAAAAAERXkYxDKSu1RFeR1kNbVSFEV5IgQ1lH20RXkmlDOlYfRFeSs0M4QDVEV5L9Q0YP/0RXk0dDMzG5RFeTkQAAAABEV5PaAAAAAERXlCQAAAAARFeUbgAAAABEV6FpAAAAAERXobMAAAAARFeh/QAAAABEV6JHAAAAAERXopFDDVORRFei20NxGSNEV6MlQ22aoURXo25C9lnCRFejuAAAAABEV6QCAAAAAERXpEwAAAAARFeklgAAAABEV6W9AAAAAERXpgcAAAAARFemUQAAAABEV6abAAAAAERXpuVDLnHjRFenL0M9OBdEV6d5QxBdL0RXp8MAAAAARFeoDQAAAABEV6hWAAAAAERXqKAAAAAARF33JAAAAABEXfdzAAAAAERd98EAAAAARF34DwAAAABEXfheQy+tTURd+KxDS93XRF34+kM42jtEXflIQswuZkRd+ZcAAAAARF355QAAAABEXfozAAAAAERd+oEAAAAARF5M4QAAAABEXk0wAAAAAEReTX4AAAAARF5NzQAAAABEXk4bQrksMkReTmpDvnVcRF5OuEQoL11EXk8HREPcqkReT1VEI/uQRF5PpEPTigZEXk/zQ4LN9kReUEFDX7PhRF5QkAAAAABEXlDeAAAAAEReUS0AAAAARF5RewAAAABEXo0MAAAAAERejVsAAAAARF6NqQAAAABEXo34AAAAAERejkdDA7iRRF6OlUOCrD5EXo7kQ8vYCkRejzND56FuRF6PgUO0Y8BEXo/QQyOz3URekB8AAAAARF6QbgAAAABEXp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AAAABEgmWDAAAAAESCZbkAAAAARILgJgAAAABEguBcAAAAAESC4JMAAAAARILgyQAAAABEguEAQykld0SC4TZDdX0HRILhbENFmp9EguGjQb3PWESC4dkAAAAARILiEAAAAABEguJGAAAAAESC4n0AAAAARILldwAAAABEguWtAAAAAESC5eMAAAAARILmGgAAAABEguZQQwBjuUSC5odDV6cNRILmvUM6wtdEgub0QqvdxESC5yoAAAAARILnYQAAAABEgueXAAAAAESC580AAAAARIQHrQAAAABEhAflAAAAAESECBwAAAAARIQIVAAAAABEhAiLQ6u3TESECMJDwF2mRIQI+kO6QMBEhAkxQ4fEYkSECWlC/e2yRIQJoAAAAABEhAnXAAAAAESECg8AAAAARIQKRgAAAABEhkcTAAAAAESGR00AAAAARIZHhgAAAABEhke/AAAAAESGR/lDLs0JRIZIMkNUEF9EhkhrQ0uXC0SGSKRDHr1tRIZI3gAAAABEhkkXAAAAAESGSVAAAAAARIZJikL/SApEhknDQ2n1HUSGSfxDaNZfRIZKNULoybBEhkpvAAAAAESGSqgAAAAARIZK4QAAAABEhksbAAAAAESKp1YAAAAARIqnkwAAAABEiqfQAAAAAESKqA0AAAAARIqoSkOZccZEiqiHQ8OX8ESKqMRD0uwsRIqpAUPBGSZEiqk+Q4aumESKqXsAAAAARIqpuAAAAABEiqn1AAAAAESKqjMAAAAARIsHRgAAAABEiweEAAAAAESLB8EAAAAARIsH/gAAAABEiwg8QRzZQESLCHlDOZ21RIsIt0NpEt9Eiwj0Qxy7mUSLCTIAAAAARIsJbwAAAABEiwmsAAAAAESLCepC1l7iRIsKJ0NKJGFEiwplQ2VGDUSLCqJDI96fRIsK3wAAAABEiwsdAAAAAESLC1oAAAAARIsLmAAAAABEi6aPAAAAAESLps0AAAAARIunCgAAAABEi6dIAAAAAESLp4ZDAlSPRIunxEN89OlEi6gCQ36+10SLqEBDKC6nRIuofgAAAABEi6i8AAAAAESLqPoAAAAARIupOAAAAABEi6l2AAAAAESLqbQAAAAARIup8kMy0NNEi6owQ4TQB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AAAAARKSniwAAAABEpKfhQxLIMUSkqDdDaeADRKSojUNwUU9EpKjjQ0nNC0SkqTpDL+FvRKSpkAAAAABEpKnmAAAAAESkqjwAAAAARKSqkgAAAABEqfuwAAAAAESp/AwAAAAARKn8aAAAAABEqfzEAAAAAESp/SBDNOW9RKn9e0NlYU9Eqf3XQ0R360Sp/jNCwDr2RKn+jwAAAABEqf7rAAAAAESp/0YAAAAARKn/ogAAAABErEarAAAAAESsRwoAAAAARKxHaAAAAABErEfGAAAAAESsSCVCE4y4RKxIg0NICpdErEjhQ4IvIkSsSUBDKx7dRKxJngAAAABErEn8AAAAAESsSloAAAAARKxKuQAAAABEtQkRAAAAAES1CXkAAAAARLUJ4QAAAABEtQpKAAAAAES1CrJDJhD9RLULGkN2IZtEtQuCQ0j6M0S1C+pCqdwmRLUMUgAAAABEtQy6AAAAAES1DSMAAAAARLUNiwAAAABEt1aPAAAAAES3VvkAAAAARLdXZAAAAABEt1fPAAAAAES3WDpDesoPRLdYpUPA01ZEt1kPQ9YeGkS3WXpDvpdCRLdZ5UOX1rpEt1pQAAAAAES3WrsAAAAARLdbJgAAAABEt1uQAAAAAETFGvIAAAAARMUbbQAAAABExRvpAAAAAETFHGQAAAAARMUc30JvoHRExR1bQ31mOUTFHdZDt+aSRMUeUkPAB3pExR7NQ6mPcETFH0lDgLBwRMUfxEMHHK9ExSBAAAAAAETFILsAAAAARMUhNwAAAABExSGyAAAAAETHFHgAAAAARMcU9gAAAABExxV0AAAAAETHFfIAAAAARMcWcEM1n/lExxbuQ1u19UTHF2xDRxs7RMcX6kLjC6ZExxhoAAAAAETHGOYAAAAARMcZZAAAAABExxniAAAAAETH/rQAAAAARMf/MwAAAABEx/+yAAAAAETIADEAAAAA'
base64.b64decode(your_string)

Well first of all you need to assign the finished product to a variable to be able to be printed out:

code_string = base64.b64decode(your_string)

Then like any beginner programmer would know, you would print the results out: Python 2.7x:

print code_string

Python 3.x:

print(code_string)

After the successful decoding, you will get a string about the size of the not yet decoded string. I hope this helps you!

What is the purpose of XSD files?

XSDs constrain the vocabulary and structure of XML documents.

  • Without an XSD, an XML document need only follow the rules for being well-formed as given in the W3C XML Recommendation.
  • With an XSD, an XML document must adhere to additional constraints placed upon the names and values of its elements and attributes in order to be considered valid against the XSD per the W3C XML Schema Recommendation.

XML is all about agreement, and XSDs provide the means for structuring and communicating the agreement beyond the basic definition of XML itself.

How can I detect if this dictionary key exists in C#?

You can use ContainsKey:

if (dict.ContainsKey(key)) { ... }

or TryGetValue:

dict.TryGetValue(key, out value);

Update: according to a comment the actual class here is not an IDictionary but a PhysicalAddressDictionary, so the methods are Contains and TryGetValue but they work in the same way.

Example usage:

PhysicalAddressEntry entry;
PhysicalAddressKey key = c.PhysicalAddresses[PhysicalAddressKey.Home].Street;
if (c.PhysicalAddresses.TryGetValue(key, out entry))
{
    row["HomeStreet"] = entry;
}

Update 2: here is the working code (compiled by question asker)

PhysicalAddressEntry entry;
PhysicalAddressKey key = PhysicalAddressKey.Home;
if (c.PhysicalAddresses.TryGetValue(key, out entry))
{
    if (entry.Street != null)
    {
        row["HomeStreet"] = entry.Street.ToString();
    }
}

...with the inner conditional repeated as necessary for each key required. The TryGetValue is only done once per PhysicalAddressKey (Home, Work, etc).

Escaping single quote in PHP when inserting into MySQL

You should just pass the variable (or data) inside "mysql_real_escape_string(trim($val))"

where $val is the data which is troubling you.

Sql select rows containing part of string

SELECT *
FROM myTable
WHERE URL = LEFT('mysyte.com/?id=2&region=0&page=1', LEN(URL))

Or use CHARINDEX http://msdn.microsoft.com/en-us/library/aa258228(v=SQL.80).aspx

Why am I getting "(304) Not Modified" error on some links when using HttpWebRequest?

It is not an issue it is because of caching...

To overcome this add a timestamp to your endpoint call, e.g. axios.get('/api/products').

After timestamp it should be axios.get(/api/products?${Date.now()}.

It will resolve your 304 status code.

Alter table add multiple columns ms sql

Take out the parentheses and the curly braces, neither are required when adding columns.

How can I scale an image in a CSS sprite

Well I think found a simpler solution for scaling images : example - lets say there is an image with 3 equal sized sprites which you would want to use, use CSS to scale the image

background-size : 300% 100%;

and then specify the custom height and width that needs to be applied to your html element eg:

 width :45%;
 height:100px;

A sample code would look something like this :

.customclass {
    background: url("/sample/whatever.png") 0 0 no-repeat ;
    background-size : 300% 100%;
    width :45%;
    height:100px;
}

im pretty new to css ,and styling is not my best area this could be a wrong way of doing it.. but it worked for me in Firefox/Chrome/Explorer 10 ,hope it works in older versions too..

Get Locale Short Date Format using javascript

Slight modification to Mitali's response. To dynamically generate the language for a more localized solution.

var lang= window.navigator.userLanguage || window.navigator.language;

var date = new Date();

var options = {
   weekday: "short",
   year: "numeric",
   month: "2-digit",
   day: "numeric"
};

date.toLocaleDateString(lang, options);

How to call Makefile from another Makefile?

Instead of the -f of make you might want to use the -C <path> option. This first changes the to the path '<path>', and then calles make there.

Example:

clean:
  rm -f ./*~ ./gmon.out ./core $(SRC_DIR)/*~ $(OBJ_DIR)/*.o
  rm -f ../svn-commit.tmp~
  rm -f $(BIN_DIR)/$(PROJECT)
  $(MAKE) -C gtest-1.4.0/make clean

Java: recommended solution for deep cloning/copying an instance

Joshua Bloch's book has a whole chapter entitled "Item 10: Override Clone Judiciously" in which he goes into why overriding clone for the most part is a bad idea because the Java spec for it creates many problems.

He provides a few alternatives:

  • Use a factory pattern in place of a constructor:

         public static Yum newInstance(Yum yum);
    
  • Use a copy constructor:

         public Yum(Yum yum);
    

All of the collection classes in Java support the copy constructor (e.g. new ArrayList(l);)

How do I implement interfaces in python?

There are third-party implementations of interfaces for Python (most popular is Zope's, also used in Twisted), but more commonly Python coders prefer to use the richer concept known as an "Abstract Base Class" (ABC), which combines an interface with the possibility of having some implementation aspects there too. ABCs are particularly well supported in Python 2.6 and later, see the PEP, but even in earlier versions of Python they're normally seen as "the way to go" -- just define a class some of whose methods raise NotImplementedError so that subclasses will be on notice that they'd better override those methods!-)

Retrieving the output of subprocess.call()

Output from subprocess.call() should only be redirected to files.

You should use subprocess.Popen() instead. Then you can pass subprocess.PIPE for the stderr, stdout, and/or stdin parameters and read from the pipes by using the communicate() method:

from subprocess import Popen, PIPE

p = Popen(['program', 'arg1'], stdin=PIPE, stdout=PIPE, stderr=PIPE)
output, err = p.communicate(b"input data that is passed to subprocess' stdin")
rc = p.returncode

The reasoning is that the file-like object used by subprocess.call() must have a real file descriptor, and thus implement the fileno() method. Just using any file-like object won't do the trick.

See here for more info.

How can I bind a background color in WPF/XAML?

The Background property expects a Brush object, not a string. Change the type of the property to Brush and initialize it thus:

Background = new SolidColorBrush(Colors.Red);

How do I sort an observable collection?

None of these answers worked in my case. Either because it screws up binding, or requires so much additional coding that it's kind of a nightmare, or the answer is just broken. So, here's yet another simpler answer i thought. It's a lot less code and it remains the same observable collection with an additional this.sort type of method. Let me know if there's some reason I shouldn't be doing it this way (efficiency etc.)?

public class ScoutItems : ObservableCollection<ScoutItem>
{
    public void Sort(SortDirection _sDir, string _sItem)
    {
             //TODO: Add logic to look at _sItem and decide what property to sort on
            IEnumerable<ScoutItem> si_enum = this.AsEnumerable();

            if (_sDir == SortDirection.Ascending)
            {
                si_enum = si_enum.OrderBy(p => p.UPC).AsEnumerable();
            } else
            {
                si_enum = si_enum.OrderByDescending(p => p.UPC).AsEnumerable();
            }

            foreach (ScoutItem si in si_enum)
            {
                int _OldIndex = this.IndexOf(si);
                int _NewIndex = si_enum.ToList().IndexOf(si);
                this.MoveItem(_OldIndex, _NewIndex);
            }
      }
}

...Where ScoutItem is my public class. Just seemed a lot simpler. Added benefit: it actually works and doesn't mess with bindings or return a new collection etc.

how to implement regions/code collapse in javascript

It works like a charm in PhpStorm

//#region My Region 1
    ...
//#endregion

//#region My Region 2
    ...
//#endregion

my regions

JQuery datepicker language

In 2020, just do

$.datetimepicker.setLocale('en');

Of course, replace 'en' with the correct language ('sv', 'fr', ...)

How to get a List<string> collection of values from app.config in WPF?

You could have them semi-colon delimited in a single value, e.g.

App.config

<add key="paths" value="C:\test1;C:\test2;C:\test3" />

C#

var paths = new List<string>(ConfigurationManager.AppSettings["paths"].Split(new char[] { ';' }));

ICommand MVVM implementation

This is almost identical to how Karl Shifflet demonstrated a RelayCommand, where Execute fires a predetermined Action<T>. A top-notch solution, if you ask me.

public class RelayCommand : ICommand
{
    private readonly Predicate<object> _canExecute;
    private readonly Action<object> _execute;

    public RelayCommand(Predicate<object> canExecute, Action<object> execute)
    {
        _canExecute = canExecute;
        _execute = execute;
    }

    public event EventHandler CanExecuteChanged
    {
        add => CommandManager.RequerySuggested += value;
        remove => CommandManager.RequerySuggested -= value;
    }

    public bool CanExecute(object parameter)
    {
        return _canExecute(parameter);
    }

    public void Execute(object parameter)
    {
        _execute(parameter);
    }
}

This could then be used as...

public class MyViewModel
{
    private ICommand _doSomething;
    public ICommand DoSomethingCommand
    {
        get
        {
            if (_doSomething == null)
            {
                _doSomething = new RelayCommand(
                    p => this.CanDoSomething,
                    p => this.DoSomeImportantMethod());
            }
            return _doSomething;
        }
    }
}

Read more:
Josh Smith (introducer of RelayCommand): Patterns - WPF Apps With The MVVM Design Pattern

jQuery Datepicker localization

Datepicker in german (Deutsch):

$.datepicker.regional['de'] = {
    monthNames: ['Januar','Februar','März','April','Mai','Juni',
    'Juli','August','September','Oktober','November','Dezember'],
    monthNamesShort: ['Jan','Feb','Mär','Apr','Mai','Jun',
    'Jul','Aug','Sep','Okt','Nov','Dez'],
    dayNames: ['Sonntag','Montag','Dienstag','Mittwoch','Donnerstag','Freitag','Samstag'],
    dayNamesShort: ['Son','Mon','Die','Mit','Don','Fre','Sam'],
    dayNamesMin: ['So','Mo','Di','Mi','Do','Fr','Sa'],
    firstDay: 1};
 $.datepicker.setDefaults($.datepicker.regional['de']);

Differences between Emacs and Vim

Emacs has viper-mode, so in some real sense, it provides a superset of features (excepting those described in What Vim features are missing in Emacs with Viper and Vimpulse?).

vi (and VIM IIRC) is lighter weight (it can edit files in place), but offers fewer features (subprocess communication, extension language).

When saving, how can you check if a field has changed?

Another late answer, but if you're just trying to see if a new file has been uploaded to a file field, try this: (adapted from Christopher Adams's comment on the link http://zmsmith.com/2010/05/django-check-if-a-field-has-changed/ in zach's comment here)

Updated link: https://web.archive.org/web/20130101010327/http://zmsmith.com:80/2010/05/django-check-if-a-field-has-changed/

def save(self, *args, **kw):
    from django.core.files.uploadedfile import UploadedFile
    if hasattr(self.image, 'file') and isinstance(self.image.file, UploadedFile) :
        # Handle FileFields as special cases, because the uploaded filename could be
        # the same as the filename that's already there even though there may
        # be different file contents.

        # if a file was just uploaded, the storage model with be UploadedFile
        # Do new file stuff here
        pass

What is the most efficient string concatenation method in python?

One Year later, let's test mkoistinen's answer with python 3.4.3:

  • plus 0.963564149000 (95.83% as fast)
  • join 0.923408469000 (100.00% as fast)
  • form 1.501130934000 (61.51% as fast)
  • intp 1.019677452000 (90.56% as fast)

Nothing changed. Join is still the fastest method. With intp being arguably the best choice in terms of readability you might want to use intp nevertheless.

What encoding/code page is cmd.exe using?

In Java I used encoding "IBM850" to write the file. That solved the problem.

Scrolling an iframe with JavaScript?

Use the scrollTop property of the frame's content to set the content's vertical scroll-offset to a specific number of pixels (like 100):

<iframe src="foo.html" onload="this.contentWindow.document.documentElement.scrollTop=100"></iframe>

Hibernate Error: org.hibernate.NonUniqueObjectException: a different object with the same identifier value was already associated with the session

We are using an old version hibernate (3.2.6) and the problem for us was, that Hibernate expected the first column in the result set to be the generated primary key. Took me ages to figure that out.

Solution: Ensure in that in the DDL the generated primary key is always the first column. Solution 2: Update hibernate

JavaScript for detecting browser language preference

var language = window.navigator.userLanguage || window.navigator.language;
alert(language); //works IE/SAFARI/CHROME/FF

window.navigator.userLanguage is IE only and it's the language set in Windows Control Panel - Regional Options and NOT browser language, but you could suppose that a user using a machine with Window Regional settings set to France is probably a French user.

navigator.language is FireFox and all other browser.

Some language code: 'it' = italy, 'en-US' = english US, etc.


As pointed out by rcoup and The WebMacheter in comments below, this workaround won't let you discriminate among English dialects when users are viewing website in browsers other than IE.

window.navigator.language (Chrome/FF/Safari) returns always browser language and not browser's preferred language, but: "it's pretty common for English speakers (gb, au, nz, etc) to have an en-us version of Firefox/Chrome/Safari." Hence window.navigator.language will still return en-US even if the user preferred language is en-GB.

LaTeX: Prevent line break in a span of text

Also, if you have two subsequent words in regular text and you want to avoid a line break between them, you can use the ~ character.

For example:

As we can see in Fig.~\ref{BlaBla}, there is nothing interesting to see. A~better place..

This can ensure that you don't have a line starting with a figure number (without the Fig. part) or with an uppercase A.

Does a `+` in a URL scheme/host/path represent a space?

Space characters may only be encoded as "+" in one context: application/x-www-form-urlencoded key-value pairs.

The RFC-1866 (HTML 2.0 specification), paragraph 8.2.1. subparagraph 1. says: "The form field names and values are escaped: space characters are replaced by `+', and then reserved characters are escaped").

Here is an example of such a string in URL where RFC-1866 allows encoding spaces as pluses: "http://example.com/over/there?name=foo+bar". So, only after "?", spaces can be replaced by pluses (in other cases, spaces should be encoded to %20). This way of encoding form data is also given in later HTML specifications, for example, look for relevant paragraphs about application/x-www-form-urlencoded in HTML 4.01 Specification, and so on.

But, because it's hard to always correctly determine the context, it's the best practice to never encode spaces as "+". It's better to percent-encode all character except "unreserved" defined in RFC-3986, p.2.3. Here is a code example that illustrates what should be encoded. It is given in Delphi (pascal) programming language, but it is very easy to understand how it works for any programmer regardless of the language possessed:

(* percent-encode all unreserved characters as defined in RFC-3986, p.2.3 *)
function UrlEncodeRfcA(const S: AnsiString): AnsiString;
const    
  HexCharArrA: array [0..15] of AnsiChar = '0123456789ABCDEF';
var
  I: Integer;
  c: AnsiChar;
begin
 // percent-encoding, see RFC-3986, p. 2.1
  Result := S;
  for I := Length(S) downto 1 do
  begin
    c := S[I];
    case c of
      'A' .. 'Z', 'a' .. 'z', // alpha
      '0' .. '9',             // digit
      '-', '.', '_', '~':;    // rest of unreserved characters as defined in the RFC-3986, p.2.3
      else
        begin
          Result[I] := '%';
          Insert('00', Result, I + 1);
          Result[I + 1] := HexCharArrA[(Byte(C) shr 4) and $F)];
          Result[I + 2] := HexCharArrA[Byte(C) and $F];
        end;
    end;
  end;
end;

function UrlEncodeRfcW(const S: UnicodeString): AnsiString;
begin
  Result := UrlEncodeRfcA(Utf8Encode(S));
end;

Using column alias in WHERE clause of MySQL query produces an error

Standard SQL (or MySQL) does not permit the use of column aliases in a WHERE clause because

when the WHERE clause is evaluated, the column value may not yet have been determined.

(from MySQL documentation). What you can do is calculate the column value in the WHERE clause, save the value in a variable, and use it in the field list. For example you could do this:

SELECT `users`.`first_name`, `users`.`last_name`, `users`.`email`,
@postcode AS `guaranteed_postcode`
FROM `users` LEFT OUTER JOIN `locations`
ON `users`.`id` = `locations`.`user_id`
WHERE (@postcode := SUBSTRING(`locations`.`raw`,-6,4)) NOT IN
(
 SELECT `postcode` FROM `postcodes` WHERE `region` IN
 (
  'australia'
 )
)

This avoids repeating the expression when it grows complicated, making the code easier to maintain.

How do I delete specific lines in Notepad++?

You can try doing a replace of #region with \n, turning extended search mode on.

Why do I get "Exception; must be caught or declared to be thrown" when I try to compile my Java code?

All your problems derive from this

byte[] encrypted = cipher.doFinal(toEncrypt.getBytes());
return encrypted;

Which are enclosed in a try, catch block, the problem is that in case the program found an exception you are not returning anything. Put it like this (modify it as your program logic stands):

public static byte[] encrypt(String toEncrypt) throws Exception{
    try{
        String plaintext = toEncrypt;
        String key = "01234567890abcde";
        String iv = "fedcba9876543210";

        SecretKeySpec keyspec = new SecretKeySpec(key.getBytes(), "AES");
        IvParameterSpec ivspec = new IvParameterSpec(iv.getBytes());

        Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
        cipher.init(Cipher.ENCRYPT_MODE,keyspec,ivspec);
        byte[] encrypted = cipher.doFinal(toEncrypt.getBytes());

        return encrypted;
    } catch(Exception e){
        return null;            // Always must return something
    }
}

For the second one you must catch the Exception from the encrypt method call, like this (also modify it as your program logic stands):

public void actionPerformed(ActionEvent e)
  .
  .
  .
    try {
        byte[] encrypted = encrypt(concatURL);
        String encryptedString = bytesToHex(encrypted);
        content.removeAll();
        content.add(new JLabel("Concatenated User Input -->" + concatURL));

        content.add(encryptedTextField);
    setContentPane(content);
    } catch (Exception exc) {
        // TODO: handle exception
    }
}

The lessons you must learn from this:

  • A method with a return-type must always return an object of that type, I mean in all possible scenarios
  • All checked exceptions must always be handled

Is there a way to check if a file is in use?

Aside from working 3-liners and just for reference: If you want the full blown information - there is a little project on Microsoft Dev Center:

https://code.msdn.microsoft.com/windowsapps/How-to-know-the-process-704839f4

From the Introduction:

The C# sample code developed in .NET Framework 4.0 would help in finding out which is the process that is having a lock on a file. RmStartSession function which is included in rstrtmgr.dll has been used to create a restart manager session and according to the return result a new instance of Win32Exception object is created. After registering the resources to a Restart Manager session via RmRegisterRescources function, RmGetList function is invoked to check what are the applications are using a particular file by enumerating the RM_PROCESS_INFO array.

It works by connecting to the "Restart Manager Session".

The Restart Manager uses the list of resources registered with the session to determine which applications and services must be shut down and restarted. Resources can be identified by filenames, service short names, or RM_UNIQUE_PROCESS structures that describe running applications.

It might be a little overengineered for your particular needs... But if that is what you want, go ahead and grab the vs-project.

How do I correct "Commit Failed. File xxx is out of date. xxx path not found."

This looks like a problem with the svn:mergeinfo property getting out of wack between the branch and the trunk.

Which leads to the following questions (forgive my command line instructions as I done use tortoise much):

  1. Are you merging at the trunk root level or the sub folder level? In my experience it is always best to do at the root level, this way the whole trunk thinks it has been merged to rather than just part (this seems to confuse svn greatly in 1.5.0)

  2. My next question is were you using the --reintergrate parameter? I can never remember how to get to this in tortoise, but when you are going back to the trunk from a branch then you should use this parameter.

  3. Have you merged the trunk into the branch before you have reintegrated? This can help remove conflicts that you may see when you merge back?

  4. Have you got any svn:mergeinfo properties on the branch that are not at the root level? This I have found always causes problems. You can always find this out by going svn -R pg svn:mergeinfo. You can then record the locations and revisions that were below the root, if you find them relevant then move them to the root by svn merge --record-only -r start:end <location> and then delete them from the sub root locations with svn pd svn:mergeinfo <location> You then need to commit these changes

  5. Once you have all that is done try merging again.

Using JQuery hover with HTML image map

You should check out this plugin:

https://github.com/kemayo/maphilight

and the demo:

http://davidlynch.org/js/maphilight/docs/demo_usa.html

if anything, you might be able to borrow some code from it to fix yours.

Double.TryParse or Convert.ToDouble - which is faster and safer?

Unless you are 100% certain of your inputs, which is rarely the case, you should use Double.TryParse.

Convert.ToDouble will throw an exception on non-numbers
Double.Parse will throw an exception on non-numbers or null
Double.TryParse will return false or 0 on any of the above without generating an exception.

The speed of the parse becomes secondary when you throw an exception because there is not much slower than an exception.

Use '=' or LIKE to compare strings in SQL?

LIKE and the equality operator have different purposes, they don't do the same thing:
= is much faster, whereas LIKE can interpret wildcards. Use = wherever you can and LIKE wherever you must.

SELECT * FROM user WHERE login LIKE 'Test%';

Sample matches:

TestUser1
TestUser2
TestU
Test

What's your most controversial programming opinion?

Before January 1st 1970, true and false were the other way around...

How do I get current date/time on the Windows command line in a suitable format for usage in a file/folder name?

Unfortunately this is not immune to regional settings, but it does what you want.

set hour=%time:~0,2%
if "%time:~0,1%"==" " set hour=0%time:~1,1%
set _my_datetime=%date:~10,4%-%date:~4,2%-%date:~7,2%_%hour%%time:~3,2%

Amazing the stuff you can find on Wikipedia.

How do I pass a string into subprocess.Popen (using the stdin argument)?

There's a beautiful solution if you're using Python 3.4 or better. Use the input argument instead of the stdin argument, which accepts a bytes argument:

output = subprocess.check_output(
    ["sed", "s/foo/bar/"],
    input=b"foo",
)

This works for check_output and run, but not call or check_call for some reason.

What does mysql error 1025 (HY000): Error on rename of './foo' (errorno: 150) mean?

Take a look in error file for your mysql database. According to Bug #26305 my sql do not give you the cause. This bug exists since MySQL 4.1 ;-)

Does a VPN Hide my Location on Android?

Your question can be conveniently divided into several parts:

Does a VPN hide location? Yes, he is capable of this. This is not about GPS determining your location. If you try to change the region via VPN in an application that requires GPS access, nothing will work. However, sites define your region differently. They get an IP address and see what country or region it belongs to. If you can change your IP address, you can change your region. This is exactly what VPNs can do.

How to hide location on Android? There is nothing difficult in figuring out how to set up a VPN on Android, but a couple of nuances still need to be highlighted. Let's start with the fact that not all Android VPNs are created equal. For example, VeePN outperforms many other services in terms of efficiency in circumventing restrictions. It has 2500+ VPN servers and a powerful IP and DNS leak protection system.

You can easily change the location of your Android device by using a VPN. Follow these steps for any device model (Samsung, Sony, Huawei, etc.):

  1. Download and install a trusted VPN.

  2. Install the VPN on your Android device.

  3. Open the application and connect to a server in a different country.

  4. Your Android location will now be successfully changed!

Is it legal? Yes, changing your location on Android is legal. Likewise, you can change VPN settings in Microsoft Edge on your PC, and all this is within the law. VPN allows you to change your IP address, safeguarding your privacy and protecting your actual location from being exposed. However, VPN laws may vary from country to country. There are restrictions in some regions.

Brief summary: Yes, you can change your region on Android and a VPN is a necessary assistant for this. It's simple, safe and legal. Today, VPN is the best way to change the region and unblock sites with regional restrictions.

What is the difference between 'SAME' and 'VALID' padding in tf.nn.max_pool of tensorflow?

If you like ascii art:

  • "VALID" = without padding:

       inputs:         1  2  3  4  5  6  7  8  9  10 11 (12 13)
                      |________________|                dropped
                                     |_________________|
    
  • "SAME" = with zero padding:

                   pad|                                      |pad
       inputs:      0 |1  2  3  4  5  6  7  8  9  10 11 12 13|0  0
                   |________________|
                                  |_________________|
                                                 |________________|
    

In this example:

  • Input width = 13
  • Filter width = 6
  • Stride = 5

Notes:

  • "VALID" only ever drops the right-most columns (or bottom-most rows).
  • "SAME" tries to pad evenly left and right, but if the amount of columns to be added is odd, it will add the extra column to the right, as is the case in this example (the same logic applies vertically: there may be an extra row of zeros at the bottom).

Edit:

About the name:

  • With "SAME" padding, if you use a stride of 1, the layer's outputs will have the same spatial dimensions as its inputs.
  • With "VALID" padding, there's no "made-up" padding inputs. The layer only uses valid input data.

SQL Insert Query Using C#

I assume you have a connection to your database and you can not do the insert parameters using c #.

You are not adding the parameters in your query. It should look like:

String query = "INSERT INTO dbo.SMS_PW (id,username,password,email) VALUES (@id,@username,@password, @email)";

SqlCommand command = new SqlCommand(query, db.Connection);
command.Parameters.Add("@id","abc");
command.Parameters.Add("@username","abc");
command.Parameters.Add("@password","abc");
command.Parameters.Add("@email","abc");

command.ExecuteNonQuery();

Updated:

using(SqlConnection connection = new SqlConnection(_connectionString))
{
    String query = "INSERT INTO dbo.SMS_PW (id,username,password,email) VALUES (@id,@username,@password, @email)";

    using(SqlCommand command = new SqlCommand(query, connection))
    {
        command.Parameters.AddWithValue("@id", "abc");
        command.Parameters.AddWithValue("@username", "abc");
        command.Parameters.AddWithValue("@password", "abc");
        command.Parameters.AddWithValue("@email", "abc");

        connection.Open();
        int result = command.ExecuteNonQuery();

        // Check Error
        if(result < 0)
            Console.WriteLine("Error inserting data into Database!");
    }
}

Difference between scaling horizontally and vertically for databases

You have a company and there is only 1 worker but you got 1 new project at that time you hire new candidate -- this is horizontal scaling. where new candidate is new machines and project is new traffic/calls to your api's.

Where as 1 project with an IIT/NIT guy handling all request to your api/traffic. If any time more request to your api's then fire him and replacing him with a high IQ NIT/IIT guy -- this is vertical scaling.

How can I detect window size with jQuery?

You cannot really find the display resolution from a web page. There is a CSS Media Queries statement for it, but it is poorly implemented in most devices and browsers, if at all. However, you do not need to know the resolution of the display, because changing it causes the (pixel) width of the window to change, which can be detected using the methods others have described:

$(window).resize(function() {
  // This will execute whenever the window is resized
  $(window).height(); // New height
  $(window).width(); // New width
});

You can also use CSS Media Queries in browsers that support them to adapt your page's style to various display widths, but you should really be using em units and percentages and min-width and max-width in your CSS if you want a proper flexible layout. Gmail probably uses a combination of all these.

Resize image in PHP

You need to use either PHP's ImageMagick or GD functions to work with images.

With GD, for example, it's as simple as...

function resize_image($file, $w, $h, $crop=FALSE) {
    list($width, $height) = getimagesize($file);
    $r = $width / $height;
    if ($crop) {
        if ($width > $height) {
            $width = ceil($width-($width*abs($r-$w/$h)));
        } else {
            $height = ceil($height-($height*abs($r-$w/$h)));
        }
        $newwidth = $w;
        $newheight = $h;
    } else {
        if ($w/$h > $r) {
            $newwidth = $h*$r;
            $newheight = $h;
        } else {
            $newheight = $w/$r;
            $newwidth = $w;
        }
    }
    $src = imagecreatefromjpeg($file);
    $dst = imagecreatetruecolor($newwidth, $newheight);
    imagecopyresampled($dst, $src, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);

    return $dst;
}

And you could call this function, like so...

$img = resize_image(‘/path/to/some/image.jpg’, 200, 200);

From personal experience, GD's image resampling does dramatically reduce file size too, especially when resampling raw digital camera images.

Stop form refreshing page on submit

In my opinion, most answers are trying to solve the problem asked on your question, but I don't think that's the best approach for your scenario.

How would I go about preventing the page from refreshing when pressing the send button without any data in the fields?

A .preventDefault() does indeed not refresh the page. But I think that a simple require on the fields you want populated with data, would solve your problem.

<form id="prospects_form" method="post">
    <input id="form_name" tabindex="1" class="boxsize" type="text" name="name" placeholder="Full name*" maxlength="80" value="" required/>
    <input id="form_email" tabindex="2" class="boxsize" type="text" name="email" placeholder="Email*" maxlength="100" value="" required/>
    <input id="form_subject" class="boxsize" type="text" name="subject" placeholder="Subject*" maxlength="50" value="FORM: Row for OUBC" required/>
    <textarea id="form_message" class="boxsize" name="message" placeholder="Message*" tabindex="3" rows="6" cols="5" maxlength="500"></textarea>
</form>

Notice the require tag added at the end of each input. The result will be the same: not refreshing the page without any data in the fields.

MySQL CONCAT returns NULL if any field contain NULL

CONCAT_WS still produces null for me if the first field is Null. I solved this by adding a zero length string at the beginning as in

CONCAT_WS("",`affiliate_name`,'-',`model`,'-',`ip`,'-',`os_type`,'-',`os_version`)

however

CONCAT("",`affiliate_name`,'-',`model`,'-',`ip`,'-',`os_type`,'-',`os_version`) 

produces Null when the first field is Null.

How do I target only Internet Explorer 10 for certain situations like Internet Explorer-specific CSS or Internet Explorer-specific JavaScript code?

clipBoardData is a function that is only available in IE, so if you are seeking to target all IE versions you can use

<script type="text/javascript">
if (window.clipboardData)
            alert("You are using IE!");
</script>

ngFor with index as value in attribute

Adding this late answer to show a case most people will come across. If you only need to see what is the last item in the list, use the last key word:

<div *ngFor="let item of devcaseFeedback.reviewItems; let last = last">
  <divider *ngIf="!last"></divider>
</div>

This will add the divider component to every item except the last.

Because of the comment below, I will add the rest of the ngFor exported values that can be aliased to local variables (As are shown in the docs):

  • $implicit: T: The value of the individual items in the iterable (ngForOf).
  • ngForOf: NgIterable: The value of the iterable expression. Useful when the expression is more complex then a property access, for example when using the async pipe (userStreams | async).
  • index: number: The index of the current item in the iterable.
  • count: number: The length of the iterable.
  • count: number: The length of the iterable.
  • first: boolean: True when the item is the first item in the iterable.
  • last: boolean: True when the item is the last item in the iterable.
  • even: boolean: True when the item has an even index in the iterable.
  • odd: boolean: True when the item has an odd index in the iterable.

Create a date time with month and day only, no year

Well, you can create your own type - but a DateTime always has a full date and time. You can't even have "just a date" using DateTime - the closest you can come is to have a DateTime at midnight.

You could always ignore the year though - or take the current year:

// Consider whether you want DateTime.UtcNow.Year instead
DateTime value = new DateTime(DateTime.Now.Year, month, day);

To create your own type, you could always just embed a DateTime within a struct, and proxy on calls like AddDays etc:

public struct MonthDay : IEquatable<MonthDay>
{
    private readonly DateTime dateTime;

    public MonthDay(int month, int day)
    {
        dateTime = new DateTime(2000, month, day);
    }

    public MonthDay AddDays(int days)
    {
        DateTime added = dateTime.AddDays(days);
        return new MonthDay(added.Month, added.Day);
    }

    // TODO: Implement interfaces, equality etc
}

Note that the year you choose affects the behaviour of the type - should Feb 29th be a valid month/day value or not? It depends on the year...

Personally I don't think I would create a type for this - instead I'd have a method to return "the next time the program should be run".

mysql_connect(): The mysql extension is deprecated and will be removed in the future: use mysqli or PDO instead

Simply put, you need to rewrite all of your database connections and queries.

You are using mysql_* functions which are now deprecated and will be removed from PHP in the future. So you need to start using MySQLi or PDO instead, just as the error notice warned you.

A basic example of using PDO (without error handling):

<?php
$db = new PDO('mysql:host=localhost;dbname=testdb;charset=utf8', 'username', 'password');
$result = $db->exec("INSERT INTO table(firstname, lastname) VAULES('John', 'Doe')");
$insertId = $db->lastInsertId();
?>

A basic example of using MySQLi (without error handling):

$db = new mysqli($DBServer, $DBUser, $DBPass, $DBName);
$result = $db->query("INSERT INTO table(firstname, lastname) VAULES('John', 'Doe')");

Here's a handy little PDO tutorial to get you started. There are plenty of others, and ones about the PDO alternative, MySQLi.

In Ruby, how do I skip a loop in a .each loop, similar to 'continue'

Use next:

(1..10).each do |a|
  next if a.even?
  puts a
end

prints:

1
3   
5
7
9

For additional coolness check out also redo and retry.

Works also for friends like times, upto, downto, each_with_index, select, map and other iterators (and more generally blocks).

For more info see http://ruby-doc.org/docs/ProgrammingRuby/html/tut_expressions.html#UL.

How to manage a redirect request after a jQuery Ajax call

in the servlet you should put response.setStatus(response.SC_MOVED_PERMANENTLY); to send the '301' xmlHttp status you need for a redirection...

and in the $.ajax function you should not use the .toString() function..., just

if (xmlHttp.status == 301) { top.location.href = 'xxxx.jsp'; }

the problem is it is not very flexible, you can't decide where you want to redirect..

redirecting through the servlets should be the best way. but i still can not find the right way to do it.

Access to build environment variables from a groovy script in a Jenkins build step (Windows)

The Scriptler Groovy script doesn't seem to get all the environment variables of the build. But what you can do is force them in as parameters to the script:

  1. When you add the Scriptler build step into your job, select the option "Define script parameters"

  2. Add a parameter for each environment variable you want to pass in. For example "Name: JOB_NAME", "Value: $JOB_NAME". The value will get expanded from the Jenkins build environment using '$envName' type variables, most fields in the job configuration settings support this sort of expansion from my experience.

  3. In your script, you should have a variable with the same name as the parameter, so you can access the parameters with something like:

    println "JOB_NAME = $JOB_NAME"

I haven't used Sciptler myself apart from some experimentation, but your question posed an interesting problem. I hope this helps!

Rotating and spacing axis labels in ggplot2

Use coord_flip()

data(diamonds)
diamonds$cut <- paste("Super Dee-Duper",as.character(diamonds$cut))

qplot(cut, carat, data = diamonds, geom = "boxplot") +
  coord_flip()

enter image description here


Add str_wrap()

# wrap text to no more than 15 spaces
library(stringr)
diamonds$cut2 <- str_wrap(diamonds$cut, width = 15)
qplot(cut2, carat, data = diamonds, geom = "boxplot") +
  coord_flip()

enter image description here


In Ch 3.9 of R for Data Science, Wickham and Grolemund speak to this exact question:

coord_flip() switches the x and y axes. This is useful (for example), if you want horizontal boxplots. It’s also useful for long labels: it’s hard to get them to fit without overlapping on the x-axis.

Pygame mouse clicking detection

I was looking for the same answer to this question and after much head scratching this is the answer I came up with:

#Python 3.4.3 with Pygame
import pygame

pygame.init()
pygame.display.set_caption('Crash!')
window = pygame.display.set_mode((300, 300))


# Draw Once
Rectplace = pygame.draw.rect(window, (255, 0, 0),(100, 100, 100, 100))
pygame.display.update()
# Main Loop
while True:
    # Mouse position and button clicking.
    pos = pygame.mouse.get_pos()
    pressed1, pressed2, pressed3 = pygame.mouse.get_pressed()
    # Check if the rect collided with the mouse pos
    # and if the left mouse button was pressed.
    if Rectplace.collidepoint(pos) and pressed1:
        print("You have opened a chest!")
    # Quit pygame.
            for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            quit(1)

PDO error message?

From the manual:

If the database server successfully prepares the statement, PDO::prepare() returns a PDOStatement object. If the database server cannot successfully prepare the statement, PDO::prepare() returns FALSE or emits PDOException (depending on error handling).

The prepare statement likely caused an error because the db would be unable to prepare the statement. Try testing for an error immediately after you prepare your query and before you execute it.

$qry = '
    INSERT INTO non-existant-table (id, score) 
    SELECT id, 40 
    FROM another-non-existant-table
    WHERE description LIKE "%:search_string%"
    AND available = "yes"
    ON DUPLICATE KEY UPDATE score = score + 40
';
$sth = $this->pdo->prepare($qry);
print_r($this->pdo->errorInfo());

Javascript onclick hide div

just add onclick handler for anchor tag

onclick="this.parentNode.style.display = 'none'"

or change onclick handler for img tag

onclick="this.parentNode.parentNode.style.display = 'none'"

Tuple unpacking in for loops

Enumerate basically gives you an index to work with in the for loop. So:

for i,a in enumerate([4, 5, 6, 7]):
    print i, ": ", a

Would print:

0: 4
1: 5
2: 6
3: 7

Java: How to check if object is null?

drawable.equals(null)

The above line calls the "equals(...)" method on the drawable object.

So, when drawable is not null and it is a real object, then all goes well as calling the "equals(null)" method will return "false"

But when "drawable" is null, then it means calling the "equals(...)" method on null object, means calling a method on an object that doesn't exist so it throws "NullPointerException"

To check whether an object exists and it is not null, use the following

if(drawable == null) {
    ...
    ...
}

In above condition, we are checking that the reference variable "drawable" is null or contains some value (reference to its object) so it won't throw exception in case drawable is null as checking

null == null

is valid.

IIS7 folder permissions for web application

  1. Working on IIS 7.5 and Windows 7 i couldnt give permission APPPOOL/Mypool
  2. IUSR and IIS_IUSRS permissions not working for me
  3. I got to problem this way:

    -Created console application with C#
    -This appliaction using createeventsource like this

    if(!System.Diagnostics.EventLog.SourceExists(sourceName)) System.Diagnostics.EventLog.CreateEventSource(sourceName,logName);

    -Build solution and get .exe file

    -Run exe as administator.This create log file.

NOTE: Dont remember Event viewer must be refresh for see the log.

I hope this solution helps someone :)

How to add users to Docker container?

The trick is to use useradd instead of its interactive wrapper adduser. I usually create users with:

RUN useradd -ms /bin/bash newuser

which creates a home directory for the user and ensures that bash is the default shell.

You can then add:

USER newuser
WORKDIR /home/newuser

to your dockerfile. Every command afterwards as well as interactive sessions will be executed as user newuser:

docker run -t -i image
newuser@131b7ad86360:~$

You might have to give newuser the permissions to execute the programs you intend to run before invoking the user command.

Using non-privileged users inside containers is a good idea for security reasons. It also has a few drawbacks. Most importantly, people deriving images from your image will have to switch back to root before they can execute commands with superuser privileges.

Python - How to convert JSON File to Dataframe

import pandas as pd
print(pd.json_normalize(your_json))

This will Normalize semi-structured JSON data into a flat table

Output

  FirstName LastName MiddleName password    username
      John     Mark      Lewis     2910  johnlewis2

Qt: How do I handle the event of the user pressing the 'X' (close) button?

If you have a QMainWindow you can override closeEvent method.

#include <QCloseEvent>
void MainWindow::closeEvent (QCloseEvent *event)
{
    QMessageBox::StandardButton resBtn = QMessageBox::question( this, APP_NAME,
                                                                tr("Are you sure?\n"),
                                                                QMessageBox::Cancel | QMessageBox::No | QMessageBox::Yes,
                                                                QMessageBox::Yes);
    if (resBtn != QMessageBox::Yes) {
        event->ignore();
    } else {
        event->accept();
    }
}


If you're subclassing a QDialog, the closeEvent will not be called and so you have to override reject():

void MyDialog::reject()
{
    QMessageBox::StandardButton resBtn = QMessageBox::Yes;
    if (changes) {
        resBtn = QMessageBox::question( this, APP_NAME,
                                        tr("Are you sure?\n"),
                                        QMessageBox::Cancel | QMessageBox::No | QMessageBox::Yes,
                                        QMessageBox::Yes);
    }
    if (resBtn == QMessageBox::Yes) {
        QDialog::reject();
    }
}

How to refresh datagrid in WPF

Reload the datasource of your grid after the update

myGrid.ItemsSource = null;
myGrid.ItemsSource = myDataSource;

What's a "static method" in C#?

A static method, field, property, or event is callable on a class even when no instance of the class has been created. If any instances of the class are created, they cannot be used to access the static member. Only one copy of static fields and events exists, and static methods and properties can only access static fields and static events. Static members are often used to represent data or calculations that do not change in response to object state; for instance, a math library might contain static methods for calculating sine and cosine. Static class members are declared using the static keyword before the return type of the membe

Best way to use Google's hosted jQuery, but fall back to my hosted library on Google fail

UPDATE:
This answer turned out to be wrong. Please see the comments for the real explanation.


Most of you question has been answered, but as for the final part:

What would be the danger of both copies coming through?

None really. You'd waste bandwidth, might add some milliseconds downloading a second useless copy, but there's not actual harm if they both come through. You should, of course, avoid this using the techniques mentioned above.

Xcode: failed to get the task for process

I had a the same issue and after reading the above answers all I had to do was go to Build Settings > Code Signing > Provisioning Profile > None and was able to ran the app on my devices again. Hope this helps someone else out

Android button background color

No need to be that hardcore.
Try this :

YourButtonObject.setBackground(0xff99cc00);

Refresh page after form submitting

If you want the form to be submitted on the same page then remove the action from the form attributes.

<form method="POST" name="myform">
 <!-- Your HTML code Here -->
</form>

However, If you want to reload the page or redirect the page after submitting the form from another file then you call this function in php and it will redirect the page in 0 seconds. Also, You can use the header if you want to, just make sure you don't have any content before using the header

 function page_redirect($location)
 {
   echo '<META HTTP-EQUIV="Refresh" Content="0; URL='.$location.'">';
   exit; 
 }

 // I want the page to go to google.
 // page_redirect("http://www.google.com")

Change the URL in the browser without loading the new page using JavaScript

jQuery has a great plugin for changing browsers' URL, called jQuery-pusher.

JavaScript pushState and jQuery could be used together, like:

history.pushState(null, null, $(this).attr('href'));

Example:

$('a').click(function (event) {

  // Prevent default click action
  event.preventDefault();     

  // Detect if pushState is available
  if(history.pushState) {
    history.pushState(null, null, $(this).attr('href'));
  }
  return false;
});

Using only JavaScript history.pushState(), which changes the referrer, that gets used in the HTTP header for XMLHttpRequest objects created after you change the state.

Example:

window.history.pushState("object", "Your New Title", "/new-url");

The pushState() method:

pushState() takes three parameters: a state object, a title (which is currently ignored), and (optionally) a URL. Let's examine each of these three parameters in more detail:

  1. state object — The state object is a JavaScript object which is associated with the new history entry created by pushState(). Whenever the user navigates to the new state, a popstate event is fired, and the state property of the event contains a copy of the history entry's state object.

    The state object can be anything that can be serialized. Because Firefox saves state objects to the user's disk so they can be restored after the user restarts her browser, we impose a size limit of 640k characters on the serialized representation of a state object. If you pass a state object whose serialized representation is larger than this to pushState(), the method will throw an exception. If you need more space than this, you're encouraged to use sessionStorage and/or localStorage.

  2. title — Firefox currently ignores this parameter, although it may use it in the future. Passing the empty string here should be safe against future changes to the method. Alternatively, you could pass a short title for the state to which you're moving.

  3. URL — The new history entry's URL is given by this parameter. Note that the browser won't attempt to load this URL after a call to pushState(), but it might attempt to load the URL later, for instance after the user restarts her browser. The new URL does not need to be absolute; if it's relative, it's resolved relative to the current URL. The new URL must be of the same origin as the current URL; otherwise, pushState() will throw an exception. This parameter is optional; if it isn't specified, it's set to the document's current URL.

Request header field Access-Control-Allow-Headers is not allowed by itself in preflight response

I too faced the same problem in Angular 6. I solved the issue by using below code. Add the code in component.ts file.

import { HttpHeaders } from '@angular/common/http';

headers;

constructor() {
    this.headers = new HttpHeaders();
    this.headers.append('Access-Control-Allow-Headers', 'Authorization');
}

getData() {
    this.http.get(url,this.headers). subscribe (res => {
    // your code here...
})}

How to add an image in Tkinter?

It's not a standard lib of python 2.7. So in order for these to work properly and if you're using Python 2.7 you should download the PIL library first: Direct download link: http://effbot.org/downloads/PIL-1.1.7.win32-py2.7.exe After installing it, follow these steps:

  1. Make sure that your script.py is at the same folder with the image you want to show.
  2. Edit your script.py

    from Tkinter import *        
    from PIL import ImageTk, Image
    
    app_root = Tk()
    
    #Setting it up
    img = ImageTk.PhotoImage(Image.open("app.png"))
    
    #Displaying it
    imglabel = Label(app_root, image=img).grid(row=1, column=1)        
    
    
    app_root.mainloop()
    

Hope that helps!

Pythonic way to check if a file exists?

To check if a path is an existing file:

os.path.isfile(path)

Return True if path is an existing regular file. This follows symbolic links, so both islink() and isfile() can be true for the same path.

Defining an abstract class without any abstract methods

Of course.

Declaring a class abstract only means that you don't allow it to be instantiated on its own.

Declaring a method abstract means that subclasses have to provide an implementation for that method.

The two are separate concepts, though obviously you can't have an abstract method in a non-abstract class. You can even have abstract classes with final methods but never the other way around.

Angularjs Template Default Value if Binding Null / Undefined (With Filter)

How can I use the binary operator alongside the date filter?

<span class="gallery-date">{{gallery.date | date:'mediumDate' || "Date Empty"}}</span>

you also try:

<span class="gallery-date">{{ gallery.date == 'NULL' ? 'mediumDate' : "gallery.date"}}</span>

Working Copy Locked

Tortoise svn ->clean up

Thats all in SVN

Effective way to find any file's Encoding

The following codes are my Powershell codes to determinate if some cpp or h or ml files are encodeding with ISO-8859-1(Latin-1) or UTF-8 without BOM, if neither then suppose it to be GB18030. I am a Chinese working in France and MSVC saves as Latin-1 on french computer and saves as GB on Chinese computer so this helps me avoid encoding problem when do source file exchanges between my system and my colleagues.

The way is simple, if all characters are between x00-x7E, ASCII, UTF-8 and Latin-1 are all the same, but if I read a non ASCII file by UTF-8, we will find the special character ? show up, so try to read with Latin-1. In Latin-1, between \x7F and \xAF is empty, while GB uses full between x00-xFF so if I got any between the two, it's not Latin-1

The code is written in PowerShell, but uses .net so it's easy to be translated into C# or F#

$Utf8NoBomEncoding = New-Object System.Text.UTF8Encoding($False)
foreach($i in Get-ChildItem .\ -Recurse -include *.cpp,*.h, *.ml) {
    $openUTF = New-Object System.IO.StreamReader -ArgumentList ($i, [Text.Encoding]::UTF8)
    $contentUTF = $openUTF.ReadToEnd()
    [regex]$regex = '?'
    $c=$regex.Matches($contentUTF).count
    $openUTF.Close()
    if ($c -ne 0) {
        $openLatin1 = New-Object System.IO.StreamReader -ArgumentList ($i, [Text.Encoding]::GetEncoding('ISO-8859-1'))
        $contentLatin1 = $openLatin1.ReadToEnd()
        $openLatin1.Close()
        [regex]$regex = '[\x7F-\xAF]'
        $c=$regex.Matches($contentLatin1).count
        if ($c -eq 0) {
            [System.IO.File]::WriteAllLines($i, $contentLatin1, $Utf8NoBomEncoding)
            $i.FullName
        } 
        else {
            $openGB = New-Object System.IO.StreamReader -ArgumentList ($i, [Text.Encoding]::GetEncoding('GB18030'))
            $contentGB = $openGB.ReadToEnd()
            $openGB.Close()
            [System.IO.File]::WriteAllLines($i, $contentGB, $Utf8NoBomEncoding)
            $i.FullName
        }
    }
}
Write-Host -NoNewLine 'Press any key to continue...';
$null = $Host.UI.RawUI.ReadKey('NoEcho,IncludeKeyDown');

how to check if a file is a directory or regular file in python?

Many of the Python directory functions are in the os.path module.

import os
os.path.isdir(d)

Show space, tab, CRLF characters in editor of Visual Studio

For Visual Studio for mac, you can find it under Visual Studio -> Preferences -> Text Editor -> Markers and Rulers -> Show invisible characters

Please note you may need to restart Visual Studio for the changes to take effect

href image link download on click

Try this...

<a href="/path/to/image" download>
    <img src="/path/to/image" />
 </a>

How to list all functions in a Python module?

You can use the following method to get list all the functions in your module from shell:

import module

module.*?

How to know/change current directory in Python shell?

You can use the os module.

>>> import os
>>> os.getcwd()
'/home/user'
>>> os.chdir("/tmp/")
>>> os.getcwd()
'/tmp'

But if it's about finding other modules: You can set an environment variable called PYTHONPATH, under Linux would be like

export PYTHONPATH=/path/to/my/library:$PYTHONPATH

Then, the interpreter searches also at this place for imported modules. I guess the name would be the same under Windows, but don't know how to change.

edit

Under Windows:

set PYTHONPATH=%PYTHONPATH%;C:\My_python_lib

(taken from http://docs.python.org/using/windows.html)

edit 2

... and even better: use virtualenv and virtualenv_wrapper, this will allow you to create a development environment where you can add module paths as you like (add2virtualenv) without polluting your installation or "normal" working environment.

http://virtualenvwrapper.readthedocs.org/en/latest/command_ref.html

TypeScript or JavaScript type casting

In typescript it is possible to do an instanceof check in an if statement and you will have access to the same variable with the Typed properties.

So let's say MarkerSymbolInfo has a property on it called marker. You can do the following:

if (symbolInfo instanceof MarkerSymbol) {
    // access .marker here
    const marker = symbolInfo.marker
}

It's a nice little trick to get the instance of a variable using the same variable without needing to reassign it to a different variable name.

Check out these two resources for more information:

TypeScript instanceof & JavaScript instanceof

How to get previous month and year relative to today, using strtotime and date?

date("m-Y", strtotime("-1 months")); 

would solve this

What is output buffering?

Output Buffering for Web Developers, a Beginner’s Guide:

Without output buffering (the default), your HTML is sent to the browser in pieces as PHP processes through your script. With output buffering, your HTML is stored in a variable and sent to the browser as one piece at the end of your script.

Advantages of output buffering for Web developers

  • Turning on output buffering alone decreases the amount of time it takes to download and render our HTML because it's not being sent to the browser in pieces as PHP processes the HTML.
  • All the fancy stuff we can do with PHP strings, we can now do with our whole HTML page as one variable.
  • If you've ever encountered the message "Warning: Cannot modify header information - headers already sent by (output)" while setting cookies, you'll be happy to know that output buffering is your answer.

ngOnInit not being called when Injectable class is Instantiated

I had to call a function once my dataService was initialized, instead, I called it inside the constructor, that worked for me.

Server Document Root Path in PHP

$files = glob($_SERVER["DOCUMENT_ROOT"]."/myFolder/*");

Is the MIME type 'image/jpg' the same as 'image/jpeg'?

The important thing to note here is that the mime type is not the same as the file extension. Sometimes, however, they have the same value.

https://www.iana.org/assignments/media-types/media-types.xhtml includes a list of registered Mime types, though there is nothing stopping you from making up your own, as long as you are at both the sending and the receiving end. Here is where Microsoft comes in to the picture.

Where there is a lot of confusion is the fact that operating systems have their own way of identifying file types by using the tail end of the file name, referred to as the extension. In modern operating systems, the whole name is one long string, but in more primitive operating systems, it is treated as a separate attribute.

The OS which caused the confusion is MSDOS, which had limited the extension to 3 characters. This limitation is inherited to this day in devices, such as SD cards, which still store data in the same way.

One side effect of this limitation is that some file extensions, such as .gif match their Mime Type, image/gif, while others are compromised. This includes image/jpeg whose extension is shortened to .jpg. Even in modern Windows, where the limitation is lifted, Microsoft never let the past go, and so the file extension is still the shortened version.

Given that that:

  1. File Extensions are not File Types
  2. Historically, some operating systems had serious file name limitations
  3. Some operating systems will just go ahead and make up their own rules

The short answer is:

  • Technically, there is no such thing as image/jpg, so the answer is that it is not the same as image/jpeg
  • That won’t stop some operating systems and software from treating it as if it is the same

While we’re at it …

Legacy versions of Internet Explorer took the liberty of uploading jpeg files with the Mime Type of image/pjpeg, which, of course, just means more work for everybody else. They also uploaded png files as image/x-png.

adb is not recognized as internal or external command on windows

If you get your adb from Android Studio (which most will nowadays since Android is deprecated on Eclipse), your adb program will most likely be located here:

%USERPROFILE%\AppData\Local\Android\sdk\platform-tools

Where %USERPROFILE% represents something like C:\Users\yourName.

If you go into your computer's environmental variables and add %USERPROFILE%\AppData\Local\Android\sdk\platform-tools to the PATH (just copy-paste that line, even with the % --- it will work fine, at least on Windows, you don't need to hardcode your username) then it should work now. Open a new command prompt and type adb to check.

Storing money in a decimal column - what precision and scale?

We recently implemented a system that needs to handle values in multiple currencies and convert between them, and figured out a few things the hard way.

NEVER USE FLOATING POINT NUMBERS FOR MONEY

Floating point arithmetic introduces inaccuracies that may not be noticed until they've screwed something up. All values should be stored as either integers or fixed-decimal types, and if you choose to use a fixed-decimal type then make sure you understand exactly what that type does under the hood (ie, does it internally use an integer or floating point type).

When you do need to do calculations or conversions:

  1. Convert values to floating point
  2. Calculate new value
  3. Round the number and convert it back to an integer

When converting a floating point number back to an integer in step 3, don't just cast it - use a math function to round it first. This will usually be round, though in special cases it could be floor or ceil. Know the difference and choose carefully.

Store the type of a number alongside the value

This may not be as important for you if you're only handling one currency, but it was important for us in handling multiple currencies. We used the 3-character code for a currency, such as USD, GBP, JPY, EUR, etc.

Depending on the situation, it may also be helpful to store:

  • Whether the number is before or after tax (and what the tax rate was)
  • Whether the number is the result of a conversion (and what it was converted from)

Know the accuracy bounds of the numbers you're dealing with

For real values, you want to be as precise as the smallest unit of the currency. This means you have no values smaller than a cent, a penny, a yen, a fen, etc. Don't store values with higher accuracy than that for no reason.

Internally, you may choose to deal with smaller values, in which case that's a different type of currency value. Make sure your code knows which is which and doesn't get them mixed up. Avoid using floating point values even here.


Adding all those rules together, we decided on the following rules. In running code, currencies are stored using an integer for the smallest unit.

class Currency {
   String code;       //  eg "USD"
   int value;         //  eg 2500
   boolean converted;
}

class Price {
   Currency grossValue;
   Currency netValue;
   Tax taxRate;
}

In the database, the values are stored as a string in the following format:

USD:2500

That stores the value of $25.00. We were able to do that only because the code that deals with currencies doesn't need to be within the database layer itself, so all values can be converted into memory first. Other situations will no doubt lend themselves to other solutions.


And in case I didn't make it clear earlier, don't use float!

Missing artifact com.microsoft.sqlserver:sqljdbc4:jar:4.0

It is not too hard. I have not read the license yet. However I have proven this works. You can copy sqljdbc4 jar file to a network share or local directory. Your build.gradle should look like this :

apply plugin: 'java'
//apply plugin: 'maven'
//apply plugin: 'enhance'

sourceCompatibility = 1.8
version = '1.0'

//library versions
def hibernateVersion='4.3.10.Final'
def microsoftSQLServerJDBCLibVersion='4.0'
def springVersion='2.5.6'

def log4jVersion='1.2.16'
def jbossejbapiVersion='3.0.0.GA'

repositories {
    mavenCentral()
    maven{url "file://Sharedir/releases"}
}

dependencies {
    testCompile group: 'junit', name: 'junit', version: '4.11'
    compile "org.hibernate:hibernate-core:$hibernateVersion"
    compile "com.microsoft.sqlserver:sqljdbc4:$microsoftSQLServerJDBCLibVersion"
}

task showMeCache << {
    configurations.compile.each { println it }
}

under the sharedir/releases directory, I have directory similar to maven structure which is \sharedir\releases\com\microsoft\sqlserver\sqljdbc4\4.0\sqljdbc4-4.0.jar

good luck.

David Yen

check all socket opened in linux OS

Also you can use ss utility to dump sockets statistics.

To dump summary:

ss -s

Total: 91 (kernel 0)
TCP:   18 (estab 11, closed 0, orphaned 0, synrecv 0, timewait 0/0), ports 0

Transport Total     IP        IPv6
*         0         -         -        
RAW       0         0         0        
UDP       4         2         2        
TCP       18        16        2        
INET      22        18        4        
FRAG      0         0         0

To display all sockets:

ss -a

To display UDP sockets:

ss -u -a

To display TCP sockets:

ss -t -a

Here you can read ss man: ss

Should methods in a Java interface be declared with or without a public access modifier?

It's totally subjective. I omit the redundant public modifier as it seems like clutter. As mentioned by others - consistency is the key to this decision.

It's interesting to note that the C# language designers decided to enforce this. Declaring an interface method as public in C# is actually a compile error. Consistency is probably not important across languages though, so I guess this is not really directly relevant to Java.

How to echo out the values of this array?

Here is a simple routine for an array of primitive elements:

for ($i = 0; $i < count($mySimpleArray); $i++)
{
   echo $mySimpleArray[$i] . "\n";
}

Set selected item in Android BottomNavigationView

@Override
protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);

   bottomNavigationView.setOnNavigationItemSelectedListener(this);
   Menu menu = bottomNavigationView.getMenu();
   this.onNavigationItemSelected(menu.findItem(R.id.action_favorites));
}

What is the most robust way to force a UIView to redraw?

The guaranteed, rock solid way to force a UIView to re-render is [myView setNeedsDisplay]. If you're having trouble with that, you're likely running into one of these issues:

  • You're calling it before you actually have the data, or your -drawRect: is over-caching something.

  • You're expecting the view to draw at the moment you call this method. There is intentionally no way to demand "draw right now this very second" using the Cocoa drawing system. That would disrupt the entire view compositing system, trash performance and likely create all kinds of artifacting. There are only ways to say "this needs to be drawn in the next draw cycle."

If what you need is "some logic, draw, some more logic," then you need to put the "some more logic" in a separate method and invoke it using -performSelector:withObject:afterDelay: with a delay of 0. That will put "some more logic" after the next draw cycle. See this question for an example of that kind of code, and a case where it might be needed (though it's usually best to look for other solutions if possible since it complicates the code).

If you don't think things are getting drawn, put a breakpoint in -drawRect: and see when you're getting called. If you're calling -setNeedsDisplay, but -drawRect: isn't getting called in the next event loop, then dig into your view hierarchy and make sure you're not trying to outsmart is somewhere. Over-cleverness is the #1 cause of bad drawing in my experience. When you think you know best how to trick the system into doing what you want, you usually get it doing exactly what you don't want.

Regular expression to stop at first match

How about

.*location="([^"]*)".*

This avoids the unlimited search with .* and will match exactly to the first quote.

Python 3 print without parenthesis

Although you need a pair of parentheses to print in Python 3, you no longer need a space after print, because it's a function. So that's only a single extra character.

If you still find typing a single pair of parentheses to be "unnecessarily time-consuming," you can do p = print and save a few characters that way. Because you can bind new references to functions but not to keywords, you can only do this print shortcut in Python 3.

Python 2:

>>> p = print
  File "<stdin>", line 1
    p = print
            ^
SyntaxError: invalid syntax

Python 3:

>>> p = print
>>> p('hello')
hello

It'll make your code less readable, but you'll save those few characters every time you print something.

How can I query a value in SQL Server XML column

You can query the whole tag, or just the specific value. Here I use a wildcard for the xml namespaces.

declare @myDoc xml
set @myDoc = 
'<Root xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://stackoverflow.com">
    <Child>my value</Child>
 </Root>'

select @myDoc.query('/*:Root/*:Child') -- whole tag
select @myDoc.value('(/*:Root/*:Child)[1]', 'varchar(255)') -- only value

How can I update the current line in a C# Windows Console App?

I was doing a search for this to see if the solution I wrote could be optimised for speed. What I wanted was a countdown timer, not just updating the current line. Here's what I came up with. Might be useful to someone

            int sleepTime = 5 * 60;    // 5 minutes

            for (int secondsRemaining = sleepTime; secondsRemaining > 0; secondsRemaining --)
            {
                double minutesPrecise = secondsRemaining / 60;
                double minutesRounded = Math.Round(minutesPrecise, 0);
                int seconds = Convert.ToInt32((minutesRounded * 60) - secondsRemaining);
                Console.Write($"\rProcess will resume in {minutesRounded}:{String.Format("{0:D2}", -seconds)} ");
                Thread.Sleep(1000);
            }
            Console.WriteLine("");

Xcode 6.1 - How to uninstall command line tools?

An excerpt from an apple technical note (Thanks to matthias-bauch)

Xcode includes all your command-line tools. If it is installed on your system, remove it to uninstall your tools.

If your tools were downloaded separately from Xcode, then they are located at /Library/Developer/CommandLineTools on your system. Delete the CommandLineTools folder to uninstall them.

you could easily delete using terminal:

Here is an article that explains how to remove the command line tools but do it at your own risk.Try this only if any of the above doesn't work.

Pass element ID to Javascript function

In jsFiddle by default the code you type into the script block is wrapped in a function executed on window.onload:

<script type='text/javascript'>//<![CDATA[ 
    window.onload = function () {
        function myFunc(id){
            alert(id);     
        }
    }
//]]>  
</script>

Because of this, your function myFunc is not in the global scope so is not available to your html buttons. By changing the option to No-wrap in <head> as Sergio suggests your code isn't wrapped:

<script type='text/javascript'>//<![CDATA[ 
    function myFunc(id){
       alert(id);     
    }
//]]>  
</script>

and so the function is in the global scope and available to your html buttons.

Java AES and using my own Key

You should use a KeyGenerator to generate the Key,

AES key lengths are 128, 192, and 256 bit depending on the cipher you want to use.

Take a look at the tutorial here

Here is the code for Password Based Encryption, this has the password being entered through System.in you can change that to use a stored password if you want.

        PBEKeySpec pbeKeySpec;
        PBEParameterSpec pbeParamSpec;
        SecretKeyFactory keyFac;

        // Salt
        byte[] salt = {
            (byte)0xc7, (byte)0x73, (byte)0x21, (byte)0x8c,
            (byte)0x7e, (byte)0xc8, (byte)0xee, (byte)0x99
        };

        // Iteration count
        int count = 20;

        // Create PBE parameter set
        pbeParamSpec = new PBEParameterSpec(salt, count);

        // Prompt user for encryption password.
        // Collect user password as char array (using the
        // "readPassword" method from above), and convert
        // it into a SecretKey object, using a PBE key
        // factory.
        System.out.print("Enter encryption password:  ");
        System.out.flush();
        pbeKeySpec = new PBEKeySpec(readPassword(System.in));
        keyFac = SecretKeyFactory.getInstance("PBEWithMD5AndDES");
        SecretKey pbeKey = keyFac.generateSecret(pbeKeySpec);

        // Create PBE Cipher
        Cipher pbeCipher = Cipher.getInstance("PBEWithMD5AndDES");

        // Initialize PBE Cipher with key and parameters
        pbeCipher.init(Cipher.ENCRYPT_MODE, pbeKey, pbeParamSpec);

        // Our cleartext
        byte[] cleartext = "This is another example".getBytes();

        // Encrypt the cleartext
        byte[] ciphertext = pbeCipher.doFinal(cleartext);

Winforms issue - Error creating window handle

The out of memory suggestion doesn't seem like a bad lead.

What is your program doing that it gets this error?

Is it creating a great many windows or controls? Does it create them programatically as opposed to at design time? If so, do you do this in a loop? Is that loop infinite? Are you consuming staggering boatloads of memory in some other way?

What happens when you watch the memory used by your application in task manager? Does it skyrocket to the moon? Or better yet, as suggested above use process monitor to dive into the details.

Sending and Parsing JSON Objects in Android

you just need to import this

   import org.json.JSONObject;


  constructing the String that you want to send

 JSONObject param=new JSONObject();
 JSONObject post=new JSONObject();

im using two object because you can have an jsonObject within another

post.put("username(here i write the key)","someusername"(here i put the value);
post.put("message","this is a sweet message");
post.put("image","http://localhost/someimage.jpg");
post.put("time":  "present time");

then i put the post json inside another like this

  param.put("post",post);

this is the method that i use to make a request

 makeRequest(param.toString());

public JSONObject makeRequest(String param)
{
    try
    {

setting the connection

        urlConnection = new URL("your url");
        connection = (HttpURLConnection) urlConnection.openConnection();
        connection.setDoOutput(true);
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-type", "application/json;charset=UTF-8");
        connection.setReadTimeout(60000);
        connection.setConnectTimeout(60000);
        connection.connect();

setting the outputstream

        dataOutputStream = new DataOutputStream(connection.getOutputStream());

i use this to see in the logcat what i am sending

        Log.d("OUTPUT STREAM  " ,param);
        dataOutputStream.writeBytes(param);
        dataOutputStream.flush();
        dataOutputStream.close();

        InputStream in = new BufferedInputStream(connection.getInputStream());
        BufferedReader reader = new BufferedReader(new InputStreamReader(in));
        result = new StringBuilder();
        String line;

here the string is constructed

        while ((line = reader.readLine()) != null)
        {
            result.append(line);
        }

i use this log to see what its comming in the response

         Log.d("INPUTSTREAM: ",result.toString());

instancing a json with the String that contains the server response

        jResponse=new JSONObject(result.toString());

    }
    catch (IOException e) {
        e.printStackTrace();
        return jResponse=null;
    } catch (JSONException e)
    {
        e.printStackTrace();
        return jResponse=null;
    }
    connection.disconnect();
    return jResponse;
}

Get the _id of inserted document in Mongo database in NodeJS

Now you can use insertOne method and in promise's result.insertedId

How to prevent http file caching in Apache httpd (MAMP)

Tried this? Should work in both .htaccess, httpd.conf and in a VirtualHost (usually placed in httpd-vhosts.conf if you have included it from your httpd.conf)

<filesMatch "\.(html|htm|js|css)$">
  FileETag None
  <ifModule mod_headers.c>
     Header unset ETag
     Header set Cache-Control "max-age=0, no-cache, no-store, must-revalidate"
     Header set Pragma "no-cache"
     Header set Expires "Wed, 11 Jan 1984 05:00:00 GMT"
  </ifModule>
</filesMatch>

100% Prevent Files from being cached

This is similar to how google ads employ the header Cache-Control: private, x-gzip-ok="" > to prevent caching of ads by proxies and clients.

From http://www.askapache.com/htaccess/using-http-headers-with-htaccess.html

And optionally add the extension for the template files you are retrieving if you are using an extension other than .html for those.

How to query nested objects?

The two query mechanism work in different ways, as suggested in the docs at the section Subdocuments:

When the field holds an embedded document (i.e, subdocument), you can either specify the entire subdocument as the value of a field, or “reach into” the subdocument using dot notation, to specify values for individual fields in the subdocument:

Equality matches within subdocuments select documents if the subdocument matches exactly the specified subdocument, including the field order.


In the following example, the query matches all documents where the value of the field producer is a subdocument that contains only the field company with the value 'ABC123' and the field address with the value '123 Street', in the exact order:

db.inventory.find( {
    producer: {
        company: 'ABC123',
        address: '123 Street'
    }
});

Run Python script at startup in Ubuntu

If you are on Ubuntu you don't need to write any other code except your Python file's code , Here are the Steps :-

  • Open Dash (The First Icon In Sidebar).
  • Then type Startup Applications and open that app.
  • Here Click the Add Button on the right.
  • There fill in the details and in the command area browse for your Python File and click Ok.
  • Test it by Restarting System . Done . Enjoy !!

what is the most efficient way of counting occurrences in pandas?

When you want to count the frequency of categorical data in a column in pandas dataFrame use: df['Column_Name'].value_counts()

-Source.

How to check if String value is Boolean type in Java?

  • parseBoolean(String) returns true if the String is (case-insensitive) "true", otherwise false
  • valueOf(String) ditto, returns the canonical Boolean Objects
  • getBoolean(String) is a red herring; it fetches the System property of the given name and compares that to "true"

There exists no method to test whether a String encodes a Boolean; for all practical effects, any non-"true"-String is "false".

How to load data from a text file in a PostgreSQL database?

Let consider that your data are in the file values.txt and that you want to import them in the database table myTable then the following query does the job

COPY myTable FROM 'value.txt' (DELIMITER('|'));

https://www.postgresql.org/docs/current/static/sql-copy.html

How to bind Close command to a button

All it takes is a bit of XAML...

<Window x:Class="WCSamples.Window1"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <Window.CommandBindings>
        <CommandBinding Command="ApplicationCommands.Close"
                        Executed="CloseCommandHandler"/>
    </Window.CommandBindings>
    <StackPanel Name="MainStackPanel">
        <Button Command="ApplicationCommands.Close" 
                Content="Close Window" />
    </StackPanel>
</Window>

And a bit of C#...

private void CloseCommandHandler(object sender, ExecutedRoutedEventArgs e)
{
    this.Close();
}

(adapted from this MSDN article)

transform object to array with lodash

2017 update: Object.values, lodash values and toArray do it. And to preserve keys map and spread operator play nice:

_x000D_
_x000D_
// import { toArray, map } from 'lodash'_x000D_
const map = _.map_x000D_
_x000D_
const input = {_x000D_
  key: {_x000D_
    value: 'value'_x000D_
  }_x000D_
}_x000D_
_x000D_
const output = map(input, (value, key) => ({_x000D_
  key,_x000D_
  ...value_x000D_
}))_x000D_
_x000D_
console.log(output)_x000D_
// >> [{key: 'key', value: 'value'}])
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.js"></script>
_x000D_
_x000D_
_x000D_

How to sort a Ruby Hash by number value?

Since value is the last entry, you can do:

metrics.sort_by(&:last)

How to move table from one tablespace to another in oracle 11g

Use sql from sql:

spool output of this to a file:

select 'alter index '||owner||'.'||index_name||' rebuild tablespace TO_TABLESPACE_NAME;' from all_indexes where owner='OWNERNAME';

spoolfile will have something like this:

alter index OWNER.PK_INDEX rebuild tablespace CORRECT_TS_NAME;

How to repeat a char using printf?

printf doesn't do that -- and printf is overkill for printing a single character.

char c = '*';
int count = 42;
for (i = 0; i < count; i ++) {
    putchar(c);
}

Don't worry about this being inefficient; putchar() buffers its output, so it won't perform a physical output operation for each character unless it needs to.

Git - How to close commit editor?

After writing commit message, just press Esc Button and then write :wq or :wq! and then Enter to close the unix file.

Reading large text files with streams in C#

Have a look at the following code snippet. You have mentioned Most files will be 30-40 MB. This claims to read 180 MB in 1.4 seconds on an Intel Quad Core:

private int _bufferSize = 16384;

private void ReadFile(string filename)
{
    StringBuilder stringBuilder = new StringBuilder();
    FileStream fileStream = new FileStream(filename, FileMode.Open, FileAccess.Read);

    using (StreamReader streamReader = new StreamReader(fileStream))
    {
        char[] fileContents = new char[_bufferSize];
        int charsRead = streamReader.Read(fileContents, 0, _bufferSize);

        // Can't do much with 0 bytes
        if (charsRead == 0)
            throw new Exception("File is 0 bytes");

        while (charsRead > 0)
        {
            stringBuilder.Append(fileContents);
            charsRead = streamReader.Read(fileContents, 0, _bufferSize);
        }
    }
}

Original Article

How can I call PHP functions by JavaScript?

This work perfectly for me:

To call a PHP function (with parameters too) you can, like a lot of people said, send a parameter opening the PHP file and from there check the value of the parameter to call the function. But you can also do that lot of people say it's impossible: directly call the proper PHP function, without adding code to the PHP file.

I found a way:

This for JavaScript:

function callPHP(expression, objs, afterHandler) {
        expression = expression.trim();
        var si = expression.indexOf("(");
        if (si == -1)
            expression += "()";
        else if (Object.keys(objs).length > 0) {
            var sfrom = expression.substring(si + 1);
            var se = sfrom.indexOf(")");
            var result = sfrom.substring(0, se).trim();
            if (result.length > 0) {
                var params = result.split(",");
                var theend = expression.substring(expression.length - sfrom.length + se);
                expression = expression.substring(0, si + 1);
                for (var i = 0; i < params.length; i++) {
                    var param = params[i].trim();
                    if (param in objs) {
                        var value = objs[param];
                        if (typeof value == "string")
                            value = "'" + value + "'";
                        if (typeof value != "undefined")
                            expression += value + ",";
                    }
                }
                expression = expression.substring(0, expression.length - 1) + theend;
            }
        }
        var doc = document.location;
        var phpFile = "URL of your PHP file";
        var php =
            "$docl = str_replace('/', '\\\\', '" + doc + "'); $absUrl = str_replace($docl, $_SERVER['DOCUMENT_ROOT'], str_replace('/', '\\\\', '" + phpFile + "'));" +
            "$fileName = basename($absUrl);$folder = substr($absUrl, 0, strlen($absUrl) - strlen($fileName));" +
            "set_include_path($folder);include $fileName;" + expression + ";";
        var url = doc + "/phpCompiler.php" + "?code=" + encodeURIComponent(php);
        $.ajax({
            type: 'GET',
            url: url,
            complete: function(resp){
                var response = resp.responseText;
                afterHandler(response);
            }
        });
    }


This for a PHP file which isn't your PHP file, but another, which path is written in url variable of JS function callPHP , and it's required to evaluate PHP code. This file is called 'phpCompiler.php' and it's in the root directory of your website:

<?php
$code = urldecode($_REQUEST['code']);
$lines = explode(";", $code);
foreach($lines as $line)
    eval(trim($line, " ") . ";");
?>


So, your PHP code remain equals except return values, which will be echoed:

<?php
function add($a,$b){
  $c=$a+$b;
  echo $c;
}
function mult($a,$b){
  $c=$a*$b;
  echo $c;
}

function divide($a,$b){
  $c=$a/$b;
  echo $c;
}
?>


I suggest you to remember that jQuery is required:
Download it from Google CDN:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>

or from Microsoft CDN: "I prefer Google! :)"

<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.1.1.min.js"></script>

Better is to download the file from one of two CDNs and put it as local file, so the startup loading of your website's faster!

The choice is to you!


Now you finished! I just tell you how to use callPHP function. This is the JavaScript to call PHP:

//Names of parameters are custom, they haven't to be equals of these of the PHP file.
//These fake names are required to assign value to the parameters in PHP
//using an hash table.
callPHP("add(num1, num2)", {
            'num1' : 1,
            'num2' : 2
        },
            function(output) {
                alert(output); //This to display the output of the PHP file.
        });

How to echo text during SQL script execution in SQLPLUS

You can change the name of the column, therefore instead of "COUNT(*)" you would have something meaningful. You will have to update your "RowCount.sql" script for that.

For example:

SQL> select count(*) as RecordCountFromTableOne from TableOne;

Will be displayed as:

RecordCountFromTableOne
-----------------------
           0

If you want to have space in the title, you need to enclose it in double quotes

SQL> select count(*) as "Record Count From Table One" from TableOne;

Will be displayed as:

Record Count From Table One
---------------------------
            0

CMake output/build directory

It sounds like you want an out of source build. There are a couple of ways you can create an out of source build.

  1. Do what you were doing, run

    cd /path/to/my/build/folder
    cmake /path/to/my/source/folder
    

    which will cause cmake to generate a build tree in /path/to/my/build/folder for the source tree in /path/to/my/source/folder.

    Once you've created it, cmake remembers where the source folder is - so you can rerun cmake on the build tree with

    cmake /path/to/my/build/folder
    

    or even

    cmake .
    

    if your current directory is already the build folder.

  2. For CMake 3.13 or later, use these options to set the source and build folders

    cmake -B/path/to/my/build/folder -S/path/to/my/source/folder
    
  3. For older CMake, use some undocumented options to set the source and build folders:

    cmake -B/path/to/my/build/folder -H/path/to/my/source/folder
    

    which will do exactly the same thing as (1), but without the reliance on the current working directory.

CMake puts all of its outputs in the build tree by default, so unless you are liberally using ${CMAKE_SOURCE_DIR} or ${CMAKE_CURRENT_SOURCE_DIR} in your cmake files, it shouldn't touch your source tree.

The biggest thing that can go wrong is if you have previously generated a build tree in your source tree (i.e. you have an in source build). Once you've done this the second part of (1) above kicks in, and cmake doesn't make any changes to the source or build locations. Thus, you cannot create an out-of-source build for a source directory with an in-source build. You can fix this fairly easily by removing (at a minimum) CMakeCache.txt from the source directory. There are a few other files (mostly in the CMakeFiles directory) that CMake generates that you should remove as well, but these won't cause cmake to treat the source tree as a build tree.

Since out-of-source builds are often more desirable than in-source builds, you might want to modify your cmake to require out of source builds:

# Ensures that we do an out of source build

MACRO(MACRO_ENSURE_OUT_OF_SOURCE_BUILD MSG)
     STRING(COMPARE EQUAL "${CMAKE_SOURCE_DIR}"
     "${CMAKE_BINARY_DIR}" insource)
     GET_FILENAME_COMPONENT(PARENTDIR ${CMAKE_SOURCE_DIR} PATH)
     STRING(COMPARE EQUAL "${CMAKE_SOURCE_DIR}"
     "${PARENTDIR}" insourcesubdir)
    IF(insource OR insourcesubdir)
        MESSAGE(FATAL_ERROR "${MSG}")
    ENDIF(insource OR insourcesubdir)
ENDMACRO(MACRO_ENSURE_OUT_OF_SOURCE_BUILD)

MACRO_ENSURE_OUT_OF_SOURCE_BUILD(
    "${CMAKE_PROJECT_NAME} requires an out of source build."
)

The above macro comes from a commonly used module called MacroOutOfSourceBuild. There are numerous sources for MacroOutOfSourceBuild.cmake on google but I can't seem to find the original and it's short enough to include here in full.

Unfortunately cmake has usually written a few files by the time the macro is invoked, so although it will stop you from actually performing the build you will still need to delete CMakeCache.txt and CMakeFiles.

You may find it useful to set the paths that binaries, shared and static libraries are written to - in which case see how do I make cmake output into a 'bin' dir? (disclaimer, I have the top voted answer on that question...but that's how I know about it).

Excel telling me my blank cells aren't blank

Found another way. Set AutoFilter for all columns (important or you will misalign data) by selecting the header row > 'Data' tab > Sort and filter - 'Filter'. Use drop-down in first data column, untick 'Select all' and select only '(Blanks)' option > [OK]. Highlight rows (now all together) > right click > 'Delete row'. Head back to the drop-down > 'Select all'. Presto :)

Android java.lang.NoClassDefFoundError

I've run into this problem a few times opening old projects that include other Android libraries. What works for me is to:

move Android to the top in the Order and Export tab and deselecting it.

Yes, this really makes the difference. Maybe it's time for me to ditch ADT for Android Studio!

How to get the version of ionic framework?

At some point in time the object changed from ionic to an uppercase Ionic.

As of July 2017 you need to put Ionic.version into your console to get the version number.

Print Pdf in C#

A very straight forward approach is to use an installed Adobe Reader or any other PDF viewer capable of printing:

Process p = new Process( );
p.StartInfo = new ProcessStartInfo( )
{
    CreateNoWindow = true,
    Verb = "print",
    FileName = path //put the correct path here
};
p.Start( );

Another way is to use a third party component, e.g. PDFView4NET

How to resolve "could not execute statement; SQL [n/a]; constraint [numbering];"?

Hibernate tries to insert data that violate underlying database integrity contraints.

There's probably misconfiguration in hibernate persistent classes and/or mapping configuration (*.hbm.xml or annotations in persitent classes).

Maybe a property of the bean you want to save is not type-compatible with its related field in database (could explain the constraint [numbering] part).

Modifying a file inside a jar

Java jar files are the same format as zip files - so if you have a zip file utility that would let you modify an archive, you have your foot in the door. Second problem is, if you want to recompile a class or something, you probably will just have to re-build the jar; but a text file or something (xml, for instance) should be easily enough modified.

How to initialize const member variable in a class?

Another possible way are namespaces:

#include <iostream>

namespace mySpace {
   static const int T = 100; 
}

using namespace std;

class T1
{
   public:
   T1()
   {
       cout << "T1 constructor: " << mySpace::T << endl;
   }
};

The disadvantage is that other classes can also use the constants if they include the header file.

Quotation marks inside a string

You need to escape the quotation marks:

String name = "\"john\"";

Check if value exists in the array (AngularJS)

You could use indexOf function.

if(list.indexOf(createItem.artNr) !== -1) {
  $scope.message = 'artNr already exists!';
}

More about indexOf:

Developing for Android in Eclipse: R.java not regenerating

Here's one more answer that I found, after none of the previous 30 answers helped.

I found my issue in the strings.xml file, although it is very very odd. I stripped down my app to bare minimum and this was the only thing that came to light. I can even replicate it on a brand new empty app.

In the strings.xml file, this compiles (and generates the R.java file):

<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">Test_My_App</string>
<string name="action_settings">Settings</string>
<string name="hello_world">Hello world!</string>
</resources>

However, this is not:

<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="hello_world">Hello world</string>
<string name="app_name">My_App</string>
<string name="action_refresh">Refresh</string>
</resources>

The "funny" thins is that I removed the action_settings several days ago. I've cleaned my code since then and never had any issues. I added additional strings to the strings.xml file today and after cleaning the code the wheels came off. Also, if I re-arrange the order of the same 3 string lines, and clean my code, the R.java file does not get re-generated.

There's my solution to my particular issue.

I hope it helps somebody...

Check if a file exists locally using JavaScript only

Try this:

window.onclick=(function(){
  try {
    var file = window.open("file://mnt/sdcard/download/Click.ogg");
    setTimeout('file.close()', 100);
    setTimeout("alert('Audio file found. Have a nice day!');", 101);
  } catch(err) {
    var wantstodl=confirm("Warning:\n the file, Click.ogg is not found.\n do you want to download it?\n "+err.message);
    if (wantstodl) {
      window.open("https://www.dropbox.com/s/qs9v6g2vru32xoe/Click.ogg?dl=1"); //downloads the audio file
    }
  }
});

I can't access http://localhost/phpmyadmin/

Resolving same problem on Ubuntu 14.04, I use code:

    sudo ln -s /etc/phpmyadmin/apache.conf /etc/apache2/conf-enabled/phpmyadmin.conf
    sudo /etc/init.d/apache2 reload

it is because since Ubuntu 13, Apache loads configuration files from the /etc/apache2/conf-enabled directory.

Ubuntu Documentation

How to set the default value for radio buttons in AngularJS?

<input type="radio" name="gender" value="male"<%=rs.getString(6).equals("male") ? "checked='checked'": "" %>: "checked='checked'" %> >Male
               <%=rs.getString(6).equals("male") ? "checked='checked'": "" %>

case in sql stored procedure on SQL Server

CASE isn't used for flow control... for this, you would need to use IF...

But, there's a set-based solution to this problem instead of the procedural approach:

UPDATE tblEmployee
SET 
  InOffice = CASE WHEN @NewStatus = 'InOffice' THEN -1 ELSE InOffice END,
  OutOffice = CASE WHEN @NewStatus = 'OutOffice' THEN -1 ELSE OutOffice END,
  Home = CASE WHEN @NewStatus = 'Home' THEN -1 ELSE Home END
WHERE EmpID = @EmpID

Note that the ELSE will preserves the original value if the @NewStatus condition isn't met.

Set up adb on Mac OS X

For macOS Users Updated to MacOs Catalina,

~/.bash_profile changed to ~/.zshrc

So ,to run adb command and all other commands already exported to ~/.bash_profile easy walkaround is to export bash_profile to zshrc

To do that,

1) Navigate to the home directory in finder

2) I used Cmd + Shift + . to show the hidden files in Finder

3) Create .zshrc file if already not exist

4) Add line "source ~/.bash_profile" without quotes

5) Save

6) Quit and open terminal

start using adb devices

How to display Oracle schema size with SQL query?

select T.TABLE_NAME, T.TABLESPACE_NAME, t.avg_row_len*t.num_rows from dba_tables t
order by T.TABLE_NAME asc

See e.g. http://www.dba-oracle.com/t_script_oracle_table_size.htm for more options

Best way to create enum of strings?

Custom String Values for Enum

from http://javahowto.blogspot.com/2006/10/custom-string-values-for-enum.html

The default string value for java enum is its face value, or the element name. However, you can customize the string value by overriding toString() method. For example,

public enum MyType {
  ONE {
      public String toString() {
          return "this is one";
      }
  },

  TWO {
      public String toString() {
          return "this is two";
      }
  }
}

Running the following test code will produce this:

public class EnumTest {
  public static void main(String[] args) {
      System.out.println(MyType.ONE);
      System.out.println(MyType.TWO);
  }
}


this is one
this is two

Ways to implement data versioning in MongoDB

If you are using mongoose, I have found the following plugin to be a useful implementation of the JSON Patch format

mongoose-patch-history

eclipse won't start - no java virtual machine was found

This happened to me also. And I found the javaw.exe in C:\Windows\System32 got deleted after the windows update. Copied one more time and Eclipse started all fine.

Java JDBC - How to connect to Oracle using Service Name instead of SID

http://download.oracle.com/docs/cd/B28359_01/java.111/b31224/urls.htm#BEIDHCBA

Thin-style Service Name Syntax

Thin-style service names are supported only by the JDBC Thin driver. The syntax is:

@//host_name:port_number/service_name

For example:

jdbc:oracle:thin:scott/tiger@//myhost:1521/myservicename

So I would try:

jdbc:oracle:thin:@//oracle.hostserver2.mydomain.ca:1522/ABCD

Also, per Robert Greathouse's answer, you can also specify the TNS name in the JDBC URL as below:

jdbc:oracle:thin:@(DESCRIPTION =(ADDRESS_LIST =(ADDRESS =(PROTOCOL=TCP)(HOST=blah.example.com)(PORT=1521)))(CONNECT_DATA=(SID=BLAHSID)(GLOBAL_NAME=BLAHSID.WORLD)(SERVER=DEDICATED)))

Submit HTML form on self page

You can do it using the same page on the action attribute: action='<yourpage>'

wildcard * in CSS for classes

If you don't need the unique identifier for further styling of the divs and are using HTML5 you could try and go with custom Data Attributes. Read on here or try a google search for HTML5 Custom Data Attributes

How do I drop a foreign key constraint only if it exists in sql server?

In SQL Server 2016 you can use DROP IF EXISTS:

CREATE TABLE t(id int primary key, 
               parentid int
                    constraint tpartnt foreign key references t(id))
GO
ALTER TABLE t
DROP CONSTRAINT IF EXISTS tpartnt
GO
DROP TABLE IF EXISTS t

See http://blogs.msdn.com/b/sqlserverstorageengine/archive/2015/11/03/drop-if-exists-new-thing-in-sql-server-2016.aspx

Solve error javax.mail.AuthenticationFailedException

There are a few steps you have to keep in mind.

Now there are two scenarios If you are developing it in your local machine login to your google account in your browser, this way the google recognizes the machine.

If you have deployed the application onto a server then after the first request you will get an authentication error, so you have to give access to the server, just go here to give access- https://www.google.com/accounts/DisplayUnlockCaptcha

Nullable property to entity field, Entity Framework through Code First

The other option is to tell EF to allow the column to be null:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
        modelBuilder.Entity<SomeObject>().Property(m => m.somefield).IsOptional();            
        base.OnModelCreating(modelBuilder);
}

This code should be in the object that inherits from DbContext.

Python conditional assignment operator

I would use

x = 'default' if not x else x

Much shorter than all of your alternatives suggested here, and straight to the point. Read, "set x to 'default' if x is not set otherwise keep it as x." If you need None, 0, False, or "" to be valid values however, you will need to change this behavior, for instance:

valid_vals = ("", 0, False) # We want None to be the only un-set value

x = 'default' if not x and x not in valid_vals else x

This sort of thing is also just begging to be turned into a function you can use everywhere easily:

setval_if = lambda val: 'default' if not val and val not in valid_vals else val

at which point, you can use it as:

>>> x = None # To set it to something not valid
>>> x = setval_if(x) # Using our special function is short and sweet now!
>>> print x # Let's check to make sure our None valued variable actually got set
'default'

Finally, if you are really missing your Ruby infix notation, you could overload ||=| (or something similar) by following this guy's hack: http://code.activestate.com/recipes/384122-infix-operators/

jQuery UI: Datepicker set year range dropdown to 100 years

This is a bit late in the day for suggesting this, given how long ago the original question was posted, but this is what I did.

I needed a range of 70 years, which, while not as much as 100, is still too many years for the visitor to scroll through. (jQuery does step through year in groups, but that's a pain in the patootie for most people.)

The first step was to modify the JavaScript for the datepicker widget: Find this code in jquery-ui.js or jquery-ui-min.js (where it will be minimized):

for (a.yearshtml+='<select class="ui-datepicker-year" onchange="DP_jQuery_'+y+".datepicker._selectMonthYear('#"+
a.id+"', this, 'Y');\" onclick=\"DP_jQuery_"+y+".datepicker._clickMonthYear('#"+a.id+"');\">";b<=g;b++)
 a.yearshtml+='<option value="'+b+'"'+(b==c?' selected="selected"':"")+">"+b+"</option>";
a.yearshtml+="</select>";

And replace it with this:

a.yearshtml+='<select class="ui-datepicker-year" onchange="DP_jQuery_'+y+
 ".datepicker._selectMonthYear('#"+a.id+"', this, 'Y');
 \" onclick=\"DP_jQuery_"+y+".datepicker._clickMonthYear('#"+a.id+"');
 \">";
for(opg=-1;b<=g;b++) {
    a.yearshtml+=((b%10)==0 || opg==-1 ?
        (opg==1 ? (opg=0, '</optgroup>') : '')+
        (b<(g-10) ? (opg=1, '<optgroup label="'+b+' >">') : '') : '')+
        '<option value="'+b+'"'+(b==c?' selected="selected"':"")+">"+b+"</option>";
}
a.yearshtml+="</select>";

This surrounds the decades (except for the current) with OPTGROUP tags.

Next, add this to your CSS file:

.ui-datepicker OPTGROUP { font-weight:normal; }
.ui-datepicker OPTGROUP OPTION { display:none; text-align:right; }
.ui-datepicker OPTGROUP:hover OPTION { display:block; }

This hides the decades until the visitor mouses over the base year. Your visitor can scroll through any number of years quickly.

Feel free to use this; just please give proper attribution in your code.

Permission denied for relation

Make sure you log into psql as the owner of the tables. to find out who own the tables use \dt

psql -h CONNECTION_STRING DBNAME -U OWNER_OF_THE_TABLES

then you can run the GRANTS

How to wait in bash for several subprocesses to finish and return exit code !=0 when any subprocess ends with code !=0?

I think that the most straight forward way to run jobs in parallel and check for status is using temporary files. There are already a couple similar answers (e.g. Nietzche-jou and mug896).

#!/bin/bash
rm -f fail
for i in `seq 0 9`; do
  doCalculations $i || touch fail &
done
wait 
! [ -f fail ]

The above code is not thread safe. If you are concerned that the code above will be running at the same time as itself, it's better to use a more unique file name, like fail.$$. The last line is to fulfill the requirement: "return exit code 1 when any of subprocesses ends with code !=0?" I threw an extra requirement in there to clean up. It may have been clearer to write it like this:

#!/bin/bash
trap 'rm -f fail.$$' EXIT
for i in `seq 0 9`; do
  doCalculations $i || touch fail.$$ &
done
wait 
! [ -f fail.$$ ] 

Here is a similar snippet for gathering results from multiple jobs: I create a temporary directory, story the outputs of all the sub tasks in a separate file, and then dump them for review. This doesn't really match the question - I'm throwing it in as a bonus:

#!/bin/bash
trap 'rm -fr $WORK' EXIT

WORK=/tmp/$$.work
mkdir -p $WORK
cd $WORK

for i in `seq 0 9`; do
  doCalculations $i >$i.result &
done
wait 
grep $ *  # display the results with filenames and contents

What is the difference between Python's list methods append and extend?

This is the equivalent of append and extend using the + operator:

>>> x = [1,2,3]
>>> x
[1, 2, 3]
>>> x = x + [4,5,6] # Extend
>>> x
[1, 2, 3, 4, 5, 6]
>>> x = x + [[7,8]] # Append
>>> x
[1, 2, 3, 4, 5, 6, [7, 8]]

TimePicker Dialog from clicking EditText

You can use the below code in the onclick listener of edittext

  TimePickerDialog timePickerDialog = new TimePickerDialog(MainActivity.this,
    new TimePickerDialog.OnTimeSetListener() {

        @Override
        public void onTimeSet(TimePicker view, int hourOfDay,
                              int minute) {

            tv_time.setText(hourOfDay + ":" + minute);
        }
    }, hour, minute, false);
     timePickerDialog.show();

You can see the full code at Android timepicker example

Executing "SELECT ... WHERE ... IN ..." using MySQLdb

this works for me:

myTuple= tuple(myList)
sql="select fooid from foo where bar in "+str(myTuple)
cursor.execute(sql)

Accessing Arrays inside Arrays In PHP

You can access the inactive tags array with (assuming $myArray contains the array)

$myArray['inactiveTags'];

Your question doesn't seem to go beyond accessing the contents of the inactiveTags key so I can only speculate with what your final goal is.

The first key:value pair in the inactiveTags array is

array ('195' => array(
                 'id' => 195, 
                 'tag' => 'auto')
      )

To access the tag value, you would use

$myArray['inactiveTags'][195]['tag']; // auto

If you want to loop through each inactiveTags element, I would suggest:

foreach($myArray['inactiveTags'] as $value) {
  print $value['id'];
  print $value['tag'];
}

This will print all the id and tag values for each inactiveTag

Edit:: For others to see, here is a var_dump of the array provided in the question since it has not readible

array
  'languages' => 
    array
      76 => 
        array
          'id' => string '76' (length=2)
          'tag' => string 'Deutsch' (length=7)
  'targets' => 
    array
      81 => 
        array
          'id' => string '81' (length=2)
          'tag' => string 'Deutschland' (length=11)
  'tags' => 
    array
      7866 => 
        array
          'id' => string '7866' (length=4)
          'tag' => string 'automobile' (length=10)
      17800 => 
        array
          'id' => string '17800' (length=5)
          'tag' => string 'seat leon' (length=9)
      17801 => 
        array
          'id' => string '17801' (length=5)
          'tag' => string 'seat leon cupra' (length=15)
  'inactiveTags' => 
    array
      195 => 
        array
          'id' => string '195' (length=3)
          'tag' => string 'auto' (length=4)
      17804 => 
        array
          'id' => string '17804' (length=5)
          'tag' => string 'coupès' (length=6)
      17805 => 
        array
          'id' => string '17805' (length=5)
          'tag' => string 'fahrdynamik' (length=11)
      901 => 
        array
          'id' => string '901' (length=3)
          'tag' => string 'fahrzeuge' (length=9)
      17802 => 
        array
          'id' => string '17802' (length=5)
          'tag' => string 'günstige neuwagen' (length=17)
      1991 => 
        array
          'id' => string '1991' (length=4)
          'tag' => string 'motorsport' (length=10)
      2154 => 
        array
          'id' => string '2154' (length=4)
          'tag' => string 'neuwagen' (length=8)
      10660 => 
        array
          'id' => string '10660' (length=5)
          'tag' => string 'seat' (length=4)
      17803 => 
        array
          'id' => string '17803' (length=5)
          'tag' => string 'sportliche ausstrahlung' (length=23)
      74 => 
        array
          'id' => string '74' (length=2)
          'tag' => string 'web 2.0' (length=7)
  'categories' => 
    array
      16082 => 
        array
          'id' => string '16082' (length=5)
          'tag' => string 'Auto & Motorrad' (length=15)
      51 => 
        array
          'id' => string '51' (length=2)
          'tag' => string 'Blogosphäre' (length=11)
      66 => 
        array
          'id' => string '66' (length=2)
          'tag' => string 'Neues & Trends' (length=14)
      68 => 
        array
          'id' => string '68' (length=2)
          'tag' => string 'Privat' (length=6)

How do I access command line arguments in Python?

First, You will need to import sys

sys - System-specific parameters and functions

This module provides access to certain variables used and maintained by the interpreter, and to functions that interact strongly with the interpreter. This module is still available. I will edit this post in case this module is not working anymore.

And then, you can print the numbers of arguments or what you want here, the list of arguments.

Follow the script below :

#!/usr/bin/python

import sys

print 'Number of arguments entered :' len(sys.argv)

print 'Your argument list :' str(sys.argv)

Then, run your python script :

$ python arguments_List.py chocolate milk hot_Chocolate

And you will have the result that you were asking :

Number of arguments entered : 4
Your argument list : ['arguments_List.py', 'chocolate', 'milk', 'hot_Chocolate']

Hope that helped someone.

Excel: How to check if a cell is empty with VBA?

IsEmpty() would be the quickest way to check for that.

IsNull() would seem like a similar solution, but keep in mind Null has to be assigned to the cell; it's not inherently created in the cell.

Also, you can check the cell by:

count()

counta()

Len(range("BCell").Value) = 0

Why doesn't catching Exception catch RuntimeException?

The premise of the question is flawed, because catching Exception does catch RuntimeException. Demo code:

public class Test {
    public static void main(String[] args) {
        try {
            throw new RuntimeException("Bang");
        } catch (Exception e) {
            System.out.println("I caught: " + e);
        }
    }
}

Output:

I caught: java.lang.RuntimeException: Bang

Your loop will have problems if:

  • callbacks is null
  • anything modifies callbacks while the loop is executing (if it were a collection rather than an array)

Perhaps that's what you're seeing?

JQuery Ajax Post results in 500 Internal Server Error

I experienced a similar compound error, which required two solutions. In my case the technology stack was MVC/ ASP.NET / IIS/ JQuery. The server side was failing with a 500 error, and this was occurring before the request was handled by the controller making the debug on the server side difficult.

The following client side debug enabled me to determine the server error

In the $.ajax error call back, display the error detail to the console

  error: (error) => {
                     console.log(JSON.stringify(error));
   }

This at least, enabled me to view the initial server error

“The JSON request was too large to be serialized”

This was resolved in the client web.config

<appSettings>
    <add key="aspnet:MaxJsonDeserializerMembers" value="150000" />

However, the request still failed. But this time with a different error that I was now able to debug on the server side

“Request Entity too large”

This was resolved by adding the following to the service web.config

<configuration>
…
 <system.serviceModel>
    <bindings>
      <basicHttpBinding>
        <binding maxBufferSize="2147483647" maxReceivedMessageSize="2147483647" maxBufferPoolSize="524288">
          <readerQuotas maxDepth="32" maxStringContentLength="2147483647"
            maxArrayLength="2147483647" maxBytesPerRead="2147483647" maxNameTableCharCount="2147483647"  />
        </binding>
      </basicHttpBinding>
    </bindings>

The configuration values may require further tuning, but at least it resolved the server errors caused by the ajax post.

Path.Combine for URLs?

I used this code to solve the problem:

string[] brokenBaseUrl = Context.Url.TrimEnd('/').Split('/');
string[] brokenRootFolderPath = RootFolderPath.Split('/');

for (int x = 0; x < brokenRootFolderPath.Length; x++)
{
    //if url doesn't already contain member, append it to the end of the string with / in front
    if (!brokenBaseUrl.Contains(brokenRootFolderPath[x]))
    {
        if (x == 0)
        {
            RootLocationUrl = Context.Url.TrimEnd('/');
        }
        else
        {
            RootLocationUrl += String.Format("/{0}", brokenRootFolderPath[x]);
        }
    }
}

Rounding a number to the nearest 5 or 10 or X

'Example: Round 499 to nearest 5. You would use the ROUND() FUNCTION.

a = inputbox("number to be rounded")
 b = inputbox("Round to nearest _______ ")


  strc = Round(A/B)
  strd = strc*B


 msgbox( a & ",  Rounded to the nearest " & b & ", is" & vbnewline & strd)

How do I catch a PHP fatal (`E_ERROR`) error?

Not really. Fatal errors are called that, because they are fatal. You can't recover from them.

Update values from one column in same table to another in SQL Server

update TABLE_1 a set COLUMN_1 = (select COLUMN_2 from TABLE_1 b where a.ID = b.ID)

How to empty a list?

lst *= 0

has the same effect as

lst[:] = []

It's a little simpler and maybe easier to remember. Other than that there's not much to say

The efficiency seems to be about the same

Return JsonResult from web api without its properties

When using WebAPI, you should just return the Object rather than specifically returning Json, as the API will either return JSON or XML depending on the request.

I am not sure why your WebAPI is returning an ActionResult, but I would change the code to something like;

public IEnumerable<ListItems> GetAllNotificationSettings()
{
    var result = new List<ListItems>();
    // Filling the list with data here...

    // Then I return the list
    return result;
}

This will result in JSON if you are calling it from some AJAX code.

P.S WebAPI is supposed to be RESTful, so your Controller should be called ListItemController and your Method should just be called Get. But that is for another day.

How Can I Override Style Info from a CSS Class in the Body of a Page?

Eli, it is important to remember that in css specificity goes a long way. If your inline css is using the !important and isn't overriding the imported stylesheet rules then closely observe the code using a tool such as 'firebug' for firefox. It will show you the css being applied to your element. If there is a syntax error firebug will show you in the warning panel that it has thrown out the declaration.

Also remember that in general an id is more specific than a class is more specific than an element.

Hope that helps.

-Rick

Using git to get just the latest revision

Use git clone with the --depth option set to 1 to create a shallow clone with a history truncated to the latest commit.

For example:

git clone --depth 1 https://github.com/user/repo.git

To also initialize and update any nested submodules, also pass --recurse-submodules and to clone them shallowly, also pass --shallow-submodules.

For example:

git clone --depth 1 --recurse-submodules --shallow-submodules https://github.com/user/repo.git

Image style height and width not taken in outlook mails

I had the pleasure of creating an email for outlook 2010 based on sharepoint data. But when creating an outlook email, outlook in its wisdom reduces the image width and height to cm. Interestingly using the width and height kicks in correctly when you forward the email but not when you open it.

Hack Fix:

I had an image [720px X 150px] which should be [19.05cm X 3.98cm]. BUT outlook set the image width and height to [15.24cm X 3.18cm]. Clearly this is a problem.

The hack I used was setting the html image tag as follows:

<img src="...." style="width:720px; heigh:150px" width="900" height="187.5" />

Why that width and height?

Well it is the ratio (25% increase) between

  • what outlook was saying and
  • what it should be by adding 25% of the current size; which is (720 X 1.25 = 900) and (150 X 1.25 = 187.5).

Its not pretty but it works.

Prevent HTML5 video from being downloaded (right-click saved)?

We could make that not so easy by hiding context menu, like this:

<video oncontextmenu="return false;"  controls>
  <source src="https://yoursite.com/yourvideo.mp4" >
</video>

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

It's called spread attributes and its aim is to make the passing of props easier.

Let us imagine that you have a component that accepts N number of properties. Passing these down can be tedious and unwieldy if the number grows.

<Component x={} y={} z={} />

Thus instead you do this, wrap them up in an object and use the spread notation

var props = { x: 1, y: 1, z:1 };
<Component {...props} />

which will unpack it into the props on your component, i.e., you "never" use {... props} inside your render() function, only when you pass the props down to another component. Use your unpacked props as normal this.props.x.

Rails 3 check if attribute changed

ActiveModel::Dirty didn't work for me because the @model.update_attributes() hid the changes. So this is how I detected changes it in an update method in a controller:

def update
  @model = Model.find(params[:id])
  detect_changes

  if @model.update_attributes(params[:model])
    do_stuff if attr_changed?
  end
end

private

def detect_changes
  @changed = []
  @changed << :attr if @model.attr != params[:model][:attr]
end

def attr_changed?
  @changed.include :attr
end

If you're trying to detect a lot of attribute changes it could get messy though. Probably shouldn't do this in a controller, but meh.

Proper usage of Optional.ifPresent()

Use flatMap. If a value is present, flatMap returns a sequential Stream containing only that value, otherwise returns an empty Stream. So there is no need to use ifPresent() . Example:

list.stream().map(data -> data.getSomeValue).map(this::getOptinalValue).flatMap(Optional::stream).collect(Collectors.toList());

Get the last day of the month in SQL

I wrote following function, it works.

It returns datetime data type. Zero hour, minute, second, miliseconds.

CREATE Function [dbo].[fn_GetLastDate]
(
    @date datetime
)
returns datetime
as
begin

declare @result datetime

 select @result = CHOOSE(month(@date),  
 DATEADD(DAY, 31 -day(@date), @date),
 IIF(YEAR(@date) % 4 = 0, DATEADD(DAY, 29 -day(@date), @date), DATEADD(DAY, 28 -day(@date), @date)), 
 DATEADD(DAY, 31 -day(@date), @date) ,
 DATEADD(DAY, 30 -day(@date), @date), 
 DATEADD(DAY, 31 -day(@date), @date),
 DATEADD(DAY, 30 -day(@date), @date), 
 DATEADD(DAY, 31 -day(@date), @date),
 DATEADD(DAY, 31 -day(@date), @date),
 DATEADD(DAY, 30 -day(@date), @date),
 DATEADD(DAY, 31 -day(@date), @date),
 DATEADD(DAY, 30 -day(@date), @date), 
 DATEADD(DAY, 31 -day(@date), @date))

 return convert(date, @result)

end

It's very easy to use. 2 example:

select [dbo].[fn_GetLastDate]('2016-02-03 12:34:12')

select [dbo].[fn_GetLastDate](GETDATE())

How to connect HTML Divs with Lines?

Definitely possible with any number of libraries and/or HTML5 technologies. You could possible hack something together in pure CSS by using something like the border-bottom property, but it would probably be horribly hacky.

If you're serious about this, you should take a look at a JS library for canvas drawing or SVG. For example, something like http://www.graphjs.org/ or http://jsdraw2dx.jsfiction.com/

MySQL - UPDATE query based on SELECT Query

I found this question in looking for my own solution to a very complex join. This is an alternative solution, to a more complex version of the problem, which I thought might be useful.

I needed to populate the product_id field in the activities table, where activities are numbered in a unit, and units are numbered in a level (identified using a string ??N), such that one can identify activities using an SKU ie L1U1A1. Those SKUs are then stored in a different table.

I identified the following to get a list of activity_id vs product_id:-

SELECT a.activity_id, w.product_id 
  FROM activities a 
  JOIN units USING(unit_id) 
  JOIN product_types USING(product_type_id) 
  JOIN web_products w 
    ON sku=CONCAT('L',SUBSTR(product_type_code,3), 'U',unit_index, 'A',activity_index)

I found that that was too complex to incorporate into a SELECT within mysql, so I created a temporary table, and joined that with the update statement:-

CREATE TEMPORARY TABLE activity_product_ids AS (<the above select statement>);

UPDATE activities a
  JOIN activity_product_ids b
    ON a.activity_id=b.activity_id 
  SET a.product_id=b.product_id;

I hope someone finds this useful

How can I get a list of all classes within current module in Python?

What about

g = globals().copy()
for name, obj in g.iteritems():

?

Convert List into Comma-Separated String

static void Main(string[] args){          
List<string> listStrings = new List<string>() { "C#", "Asp.Net", "SQL Server", "PHP", "Angular" };  
string CommaSeparateString = GenerateCommaSeparateStringFromList(listStrings);  
Console.Write(CommaSeparateString);  
Console.ReadKey();}
private static string GenerateCommaSeparateStringFromList(List<string> listStrings){return String.Join(",", listStrings);}

Convert a list of string to comma separated string C#

set up device for development (???????????? no permissions)

Enter the following commands:

adb kill-server
sudo ./adb start-server
adb devices

This happens when you are not running adb server as root.

List of IP addresses/hostnames from local network in Python

I have collected the following functionality from some other threads and it works for me in Ubuntu.

import os
import socket    
import multiprocessing
import subprocess
import os


def pinger(job_q, results_q):
    """
    Do Ping
    :param job_q:
    :param results_q:
    :return:
    """
    DEVNULL = open(os.devnull, 'w')
    while True:

        ip = job_q.get()

        if ip is None:
            break

        try:
            subprocess.check_call(['ping', '-c1', ip],
                                  stdout=DEVNULL)
            results_q.put(ip)
        except:
            pass


def get_my_ip():
    """
    Find my IP address
    :return:
    """
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    s.connect(("8.8.8.8", 80))
    ip = s.getsockname()[0]
    s.close()
    return ip


def map_network(pool_size=255):
    """
    Maps the network
    :param pool_size: amount of parallel ping processes
    :return: list of valid ip addresses
    """

    ip_list = list()

    # get my IP and compose a base like 192.168.1.xxx
    ip_parts = get_my_ip().split('.')
    base_ip = ip_parts[0] + '.' + ip_parts[1] + '.' + ip_parts[2] + '.'

    # prepare the jobs queue
    jobs = multiprocessing.Queue()
    results = multiprocessing.Queue()

    pool = [multiprocessing.Process(target=pinger, args=(jobs, results)) for i in range(pool_size)]

    for p in pool:
        p.start()

    # cue hte ping processes
    for i in range(1, 255):
        jobs.put(base_ip + '{0}'.format(i))

    for p in pool:
        jobs.put(None)

    for p in pool:
        p.join()

    # collect he results
    while not results.empty():
        ip = results.get()
        ip_list.append(ip)

    return ip_list


if __name__ == '__main__':

    print('Mapping...')
    lst = map_network()
    print(lst)

T-SQL: Export to new Excel file

Use PowerShell:

$Server = "TestServer"
$Database = "TestDatabase"
$Query = "select * from TestTable"
$FilePath = "C:\OutputFile.csv"

# This will overwrite the file if it already exists.
Invoke-Sqlcmd -Query $Query -Database $Database -ServerInstance $Server | Export-Csv $FilePath

In my usual cases, all I really need is a CSV file that can be read by Excel. However, if you need an actual Excel file, then tack on some code to convert the CSV file to an Excel file. This answer gives a solution for this, but I've not tested it.

How do I mock a service that returns promise in AngularJS Jasmine unit test?

using sinon :

const mockAction = sinon.stub(MyService.prototype,'actionBeingCalled')
                     .returns(httpPromise(200));

Known that, httpPromise can be :

const httpPromise = (code) => new Promise((resolve, reject) =>
  (code >= 200 && code <= 299) ? resolve({ code }) : reject({ code, error:true })
);

Open a URL in a new tab (and not a new window)

The browser will always open the link in a new tab if the link is on the same domain (on the same website). If the link is on some other domain it will open it in a new tab/window, depending on browser settings.

So, according to this, we can use:

<a class="my-link" href="http://www.mywebsite.com" rel="http://www.otherwebsite.com">new tab</a>

And add some jQuery code:

jQuery(document).ready(function () {
    jQuery(".my-link").on("click",function(){
        var w = window.open('http://www.mywebsite.com','_blank');
        w.focus();
        w.location.href = jQuery(this).attr('rel');
        return false;
    });
});

So, first open new window on same website with _blank target (it will open it in new tab), and then open your desired website inside that new window.

What does this GCC error "... relocation truncated to fit..." mean?

Remember to tackle error messages in order. In my case, the error above this one was "undefined reference", and I visually skipped over it to the more interesting "relocation truncated" error. In fact, my problem was an old library that was causing the "undefined reference" message. Once I fixed that, the "relocation truncated" went away also.

Create a view with ORDER BY clause

In order to add an ORDER BY to a View Perform the following

CREATE VIEW [dbo].[SQLSTANDARDS_PSHH]
AS


SELECT TOP 99999999999999
Column1,
Column2
FROM
dbo.Table
Order by
Column1

How to get value of Radio Buttons?

You need to check one if you have two

if(rbMale.Checked)
{

}
else
{

}

You need to check all the checkboxes if more then two

if(rb1.Checked)
{

}
else if(rb2.Checked)
{

}
else if(rb3.Checked)
{

}

htaccess - How to force the client's browser to clear the cache?

You can not force the browsers to clear the cache.

Your .html file seems to be re-loaded sooner as it expires after 10 days. What you have to do is to update your .html file and move all your files to a new folder such as version-2/ or append a version identifier to each file such as mypicture-2.jpg. Then you reference these new files in your .html file and the browser will load them again because the location changed.

How to remove leading zeros using C#

I just crafted this as I needed a good, simple way.

If it gets to the final digit, and if it is a zero, it will stay.

You could also use a foreach loop instead for super long strings.

I just replace each leading oldChar with the newChar.


This is great for a problem I just solved, after formatting an int into a string.

    /* Like this: */
    int counterMax = 1000;
    int counter = ...;
    string counterString = counter.ToString($"D{counterMax.ToString().Length}");
    counterString = RemoveLeadingChars('0', ' ', counterString);
    string fullCounter = $"({counterString}/{counterMax})";
    // = (   1/1000) ... ( 430/1000) ... (1000/1000)

    static string RemoveLeadingChars(char oldChar, char newChar, char[] chars)
    {
        string result = "";
        bool stop = false;
        for (int i = 0; i < chars.Length; i++)
        {
            if (i == (chars.Length - 1)) stop = true;
            if (!stop && chars[i] == oldChar) chars[i] = newChar;
            else stop = true;
            result += chars[i];
        }
        return result;
    }

    static string RemoveLeadingChars(char oldChar, char newChar, string text)
    {
        return RemoveLeadingChars(oldChar, newChar, text.ToCharArray());
    }

I always tend to make my functions suitable for my own library, so there are options.

How to iterate through table in Lua?

For those wondering why ipairs doesn't print all the values of the table all the time, here's why (I would comment this, but I don't have enough good boy points).

The function ipairs only works on tables which have an element with the key 1. If there is an element with the key 1, ipairs will try to go as far as it can in a sequential order, 1 -> 2 -> 3 -> 4 etc until it cant find an element with a key that is the next in the sequence. The order of the elements does not matter.

Tables that do not meet those requirements will not work with ipairs, use pairs instead.

Examples:

ipairsCompatable = {"AAA", "BBB", "CCC"}
ipairsCompatable2 = {[1] = "DDD", [2] = "EEE", [3] = "FFF"}
ipairsCompatable3 = {[3] = "work", [2] = "does", [1] = "this"}

notIpairsCompatable = {[2] = "this", [3] = "does", [4] = "not"}
notIpairsCompatable2 = {[2] = "this", [5] = "doesn't", [24] = "either"}

ipairs will go as far as it can with it's iterations but won't iterate over any other element in the table.

kindofIpairsCompatable = {[2] = 2, ["cool"] = "bro", [1] = 1, [3] = 3, [5] = 5 }

When printing these tables, these are the outputs. I've also included pairs outputs for comparison.

ipairs + ipairsCompatable
1       AAA
2       BBB
3       CCC

ipairs + ipairsCompatable2
1       DDD
2       EEE
3       FFF

ipairs + ipairsCompatable3
1       this
2       does
3       work

ipairs + notIpairsCompatable

pairs + notIpairsCompatable
2       this
3       does
4       not

ipairs + notIpairsCompatable2

pairs + notIpairsCompatable2
2       this
5       doesnt
24      either

ipairs + kindofIpairsCompatable
1       1
2       2
3       3

pairs + kindofIpairsCompatable
1       1
2       2
3       3
5       5
cool    bro

Bootstrap 3 Carousel fading to new slide instead of sliding to new slide

The update from 3.2.x to 3.3.x broke some of the solutions explained here and on other threads because of the change: "Added transforms to improve carousel performance in modern browsers."

If you are using Bootstrap 3.3.x there's a solution here:
http://codepen.io/transportedman/pen/NPWRGq

Basically you need to add the "carousel-fade" class to your carousel so that you have:
<div class="carousel slide carousel-fade">

And then include the following CSS:

/*
  Bootstrap Carousel Fade Transition (for Bootstrap 3.3.x)
  CSS from:       http://codepen.io/transportedman/pen/NPWRGq
  and:            http://stackoverflow.com/questions/18548731/bootstrap-3-carousel-fading-to-new-slide-instead-of-sliding-to-new-slide
  Inspired from:  http://codepen.io/Rowno/pen/Afykb 
*/
.carousel-fade .carousel-inner .item {
  opacity: 0;
  transition-property: opacity;
}

.carousel-fade .carousel-inner .active {
  opacity: 1;
}

.carousel-fade .carousel-inner .active.left,
.carousel-fade .carousel-inner .active.right {
  left: 0;
  opacity: 0;
  z-index: 1;
}

.carousel-fade .carousel-inner .next.left,
.carousel-fade .carousel-inner .prev.right {
  opacity: 1;
}

.carousel-fade .carousel-control {
  z-index: 2;
}

/*
  WHAT IS NEW IN 3.3: "Added transforms to improve carousel performance in modern browsers."
  Need to override the 3.3 new styles for modern browsers & apply opacity
*/
@media all and (transform-3d), (-webkit-transform-3d) {
    .carousel-fade .carousel-inner > .item.next,
    .carousel-fade .carousel-inner > .item.active.right {
      opacity: 0;
      -webkit-transform: translate3d(0, 0, 0);
              transform: translate3d(0, 0, 0);
    }
    .carousel-fade .carousel-inner > .item.prev,
    .carousel-fade .carousel-inner > .item.active.left {
      opacity: 0;
      -webkit-transform: translate3d(0, 0, 0);
              transform: translate3d(0, 0, 0);
    }
    .carousel-fade .carousel-inner > .item.next.left,
    .carousel-fade .carousel-inner > .item.prev.right,
    .carousel-fade .carousel-inner > .item.active {
      opacity: 1;
      -webkit-transform: translate3d(0, 0, 0);
              transform: translate3d(0, 0, 0);
    }
}

jQuery loop over JSON result from AJAX Success?

I am partial to ES2015 arrow function for finding values in an array

const result = data.find(x=> x.TEST1 === '46');

Checkout Array.prototype.find() HERE

Writing an mp4 video using python opencv

This is the default code given to save a video captured by camera

import numpy as np
import cv2

cap = cv2.VideoCapture(0)

# Define the codec and create VideoWriter object
fourcc = cv2.VideoWriter_fourcc(*'XVID')
out = cv2.VideoWriter('output.avi',fourcc, 20.0, (640,480))

while(cap.isOpened()):
    ret, frame = cap.read()
    if ret==True:
        frame = cv2.flip(frame,0)

        # write the flipped frame
        out.write(frame)

        cv2.imshow('frame',frame)
        if cv2.waitKey(1) & 0xFF == ord('q'):
            break
    else:
        break

# Release everything if job is finished
cap.release()
out.release()
cv2.destroyAllWindows()

For about two minutes of a clip captured that FULL HD

Using

cap = cv2.VideoCapture(0,cv2.CAP_DSHOW)
cap.set(3,1920)
cap.set(4,1080)
out = cv2.VideoWriter('output.avi',fourcc, 20.0, (1920,1080))

The file saved was more than 150MB

Then had to use ffmpeg to reduce the size of the file saved, between 30MB to 60MB based on the quality of the video that is required changed using crf lower the crf better the quality of the video and larger the file size generated. You can also change the format avi,mp4,mkv,etc

Then i found ffmpeg-python

Here a code to save numpy array of each frame as video using ffmpeg-python

import numpy as np
import cv2
import ffmpeg

def save_video(cap,saving_file_name,fps=33.0):

    while cap.isOpened():
        ret, frame = cap.read()
        if ret:
            i_width,i_height = frame.shape[1],frame.shape[0]
            break

    process = (
    ffmpeg
        .input('pipe:',format='rawvideo', pix_fmt='rgb24',s='{}x{}'.format(i_width,i_height))
        .output(saved_video_file_name,pix_fmt='yuv420p',vcodec='libx264',r=fps,crf=37)
        .overwrite_output()
        .run_async(pipe_stdin=True)
    )

    return process

if __name__=='__main__':

    cap = cv2.VideoCapture(0,cv2.CAP_DSHOW)
    cap.set(3,1920)
    cap.set(4,1080)
    saved_video_file_name = 'output.avi'
    process = save_video(cap,saved_video_file_name)

    while(cap.isOpened()):
        ret, frame = cap.read()
        if ret==True:
            frame = cv2.flip(frame,0)
            process.stdin.write(
                cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
                    .astype(np.uint8)
                    .tobytes()
                    )

            cv2.imshow('frame',frame)
            if cv2.waitKey(1) & 0xFF == ord('q'):
                process.stdin.close()
                process.wait()
                cap.release()
                cv2.destroyAllWindows()
                break
        else:
            process.stdin.close()
            process.wait()
            cap.release()
            cv2.destroyAllWindows()
            break

Display QImage with QtGui

Simple, but complete example showing how to display QImage might look like this:

#include <QtGui/QApplication>
#include <QLabel>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);

    QImage myImage;
    myImage.load("test.png");

    QLabel myLabel;
    myLabel.setPixmap(QPixmap::fromImage(myImage));

    myLabel.show();

    return a.exec();
}

UITextView that expands to text using auto layout

Here's a quick solution:

This problem may occur if you have set clipsToBounds property to false of your textview. If you simply delete it, the problem goes away.

myTextView.clipsToBounds = false //delete this line

How to convert a selection to lowercase or uppercase in Sublime Text

For others needing a key binding:

{ "keys": ["ctrl+="], "command": "upper_case" },
{ "keys": ["ctrl+-"], "command": "lower_case" }

Get month name from number

I created my own function converting numbers to their corresponding month.

def month_name (number):
    if number == 1:
        return "January"
    elif number == 2:
        return "February"
    elif number == 3:
        return "March"
    elif number == 4:
        return "April"
    elif number == 5:
        return "May"
    elif number == 6:
        return "June"
    elif number == 7:
        return "July"
    elif number == 8:
        return "August"
    elif number == 9:
        return "September"
    elif number == 10:
        return "October"
    elif number == 11:
        return "November"
    elif number == 12:
        return "December"

Then I can call the function. For example:

print (month_name (12))

Outputs:

>>> December

What does href expression <a href="javascript:;"></a> do?

It is a way of making a link do absolutely nothing when clicked (unless Javascript events are bound to it).

It is a way of running Javascript instead of following a link:

<a href="Javascript: doStuff();">link</a>

When there isn't actually javascript to run (like your example) it does nothing.

How to call function that takes an argument in a Django template?

if you have an object you can define it as @property so you can get results without a call, e.g.

class Item:
    @property
    def results(self):
        return something

then in the template:

<% for result in item.results %>
...
<% endfor %>

How to determine a user's IP address in node

There are two ways to get the ip address :

  1. let ip = req.ip

  2. let ip = req.connection.remoteAddress;

But there is a problem with above approaches.

If you are running your app behind Nginx or any proxy, every single IP addresses will be 127.0.0.1.

So, the best solution to get the ip address of user is :-

let ip = req.header('x-forwarded-for') || req.connection.remoteAddress;

Loading a properties file from Java package

Assuming your using the Properties class, via its load method, and I guess you are using the ClassLoader getResourceAsStream to get the input stream.

How are you passing in the name, it seems it should be in this form: /com/al/common/email/templates/foo.properties

Convert date yyyyMMdd to system.datetime format

string time = "19851231";
DateTime theTime= DateTime.ParseExact(time,
                                        "yyyyMMdd",
                                        CultureInfo.InvariantCulture,
                                        DateTimeStyles.None);

How can I avoid Java code in JSP files, using JSP 2?

Learn to customize and write your own tags using JSTL

Note that EL is EviL (runtime exceptions and refactoring).

Wicket may be evil too (performance and toilsome for small applications or simple view tier).

Example from java2s

This must be added to the web application's web.xml

<taglib>
    <taglib-uri>/java2s</taglib-uri>
    <taglib-location>/WEB-INF/java2s.tld</taglib-location>
</taglib>

Create file java2s.tld in the /WEB-INF/

<!DOCTYPE taglib
  PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.2//EN"
   "http://java.sun.com/dtd/web-jsptaglibrary_1_2.dtd">

<!-- A tab library descriptor -->
<taglib xmlns="http://java.sun.com/JSP/TagLibraryDescriptor">
    <tlib-version>1.0</tlib-version>
    <jsp-version>1.2</jsp-version>
    <short-name>Java2s Simple Tags</short-name>

    <!-- This tag manipulates its body content by converting it to upper case
    -->
    <tag>
        <name>bodyContentTag</name>
        <tag-class>com.java2s.BodyContentTag</tag-class>
        <body-content>JSP</body-content>
        <attribute>
          <name>howMany</name>
        </attribute>
    </tag>
</taglib>

Compile the following code into WEB-INF\classes\com\java2s

package com.java2s;

import java.io.IOException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.BodyContent;
import javax.servlet.jsp.tagext.BodyTagSupport;

public class BodyContentTag extends BodyTagSupport{
    private int iterations, howMany;

    public void setHowMany(int i){
        this.howMany = i;
    }

    public void setBodyContent(BodyContent bc){
        super.setBodyContent(bc);
        System.out.println("BodyContent = '" + bc.getString() + "'");
    }

    public int doAfterBody(){
        try{
            BodyContent bodyContent = super.getBodyContent();
            String bodyString  = bodyContent.getString();
            JspWriter out = bodyContent.getEnclosingWriter();

            if ( iterations % 2 == 0 )
                out.print(bodyString.toLowerCase());
            else
                out.print(bodyString.toUpperCase());

            iterations++;
            bodyContent.clear(); // empty buffer for next evaluation
        }
        catch (IOException e) {
            System.out.println("Error in BodyContentTag.doAfterBody()" + e.getMessage());
            e.printStackTrace();
        } // End of catch

        int retValue = SKIP_BODY;

        if ( iterations < howMany )
            retValue = EVAL_BODY_AGAIN;

        return retValue;
    }
}

Start the server and load the bodyContent.jsp file in the browser:

<%@ taglib uri="/java2s" prefix="java2s" %>
<html>
    <head>
        <title>A custom tag: body content</title>
    </head>
    <body>
        This page uses a custom tag manipulates its body content.Here is its output:
        <ol>
            <java2s:bodyContentTag howMany="3">
            <li>java2s.com</li>
            </java2s:bodyContentTag>
        </ol>
    </body>
</html>

How do I apply CSS3 transition to all properties except background-position?

For anyone looks for a shorthand way, to add transition for all properties except for one specific property with delay, be aware of there're differences among even modern browsers.

A simple demo below shows the difference. Check out full code

div:hover {
  width: 500px;
  height: 500px;
  border-radius: 0;
  transition: all 2s, border-radius 2s 4s;
}

Chrome will "combine" the two animation (which is like I expect), like below:

enter image description here

While Safari "separates" it (which may not be expected):

enter image description here

A more compatible way is that you assign the specific transition for specific property, if you have a delay for one of them.

How to invoke the super constructor in Python?

With Python 2.x old-style classes it would be this:

class A: 
 def __init__(self): 
   print "world" 

class B(A): 
 def __init__(self): 
   print "hello" 
   A.__init__(self)

How can I use pickle to save a dict?

Try this:

import pickle

a = {'hello': 'world'}

with open('filename.pickle', 'wb') as handle:
    pickle.dump(a, handle, protocol=pickle.HIGHEST_PROTOCOL)

with open('filename.pickle', 'rb') as handle:
    b = pickle.load(handle)

print a == b

How to load a resource bundle from a file resource in Java?

As long as you name your resource bundle files correctly (with a .properties extension), then this works:

File file = new File("C:\\temp");
URL[] urls = {file.toURI().toURL()};
ClassLoader loader = new URLClassLoader(urls);
ResourceBundle rb = ResourceBundle.getBundle("myResource", Locale.getDefault(), loader);

where "c:\temp" is the external folder (NOT on the classpath) holding the property files, and "myResource" relates to myResource.properties, myResource_fr_FR.properties, etc.

Credit to http://www.coderanch.com/t/432762/java/java/absolute-path-bundle-file

Sort arrays of primitive types in descending order

There's been some confusion about Arrays.asList in the other answers. If you say

double[] arr = new double[]{6.0, 5.0, 11.0, 7.0};
List xs = Arrays.asList(arr);
System.out.println(xs.size());  // prints 1

then you'll have a List with 1 element. The resulting List has the double[] array as its own element. What you want is to have a List<Double> whose elements are the elements of the double[].

Unfortunately, no solution involving Comparators will work for a primitive array. Arrays.sort only accepts a Comparator when being passed an Object[]. And for the reasons describe above, Arrays.asList won't let you make a List out of the elements of your array.

So despite my earlier answer which the comments below reference, there's no better way than manually reversing the array after sorting. Any other approach (such as copying the elements into a Double[] and reverse-sorting and copying them back) would be more code and slower.

MS SQL compare dates?

SELECT CASE WHEN CAST(date1 AS DATE) <= CAST(date2 AS DATE) ...

Should do what you need.

Test Case

WITH dates(date1, date2, date3, date4)
     AS (SELECT CAST('20101231 15:13:48.593' AS DATETIME),
                CAST('20101231 00:00:00.000' AS DATETIME),
                CAST('20101231 15:13:48.593' AS DATETIME),
                CAST('20101231 00:00:00.000' AS DATETIME))
SELECT CASE
         WHEN CAST(date1 AS DATE) <= CAST(date2 AS DATE) THEN 'Y'
         ELSE 'N'
       END AS COMPARISON_WITH_CAST,
       CASE
         WHEN date3 <= date4 THEN 'Y'
         ELSE 'N'
       END AS COMPARISON_WITHOUT_CAST
FROM   dates 

Returns

COMPARISON_WITH_CAST   |  COMPARISON_WITHOUT_CAST
Y                         N

Show values from a MySQL database table inside a HTML table on a webpage

Example taken from W3Schools: PHP Select Data from MySQL

<?php
$con=mysqli_connect("example.com","peter","abc123","my_db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

$result = mysqli_query($con,"SELECT * FROM Persons");

echo "<table border='1'>
<tr>
<th>Firstname</th>
<th>Lastname</th>
</tr>";

while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['FirstName'] . "</td>";
echo "<td>" . $row['LastName'] . "</td>";
echo "</tr>";
}
echo "</table>";

mysqli_close($con);
?>

It's a good place to learn from!

Reverse of JSON.stringify?

Recommended is to use JSON.parse

There is an alternative you can do :

 var myObject = eval('(' + myJSONtext + ')');

Json in javascript

Why is using the JavaScript eval function a bad idea?

mat-form-field must contain a MatFormFieldControl

The same error can occur if you have a mat slide within a mat from field as the only element in my case I had

 <mat-form-field>
    <mat-slide-toggle [(ngModel)]="myvar">
       Some Text
     </mat-slide-toggle>
 </mat-form-field>

This might happen if you had several attributes within the <mat-form-field> Simple solution was to move the slide toggle to the root

How to read data From *.CSV file using javascript?

A bit late but I hope it helps someone.

Some time ago even I faced a problem where the string data contained \n in between and while reading the file it used to read as different lines.

Eg.

"Harry\nPotter","21","Gryffindor"

While-Reading:

Harry
Potter,21,Gryffindor

I had used a library csvtojson in my angular project to solve this problem.

You can read the CSV file as a string using the following code and then pass that string to the csvtojson library and it will give you a list of JSON.

Sample Code:

const csv = require('csvtojson');
if (files && files.length > 0) {
    const file: File = files.item(0);
    const reader: FileReader = new FileReader();
    reader.readAsText(file);
    reader.onload = (e) => {
    const csvs: string = reader.result as string;
    csv({
        output: "json",
        noheader: false
    }).fromString(csvs)
        .preFileLine((fileLine, idx) => {
        //Convert csv header row to lowercase before parse csv file to json
        if (idx === 0) { return fileLine.toLowerCase() }
        return fileLine;
        })
        .then((result) => {
        // list of json in result
        });
    }
}

How can I check file size in Python?

we have two options Both include importing os module

1) import os, as os.stat() function returns an object which contains so many headers including file created time and last modified time etc.. among them st_size gives the exact size of the file.

os.stat("filename").st_size

2) import os In this, we have to provide the exact file path(absolute path), not a relative path.

os.path.getsize("path of file")

Set height of chart in Chart.js

You can also set the dimensions to the canvas

<canvas id="myChart" width="400" height="400"></canvas>

And then set the responsive options to false to always maintain the chart at the size specified.

options: {
    responsive: false,
}

MySQL create stored procedure syntax with delimiter

MY SQL STORED PROCEDURE CREATION

DELIMiTER $$
create procedure GetUserRolesEnabled(in UserId int)
Begin

select * from users
where id=UserId ;
END $$
DELIMITER ;

adb remount permission denied, but able to access super user in shell -- android

@echo off
color 0B
echo =============================================================================
echo.
echo              ClockworkMod Recovery for SAMSUNG GALAXY SIII E210L
echo.
echo                  ClockworkMod Recovery (v6.0.1.2 Touch)
echo.
echo     ¡ô¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¡ô
echo     ¨U                                                                  ¨U
echo     ¨U SAMSUNG GALAXY SIII E210L                                        ¨U
echo     ¡ô¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¨T¡ô
echo.
echo  1) (Settings\Developer options©¥ USB debugging)
echo.
echo  2) CWM SAMSUNG GALAXY SIII E210L 
echo.
echo  3) THANK!!!!!!
echo.
echo =============================================================================
echo                           ARE YOU READY? GO! ¡·¡·¡·
@pause
echo.
echo adb...
adb.exe kill-server
adb.exe wait-for-device
echo wiat¸!
echo.
echo conect...
adb.exe push IMG /data/local/tmp/
adb.exe shell su -c "dd if=/data/local/tmp/GANGSTAR-VEGAS-1.3.0-APK-Andropalace.net.apk of=/mnt/sdcard/Android/GANGSTAR-VEGAS-1.3.0-APK-Andropalace.net.apk
adb.exe shell su -c "rm /data/local/tmp/bootloader.img"
adb.exe shell su -c "rm /data/local/tmp/recovery.img"


echo ===============================================================
echo     ClockworkMod Recovery!
echo.
@pause

X11/Xlib.h not found in Ubuntu

Why not try find /usr/include/X11 -name Xlib.h

If there is a hit, you have Xlib.h

If not install it using sudo apt-get install libx11-dev

and you are good to go :)

How to access parent scope from within a custom directive *with own scope* in AngularJS?

Accessing controller method means accessing a method on parent scope from directive controller/link/scope.

If the directive is sharing/inheriting the parent scope then it is quite straight forward to just invoke a parent scope method.

Little more work is required when you want to access parent scope method from Isolated directive scope.

There are few options (may be more than listed below) to invoke a parent scope method from isolated directives scope or watch parent scope variables (option#6 specially).

Note that I used link function in these examples but you can use a directive controller as well based on requirement.

Option#1. Through Object literal and from directive html template

index.html

<!DOCTYPE html>
<html ng-app="plunker">

  <head>
    <meta charset="utf-8" />
    <title>AngularJS Plunker</title>
    <script>document.write('<base href="' + document.location + '" />');</script>
    <link rel="stylesheet" href="style.css" />
    <script data-require="[email protected]" src="https://code.angularjs.org/1.3.9/angular.js" data-semver="1.3.9"></script>
    <script src="app.js"></script>
  </head>

  <body ng-controller="MainCtrl">
    <p>Hello {{name}}!</p>

    <p> Directive Content</p>
    <sd-items-filter selected-items="selectedItems" selected-items-changed="selectedItemsChanged(selectedItems)" items="items"> </sd-items-filter>


    <P style="color:red">Selected Items (in parent controller) set to: {{selectedItemsReturnedFromDirective}} </p>

  </body>

</html>

itemfilterTemplate.html

<select ng-model="selectedItems" multiple="multiple" style="height: 200px; width: 250px;" ng-change="selectedItemsChanged({selectedItems:selectedItems})" ng-options="item.id as item.name group by item.model for item in items | orderBy:'name'">
  <option>--</option>
</select>

app.js

var app = angular.module('plunker', []);

app.directive('sdItemsFilter', function() {
  return {
    restrict: 'E',
    scope: {
      items: '=',
      selectedItems: '=',
      selectedItemsChanged: '&'
    },
    templateUrl: "itemfilterTemplate.html"
  }
})

app.controller('MainCtrl', function($scope) {
  $scope.name = 'TARS';

  $scope.selectedItems = ["allItems"];

  $scope.selectedItemsChanged = function(selectedItems1) {
    $scope.selectedItemsReturnedFromDirective = selectedItems1;
  }

  $scope.items = [{
    "id": "allItems",
    "name": "All Items",
    "order": 0
  }, {
    "id": "CaseItem",
    "name": "Case Item",
    "model": "PredefinedModel"
  }, {
    "id": "Application",
    "name": "Application",
    "model": "Bank"
    }]

});

working plnkr: http://plnkr.co/edit/rgKUsYGDo9O3tewL6xgr?p=preview

Option#2. Through Object literal and from directive link/scope

index.html

<!DOCTYPE html>
<html ng-app="plunker">

  <head>
    <meta charset="utf-8" />
    <title>AngularJS Plunker</title>
    <script>document.write('<base href="' + document.location + '" />');</script>
    <link rel="stylesheet" href="style.css" />
    <script data-require="[email protected]" src="https://code.angularjs.org/1.3.9/angular.js" data-semver="1.3.9"></script>
    <script src="app.js"></script>
  </head>

  <body ng-controller="MainCtrl">
    <p>Hello {{name}}!</p>

    <p> Directive Content</p>
    <sd-items-filter selected-items="selectedItems" selected-items-changed="selectedItemsChanged(selectedItems)" items="items"> </sd-items-filter>


    <P style="color:red">Selected Items (in parent controller) set to: {{selectedItemsReturnedFromDirective}} </p>

  </body>

</html>

itemfilterTemplate.html

<select ng-model="selectedItems" multiple="multiple" style="height: 200px; width: 250px;" 
 ng-change="selectedItemsChangedDir()" ng-options="item.id as item.name group by item.model for item in items | orderBy:'name'">
  <option>--</option>
</select>

app.js

var app = angular.module('plunker', []);

app.directive('sdItemsFilter', function() {
  return {
    restrict: 'E',
    scope: {
      items: '=',
      selectedItems: '=',
      selectedItemsChanged: '&'
    },
    templateUrl: "itemfilterTemplate.html",
    link: function (scope, element, attrs){
      scope.selectedItemsChangedDir = function(){
        scope.selectedItemsChanged({selectedItems:scope.selectedItems});  
      }
    }
  }
})

app.controller('MainCtrl', function($scope) {
  $scope.name = 'TARS';

  $scope.selectedItems = ["allItems"];

  $scope.selectedItemsChanged = function(selectedItems1) {
    $scope.selectedItemsReturnedFromDirective = selectedItems1;
  }

  $scope.items = [{
    "id": "allItems",
    "name": "All Items",
    "order": 0
  }, {
    "id": "CaseItem",
    "name": "Case Item",
    "model": "PredefinedModel"
  }, {
    "id": "Application",
    "name": "Application",
    "model": "Bank"
    }]
});

working plnkr: http://plnkr.co/edit/BRvYm2SpSpBK9uxNIcTa?p=preview

Option#3. Through Function reference and from directive html template

index.html

<!DOCTYPE html>
<html ng-app="plunker">

  <head>
    <meta charset="utf-8" />
    <title>AngularJS Plunker</title>
    <script>document.write('<base href="' + document.location + '" />');</script>
    <link rel="stylesheet" href="style.css" />
    <script data-require="[email protected]" src="https://code.angularjs.org/1.3.9/angular.js" data-semver="1.3.9"></script>
    <script src="app.js"></script>
  </head>

  <body ng-controller="MainCtrl">
    <p>Hello {{name}}!</p>

    <p> Directive Content</p>
    <sd-items-filter selected-items="selectedItems" selected-items-changed="selectedItemsChanged" items="items"> </sd-items-filter>


    <P style="color:red">Selected Items (in parent controller) set to: {{selectedItemsReturnFromDirective}} </p>

  </body>

</html>

itemfilterTemplate.html

<select ng-model="selectedItems" multiple="multiple" style="height: 200px; width: 250px;" 
 ng-change="selectedItemsChanged()(selectedItems)" ng-options="item.id as item.name group by item.model for item in items | orderBy:'name'">
  <option>--</option>
</select>

app.js

var app = angular.module('plunker', []);

app.directive('sdItemsFilter', function() {
  return {
    restrict: 'E',
    scope: {
      items: '=',
      selectedItems:'=',
      selectedItemsChanged: '&'
    },
    templateUrl: "itemfilterTemplate.html"
  }
})

app.controller('MainCtrl', function($scope) {
  $scope.name = 'TARS';

  $scope.selectedItems = ["allItems"];

  $scope.selectedItemsChanged = function(selectedItems1) {
    $scope.selectedItemsReturnFromDirective = selectedItems1;
  }

  $scope.items = [{
    "id": "allItems",
    "name": "All Items",
    "order": 0
  }, {
    "id": "CaseItem",
    "name": "Case Item",
    "model": "PredefinedModel"
  }, {
    "id": "Application",
    "name": "Application",
    "model": "Bank"
    }]
});

working plnkr: http://plnkr.co/edit/Jo6FcYfVXCCg3vH42BIz?p=preview

Option#4. Through Function reference and from directive link/scope

index.html

<!DOCTYPE html>
<html ng-app="plunker">

  <head>
    <meta charset="utf-8" />
    <title>AngularJS Plunker</title>
    <script>document.write('<base href="' + document.location + '" />');</script>
    <link rel="stylesheet" href="style.css" />
    <script data-require="[email protected]" src="https://code.angularjs.org/1.3.9/angular.js" data-semver="1.3.9"></script>
    <script src="app.js"></script>
  </head>

  <body ng-controller="MainCtrl">
    <p>Hello {{name}}!</p>

    <p> Directive Content</p>
    <sd-items-filter selected-items="selectedItems" selected-items-changed="selectedItemsChanged" items="items"> </sd-items-filter>


    <P style="color:red">Selected Items (in parent controller) set to: {{selectedItemsReturnedFromDirective}} </p>

  </body>

</html>

itemfilterTemplate.html

<select ng-model="selectedItems" multiple="multiple" style="height: 200px; width: 250px;" ng-change="selectedItemsChangedDir()" ng-options="item.id as item.name group by item.model for item in items | orderBy:'name'">
  <option>--</option>
</select>

app.js

var app = angular.module('plunker', []);

app.directive('sdItemsFilter', function() {
  return {
    restrict: 'E',
    scope: {
      items: '=',
      selectedItems: '=',
      selectedItemsChanged: '&'
    },
    templateUrl: "itemfilterTemplate.html",
    link: function (scope, element, attrs){
      scope.selectedItemsChangedDir = function(){
        scope.selectedItemsChanged()(scope.selectedItems);  
      }
    }
  }
})

app.controller('MainCtrl', function($scope) {
  $scope.name = 'TARS';

  $scope.selectedItems = ["allItems"];

  $scope.selectedItemsChanged = function(selectedItems1) {
    $scope.selectedItemsReturnedFromDirective = selectedItems1;
  }

  $scope.items = [{
    "id": "allItems",
    "name": "All Items",
    "order": 0
  }, {
    "id": "CaseItem",
    "name": "Case Item",
    "model": "PredefinedModel"
  }, {
    "id": "Application",
    "name": "Application",
    "model": "Bank"
    }]

});

working plnkr: http://plnkr.co/edit/BSqx2J1yCY86IJwAnQF1?p=preview

Option#5: Through ng-model and two way binding, you can update parent scope variables.. So, you may not require to invoke parent scope functions in some cases.

index.html

<!DOCTYPE html>
<html ng-app="plunker">

  <head>
    <meta charset="utf-8" />
    <title>AngularJS Plunker</title>
    <script>document.write('<base href="' + document.location + '" />');</script>
    <link rel="stylesheet" href="style.css" />
    <script data-require="[email protected]" src="https://code.angularjs.org/1.3.9/angular.js" data-semver="1.3.9"></script>
    <script src="app.js"></script>
  </head>

  <body ng-controller="MainCtrl">
    <p>Hello {{name}}!</p>

    <p> Directive Content</p>
    <sd-items-filter ng-model="selectedItems" selected-items-changed="selectedItemsChanged" items="items"> </sd-items-filter>


    <P style="color:red">Selected Items (in parent controller) set to: {{selectedItems}} </p>

  </body>

</html>

itemfilterTemplate.html

<select ng-model="selectedItems" multiple="multiple" style="height: 200px; width: 250px;" 
 ng-options="item.id as item.name group by item.model for item in items | orderBy:'name'">
  <option>--</option>
</select>

app.js

var app = angular.module('plunker', []);

app.directive('sdItemsFilter', function() {
  return {
    restrict: 'E',
    scope: {
      items: '=',
      selectedItems: '=ngModel'
    },
    templateUrl: "itemfilterTemplate.html"
  }
})

app.controller('MainCtrl', function($scope) {
  $scope.name = 'TARS';

  $scope.selectedItems = ["allItems"];

  $scope.items = [{
    "id": "allItems",
    "name": "All Items",
    "order": 0
  }, {
    "id": "CaseItem",
    "name": "Case Item",
    "model": "PredefinedModel"
  }, {
    "id": "Application",
    "name": "Application",
    "model": "Bank"
    }]
});

working plnkr: http://plnkr.co/edit/hNui3xgzdTnfcdzljihY?p=preview

Option#6: Through $watch and $watchCollection It is two way binding for items in all above examples, if items are modified in parent scope, items in directive would also reflect the changes.

If you want to watch other attributes or objects from parent scope, you can do that using $watch and $watchCollection as given below

html

<!DOCTYPE html>
<html ng-app="plunker">

<head>
  <meta charset="utf-8" />
  <title>AngularJS Plunker</title>
  <script>
    document.write('<base href="' + document.location + '" />');
  </script>
  <link rel="stylesheet" href="style.css" />
  <script data-require="[email protected]" src="https://code.angularjs.org/1.3.9/angular.js" data-semver="1.3.9"></script>
  <script src="app.js"></script>
</head>

<body ng-controller="MainCtrl">
  <p>Hello {{user}}!</p>
  <p>directive is watching name and current item</p>
  <table>
    <tr>
      <td>Id:</td>
      <td>
        <input type="text" ng-model="id" />
      </td>
    </tr>
    <tr>
      <td>Name:</td>
      <td>
        <input type="text" ng-model="name" />
      </td>
    </tr>
    <tr>
      <td>Model:</td>
      <td>
        <input type="text" ng-model="model" />
      </td>
    </tr>
  </table>

  <button style="margin-left:50px" type="buttun" ng-click="addItem()">Add Item</button>

  <p>Directive Contents</p>
  <sd-items-filter ng-model="selectedItems" current-item="currentItem" name="{{name}}" selected-items-changed="selectedItemsChanged" items="items"></sd-items-filter>

  <P style="color:red">Selected Items (in parent controller) set to: {{selectedItems}}</p>
</body>

</html>

script app.js

var app = angular.module('plunker', []);

app.directive('sdItemsFilter', function() {
  return {
    restrict: 'E',
    scope: {
      name: '@',
      currentItem: '=',
      items: '=',
      selectedItems: '=ngModel'
    },
    template: '<select ng-model="selectedItems" multiple="multiple" style="height: 140px; width: 250px;"' +
      'ng-options="item.id as item.name group by item.model for item in items | orderBy:\'name\'">' +
      '<option>--</option> </select>',
    link: function(scope, element, attrs) {
      scope.$watchCollection('currentItem', function() {
        console.log(JSON.stringify(scope.currentItem));
      });
      scope.$watch('name', function() {
        console.log(JSON.stringify(scope.name));
      });
    }
  }
})

 app.controller('MainCtrl', function($scope) {
  $scope.user = 'World';

  $scope.addItem = function() {
    $scope.items.push({
      id: $scope.id,
      name: $scope.name,
      model: $scope.model
    });
    $scope.currentItem = {};
    $scope.currentItem.id = $scope.id;
    $scope.currentItem.name = $scope.name;
    $scope.currentItem.model = $scope.model;
  }

  $scope.selectedItems = ["allItems"];

  $scope.items = [{
    "id": "allItems",
    "name": "All Items",
    "order": 0
  }, {
    "id": "CaseItem",
    "name": "Case Item",
    "model": "PredefinedModel"
  }, {
    "id": "Application",
    "name": "Application",
    "model": "Bank"
  }]
});

You can always refer AngularJs documentation for detailed explanations about directives.

How to convert string date to Timestamp in java?

You can convert String to Timestamp:

String inDate = "01-01-1990"
DateFormat df = new SimpleDateFormat("MM-dd-yyyy");
Timestamp ts = new Timestamp(((java.util.Date)df.parse(inDate)).getTime());

Get the last element of a std::string

You probably want to check the length of the string first and do something like this:

if (!myStr.empty())
{
    char lastChar = *myStr.rbegin();
}

How to set commands output as a variable in a batch file

If you don't want to output to a temp file and then read into a variable, this code stores result of command direct into a variable:

FOR /F %i IN ('findstr testing') DO set VARIABLE=%i
echo %VARIABLE%

If you want to enclose search string in double quotes:

FOR /F %i IN ('findstr "testing"') DO set VARIABLE=%i

If you want to store this code in a batch file, add an extra % symbol:

FOR /F %%i IN ('findstr "testing"') DO set VARIABLE=%%i

A useful example to count the number of files in a directory & store in a variable: (illustrates piping)

FOR /F %i IN ('dir /b /a-d "%cd%" ^| find /v /c "?"') DO set /a count=%i

Note the use of single quotes instead of double quotes " or grave accent ` in the command brackets. This is cleaner alternative to delims, tokens or usebackq in for loop.

Tested on Win 10 CMD.

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

If you are using .NET 4.0 you can use a Tuple.

List<Tuple<T1, T2>> list;

For older versions of .NET you have to create a custom class (unless you are lucky enough to be able to find a class that fits your needs in the base class library).

Managing jQuery plugin dependency in webpack

I got things working nicely while exposing $ and jQuery as global variables with Webpack 3.8.1 and the following.

Install jQuery as a project dependency. You can omit @3.2.1 to install the latest version or specify another version.

npm install --save [email protected]

Install expose-loader as a development dependency if not installed already.

npm install expose-loader --save-dev

Configure Webpack to load and expose jQuery for us.

// webpack.config.js
const webpack = require('webpack')

module.exports = {
  entry: [
    // entry bits
  ],
  output: {
    // output bits
  },
  module: {
    rules: [
      // any other rules
      {
        // Exposes jQuery for use outside Webpack build
        test: require.resolve('jquery'),
        use: [{
          loader: 'expose-loader',
          options: 'jQuery'
        },{
          loader: 'expose-loader',
          options: '$'
        }]
      }
    ]
  },
  plugins: [
    // Provides jQuery for other JS bundled with Webpack
    new webpack.ProvidePlugin({
      $: 'jquery',
      jQuery: 'jquery'
    })
  ]
}

What equivalents are there to TortoiseSVN, on Mac OSX?

I use svnX (http://code.google.com/p/svnx/downloads/list), it is free and usable, but not as user friendly as tortoise. It shows you the review before commit with diff for every file... but sometimes I still had to go to command line to fix some things

Error: Could not find gradle wrapper within Android SDK. Might need to update your Android SDK - Android

if you have this error when you ionic run android --device

## codova - android update 
npm install -g cordova
cordova platform update android

Reference an Element in a List of Tuples

All of the other answers here are correct but do not explain why what you were trying was wrong. When you do myList[i[0]] you are telling Python that i is a tuple and you want the value or the first element of tuple i as the index for myList.

In the majority of programming languages when you need to access a nested data type (such as arrays, lists, or tuples), you append the brackets to get to the innermost item. The first bracket gives you the location of the tuple in your list. The second bracket gives you the location of the item in the tuple.

This is a quick rudimentary example that I came up with:

info = [ ( 1, 2), (3, 4), (5, 6) ]

info[0][0] == 1
info[0][1] == 2
info[1][0] == 3
info[1][1] == 4
info[2][0] == 5
info[2][1] == 6

How to loop over directories in Linux?

The technique I use most often is find | xargs. For example, if you want to make every file in this directory and all of its subdirectories world-readable, you can do:

find . -type f -print0 | xargs -0 chmod go+r
find . -type d -print0 | xargs -0 chmod go+rx

The -print0 option terminates with a NULL character instead of a space. The -0 option splits its input the same way. So this is the combination to use on files with spaces.

You can picture this chain of commands as taking every line output by find and sticking it on the end of a chmod command.

If the command you want to run as its argument in the middle instead of on the end, you have to be a bit creative. For instance, I needed to change into every subdirectory and run the command latemk -c. So I used (from Wikipedia):

find . -type d -depth 1 -print0 | \
    xargs -0 sh -c 'for dir; do pushd "$dir" && latexmk -c && popd; done' fnord

This has the effect of for dir $(subdirs); do stuff; done, but is safe for directories with spaces in their names. Also, the separate calls to stuff are made in the same shell, which is why in my command we have to return back to the current directory with popd.

nodejs mysql Error: Connection lost The server closed the connection

better solution is to use pool - ill handle this for you.

_x000D_
_x000D_
const pool = mysql.createPool({_x000D_
  host: 'localhost',_x000D_
  user: '--',_x000D_
  database: '---',_x000D_
  password: '----'_x000D_
});_x000D_
_x000D_
// ... later_x000D_
pool.query('select 1 + 1', (err, rows) => { /* */ });
_x000D_
_x000D_
_x000D_

https://github.com/sidorares/node-mysql2/issues/836

How do I call a specific Java method on a click/submit event of a specific button in JSP?

You can try adding action="#{yourBean.function1}" on each button (changing of course the method function2, function3, or whatever you need). If that does not work, you can try the same with the onclick event.

Anyway, it would be easier to help you if you tell us what kind of buttons are you trying to use, a4j:commandButton or whatever you are using.

Adding a newline into a string in C#

Based on your replies to everyone else, something like this is what you're looking for.

string file = @"C:\file.txt";
string strToProcess = "fkdfdsfdflkdkfk@dfsdfjk72388389@kdkfkdfkkl@jkdjkfjd@jjjk@";
string[] lines = strToProcess.Split(new char[] { '@' }, StringSplitOptions.RemoveEmptyEntries);

using (StreamWriter writer = new StreamWriter(file))
{
    foreach (string line in lines)
    {
        writer.WriteLine(line + "@");
    }
}

Passing parameters to click() & bind() event in jquery?

see event.data

commentbtn.bind('click', { id: '12', name: 'Chuck Norris' }, function(event) {
    var data = event.data;
    alert(data.id);
    alert(data.name);
});

If your data is initialized before binding the event, then simply capture those variables in a closure.

// assuming id and name are defined in this scope
commentBtn.click(function() {
    alert(id), alert(name);
});

How to link to a named anchor in Multimarkdown?

I tested Github Flavored Markdown for a while and can summarize with four rules:

  1. punctuation marks will be dropped
  2. leading white spaces will be dropped
  3. upper case will be converted to lower
  4. spaces between letters will be converted to -

For example, if your section is named this:

## 1.1 Hello World

Create a link to it this way:

[Link](#11-hello-world)

Python - TypeError: 'int' object is not iterable

If the case is:

n=int(input())

Instead of -> for i in n: -> gives error- 'int' object is not iterable

Use -> for i in range(0,n): -> works fine..!

How to show/hide JPanels in a JFrame?

If you want to hide panel on button click, write below code in JButton Action. I assume you want to hide jpanel1.

jpanel1.setVisible(false);

Using jQuery, Restricting File Size Before Uploading

I tried it this way and I am getting the results in IE*, and Mozilla 3.6.16, didnt check in older versions.

<img id="myImage" src="" style="display:none;"><br>
<button onclick="findSize();">Image Size</button>
<input type="file" id="loadfile" />
<input type="button" value="find size" onclick="findSize()" />
<script type="text/javascript">
function findSize() {
    if ( $.browser.msie ) {
       var a = document.getElementById('loadfile').value;
           $('#myImage').attr('src',a);
           var imgbytes = document.getElementById('myImage').size;
           var imgkbytes = Math.round(parseInt(imgbytes)/1024);
           alert(imgkbytes+' KB');
    }else {
           var fileInput = $("#loadfile")[0];
           var imgbytes = fileInput.files[0].fileSize; // Size returned in bytes.
           var imgkbytes = Math.round(parseInt(imgbytes)/1024);
                   alert(imgkbytes+' KB');
     }
}    
</script>

Add Jquery library also.

C# Iterate through Class properties

I tried what Samuel Slade has suggested. Didn't work for me. The PropertyInfo list was coming as empty. So, I tried the following and it worked for me.

    Type type = typeof(Record);
    FieldInfo[] properties = type.GetFields();
    foreach (FieldInfo property in properties) {
       Debug.LogError(property.Name);
    }

select dept names who have more than 2 employees whose salary is greater than 1000

select min(DEPARTMENT.DeptName) as deptname 
from DEPARTMENT
inner join employee on
DEPARTMENT.DeptId = employee.DeptId
where Salary > 1000
group by (EmpId) having count(EmpId) > =2 

How do I revert to a previous package in Anaconda?

I had to use the install function instead:

conda install pandas=0.13.1