Questions Tagged with #Python

Python is a dynamic, strongly typed, object-oriented, multipurpose programming language, designed to be quick (to learn, to use, and to understand), and to enforce a clean and uniform syntax. Two similar but incompatible versions of Python are in use (Python 2.7 or 3.x). For version-specific Python questions, please also use the [tag:python-2.7] or [tag:python-3.x] tags. When using a Python variant (i.e Jython, Pypy, etc.) - please also tag the variant.

TypeError: 'tuple' object does not support item assignment when swapping values

I am writing a simple sort program in python and encounter this error. I want to swap list elements but it returns an error. I am attaching the error and program in question below. list[i+1] = list[i..

Local variable referenced before assignment?

I am using the PyQt library to take a screenshot of a webpage, then reading through a CSV file of different URLs. I am keeping a variable feed that incremements everytime a URL is processed and theref..

isPrime Function for Python Language

So I was able to solve this problem with a little bit of help from the internet and this is what I got: def isPrime(n): for i in range(2,int(n**0.5)+1): if n%i==0: return False..

How to make a 3D scatter plot in Python?

I am currently have a nx3 matrix array. I want plot the three columns as three axis's. How can I do that? I have googled and people suggested using Matlab, but I am really having a hard time with u..

coercing to Unicode: need string or buffer, NoneType found when rendering in django admin

I have this error since a long time but can't figure it out : Caught TypeError while rendering: coercing to Unicode: need string or buffer, NoneType found It happens in admin when I try to add or mo..

Python develop vs install

Two options in develop and install are confusing me. According to this site, using develop creates a special link to site-packages directory. People have suggested that I use python

Python handling socket.error: [Errno 104] Connection reset by peer

When using Python 2.7 with urllib2 to retrieve data from an API, I get the error [Errno 104] Connection reset by peer. Whats causing the error, and how should the error be handled so that the script d..

You are trying to add a non-nullable field 'new_field' to userprofile without a default

I know that from Django 1.7 I don't need to use South or any other migration system, so I am just using simple command python makemigrations However, all I get is this error: You are tryi..

Python: Making a beep noise

I'm trying to get the program to give me a beeping noise. I'm on a windows machine. I've looked at But not sure how I can program this with a barcode scan..

Import Error: No module named numpy

I have a very similar question to this question, but still one step behind. I have only one version of Python 3 installed on my Windows 7 (sorry) 64-bit system. I installed numpy following this link ..

TypeError: 'module' object is not callable

File "C:\Users\Administrator\Documents\Mibot\oops\", line 82, in __init__ self.serv = socket(AF_INET,SOCK_STREAM) TypeError: 'module' object is not callable Why am I getting this err..

How to resize an image with OpenCV2.0 and Python2.6

I want to use OpenCV2.0 and Python2.6 to show resized images. I used and adopted this example but unfortunately, this code is for OpenCV2.1 and does not seem to be working on 2.0. Here my code: import..

Why do many examples use `fig, ax = plt.subplots()` in Matplotlib/pyplot/python

I'm learning to use matplotlib by studying examples, and a lot of examples seem to include a line like the following before creating a single plot... fig, ax = plt.subplots() Here are some examples..

How do you read from stdin?

I'm trying to do some of the code golf challenges, but they all require the input to be taken from stdin. How do I get that in Python?..

Web scraping with Python

I'd like to grab daily sunrise/sunset times from a web site. Is it possible to scrape web content with Python? what are the modules used? Is there any tutorial available?..

Change a Django form field to a hidden field

I have a Django form with a RegexField, which is very similar to a normal text input field. In my view, under certain conditions I want to hide it from the user, and trying to keep the form as simila..

How to check if an element of a list is a list (in Python)?

If we have the following list: list = ['UMM', 'Uma', ['Ulaster','Ulter']] If I need to find out if an element in the list is itself a list, what can I replace aValidList in the following code with?..

Converting integer to digit list

What is the quickest and cleanest way to convert an integer into a list? For example, change 132 into [1,3,2] and 23 into [2,3]. I have a variable which is an int, and I want to be able to compare t..

Byte Array in Python

How can I represent a byte array (like in Java with byte[]) in Python? I'll need to send it over the wire with gevent. byte key[] = {0x13, 0x00, 0x00, 0x00, 0x08, 0x00}; ..

Can anyone explain python's relative imports?

I can't for the life of me get python's relative imports to work. I have created a simple example of where it does not function: The directory structure is: / / / /sub/__..

Deleting folders in python recursively

I'm having a problem with deleting empty directories. Here is my code: for dirpath, dirnames, filenames in os.walk(dir_to_search): //other codes try: os.rmdir(dirpath) except OSEr..

Using other keys for the waitKey() function of opencv

I'm working on a program (python ,opencv) in which I use the spacebar to go to the next frame, and Esc to exit the program. These are the only two keys i've got working. I tried to find out about more..

filter items in a python dictionary where keys contain a specific string

I'm a C coder developing something in python. I know how to do the following in C (and hence in C-like logic applied to python), but I'm wondering what the 'Python' way of doing it is. I have a dicti..

Generate random colors (RGB)

I just picked up image processing in python this past week at the suggestion of a friend to generate patterns of random colors. I found this piece of script online that generates a wide array of diffe..

Plot inline or a separate window using Matplotlib in Spyder IDE

When I use Matplotlib to plot some graphs, it is usually fine for the default inline drawing. However, when I draw some 3D graphs, I'd like to have them in a separate window so that interactions like ..

Get folder name of the file in Python

In Python what command should I use to get the name of the folder which contains the file I'm working with? "C:\folder1\folder2\filename.xml" Here "folder2" is what I want to get. ..

pandas three-way joining multiple dataframes on columns

I have 3 CSV files. Each has the first column as the (string) names of people, while all the other columns in each dataframe are attributes of that person. How can I "join" together all three CSV do..

SQLAlchemy: how to filter date field?

Here is model: class User(Base): ... birthday = Column(Date, index=True) #in database it's like '1987-01-17' ... I want to filter between two dates, for example to choose all users in..

Extracting first n columns of a numpy matrix

I have an array like this: array([[-0.57098887, -0.4274751 , -0.38459931, -0.58593526], [-0.22279713, -0.51723555, 0.82462029, 0.05319973], [ 0.67492385, -0.69294472, -0.2531966..

What is the best way to iterate over multiple lists at once?

Let's say I have two or more lists of same length. What's a good way to iterate through them? a, b are the lists. for i, ele in enumerate(a): print ele, b[i] or for i in range(len(a)): pr..

TensorFlow ValueError: Cannot feed value of shape (64, 64, 3) for Tensor u'Placeholder:0', which has shape '(?, 64, 64, 3)'

I am new to TensorFlow and machine learning. I am trying to classify two objects a cup and a pendrive (jpeg images). I have trained and exported a model.ckpt successfully. Now I am trying to restore t..

Last Key in Python Dictionary

I am having difficulty figuring out what the syntax would be for the last key in a Python dictionary. I know that for a Python list, one may say this to denote the last: list[-1] I also know that o..

How can I list the contents of a directory in Python?

Can’t be hard, but I’m having a mental block...

Efficient thresholding filter of an array with numpy

I need to filter an array to remove the elements that are lower than a certain threshold. My current code is like this: threshold = 5 a = numpy.array(range(10)) # testing data b = numpy.array(filter(..

Two values from one input in python?

This is somewhat of a simple question and I hate to ask it here, but I can't seem the find the answer anywhere else: is it possible to get multiple values from the user in one line of Python? For in..

How to remove stop words using nltk or python

So I have a dataset that I would like to remove stop words from using stopwords.words('english') I'm struggling how to use this within my code to just simply take out these words. I have a list of..

Using Python Requests: Sessions, Cookies, and POST

I am trying to scrape some selling data using the StubHub API. An example of this data seen here: You'll notice that if you tr..

"Expected an indented block" error?

I can't understand why python gives an "Expected indentation block" error? """ This module prints all the items within a list""" def print_lol(the_list): """ The following for loop iterates over ever..

What is the purpose of "pip install --user ..."?

From pip install --help: --user Install to the Python user install directory for your platform. Typically ~/.local/, or %APPDATA%\Python on Windows. (See the Python documentation fo..

matplotlib: colorbars and its text labels

I'd like to create a colorbar legend for a heatmap, such that the labels are in the center of each discrete color. Example borrowed from here: import matplotlib.pyplot as plt import numpy as np from ..

How to remove \n from a list element?

I'm trying to get Python to a read line from a .txt file and write the elements of the first line into a list. The elements in the file were tab- separated so I used split("\t") to separate the elemen..

Microsoft Visual C++ 14.0 is required (Unable to find vcvarsall.bat)

I've installed Python 3.5 and while running pip install mysql-python it gives me the following error error: Microsoft Visual C++ 14.0 is required (Unable to find vcvarsall.bat) I have added th..

How to print values separated by spaces instead of new lines in Python 2.7

I am using Python 2.7.3 and I am writing a script which prints the hex byte values of any user-defined file. It is working properly with one problem: each of the values is being printed on a new line...

Finding moving average from data points in Python

I am playing in Python a bit again, and I found a neat book with examples. One of the examples is to plot some data. I have a .txt file with two columns and I have the data. I plotted the data just fi..

Convert nested Python dict to object?

I'm searching for an elegant way to get data using attribute access on a dict with some nested dicts and lists (i.e. javascript-style object syntax). For example: >>> d = {'a': 1, 'b': {'c'..

How to get line count of a large file cheaply in Python?

I need to get a line count of a large file (hundreds of thousands of lines) in python. What is the most efficient way both memory- and time-wise? At the moment I do: def file_len(fname): with op..

How to scp in Python?

What's the most pythonic way to scp a file in Python? The only route I'm aware of is os.system('scp "%s" "%s:%s"' % (localfile, remotehost, remotefile) ) which is a hack, and which doesn't work o..

Round number to nearest integer

I've been trying to round long float numbers like: 32.268907563; 32.268907563; 31.2396694215; 33.6206896552; ... With no success so far. I tried math.ceil(x), math.floor(x) (although that would rou..

Creating files and directories via Python

I'm having trouble creating a directory and then opening/creating/writing into a file in the specified directory. The reason seems unclear to me. I'm using os.mkdir() and path=chap_name print "Path ..

In Python, how do I loop through the dictionary and change the value if it equals something?

If the value is None, I'd like to change it to "" (empty string). I start off like this, but I forget: for k, v in mydict.items(): if v is None: ... right? ..

Find column whose name contains a specific string

I have a dataframe with column names, and I want to find the one that contains a certain string, but does not exactly match it. I'm searching for 'spike' in column names like 'spike-2', 'hey spike', '..

Python script to do something at the same time every day

I have a long running python script that I want to do someting at 01:00 every morning. I have been looking at the sched module and at the Timer object but I can't see how to use these to achieve this..

How can I turn a string into a list in Python?

How can I turn a string (like 'hello') into a list (like [h,e,l,l,o])?..

How can I generate a list of consecutive numbers?

Say if you had a number input 8 in python and you wanted to generate a list of consecutive numbers up to 8 like [0, 1, 2, 3, 4, 5, 6, 7, 8] How could you do this?..

Matplotlib-Animation "No MovieWriters Available"

Under Linux, I've been checking out matplotlib's animation class, and it seems to work except that I cant initialise the movie writer to write out the movie. Using either of the examples: http://ma..

What is the official "preferred" way to install pip and virtualenv systemwide?

Is it this, which people seem to recommend most often: $ sudo apt-get install python-setuptools $ sudo easy_install pip $ sudo pip install virtualenv Or this, which I got from http://www.pip-instal..

Remap values in pandas column with a dict

I have a dictionary which looks like this: di = {1: "A", 2: "B"} I would like to apply it to the "col1" column of a dataframe similar to: col1 col2 0 w a 1 1 2 2 2..

How to use sys.exit() in Python

player_input = '' # This has to be initialized for the loop while player_input != 0: player_input = str(input('Roll or quit (r or q)')) if player_input == q: # This will break the loop if t..

How do I do a not equal in Django queryset filtering?

In Django model QuerySets, I see that there is a __gt and __lt for comparative values, but is there a __ne or != (not equals)? I want to filter out using a not equals. For example, for Model: bool..

What exactly should be set in PYTHONPATH?

I'm going through and writing a setup doc for other developers at work for a python project and I've been reading up on the PYTHONPATH environment variable. I'm looking at my current development syste..

Determine the type of an object?

Is there a simple way to determine if a variable is a list, dictionary, or something else? I am getting an object back that may be either type and I need to be able to tell the difference...

Delete all objects in a list

I create many object then I store in a list. But I want to delete them after some time because I create news one and don't want my memory goes high (in my case, it jumps to 20 gigs of ram if I don't d..

How do I install a Python package with a .whl file?

I'm having trouble installing a Python package on my Windows machine, and would like to install it with Christoph Gohlke's Window binaries. (Which, to my experience, alleviated much of the fuss for ma..

Why does "pip install" inside Python raise a SyntaxError?

I'm trying to use pip to install a package. I try to run pip install from the Python shell, but I get a SyntaxError. Why do I get this error? How do I use pip to install the package? >>> ..

Saving an Object (Data persistence)

I've created an object like this: = 'banana' company1.value = 40 I would like to save this object. How can I do that?..

Docker "ERROR: could not find an available, non-overlapping IPv4 address pool among the defaults to assign to the network"

I have a directory apkmirror-scraper-compose with the following structure: . +-- docker-compose.yml +-- privoxy ¦   +-- config ¦   +-- Dockerfile +-- scraper ¦   +-- Dockerfile ¦   +-- ne..

Extracting extension from filename in Python

Is there a function to extract the extension from a filename?..

String to Dictionary in Python

So I've spent way to much time on this, and it seems to me like it should be a simple fix. I'm trying to use Facebook's Authentication to register users on my site, and I'm trying to do it server side..

How can I convert a datetime object to milliseconds since epoch (unix time) in Python?

I have a Python datetime object that I want to convert to unix time, or seconds/milliseconds since the 1970 epoch. How do I do this?..

How to convert a string to utf-8 in Python

I have a browser which sends utf-8 characters to my Python server, but when I retrieve it from the query string, the encoding that Python returns is ASCII. How can I convert the plain string to utf-8?..

Tkinter example code for multiple windows, why won't buttons load correctly?

I am writing a program which should: Open a window with the press of a button. Close the newly opened window with the press of another button. I'm using classes so I can insert the code into a lar..

Python 3.6 install win32api?

Is there a way to install the win32api module for python 3.6 or do I have to change my version of python? Everytime I try to install it using pip I get the following error: Could not find a version ..

How to plot a histogram using Matplotlib in Python with a list of data?

I am trying to plot a histogram using the matplotlib.hist() function but I am not sure how to do it. I have a list probability = [0.3602150537634409, 0.42028985507246375, 0.373117033603708, 0.36..

Automatically create requirements.txt

Sometimes I download the python source code from github and don't know how to install all the dependencies. If there is no requirements.txt file I have to create it by hands. The question is: Given t..

How can I check if a string only contains letters in Python?

I'm trying to check if a string only contains letters, not digits or symbols. For example: >>> only_letters("hello") True >>> only_letters("he7lo") False ..

Saving numpy array to txt file row wise

I have an numpy array of form a = [1,2,3] which I want to save to a .txt file such that the file looks like: 1 2 3 If I use numpy.savetxt then I get a file like: 1 2 3 There should be a easy ..

How do I get the opposite (negation) of a Boolean in Python?

For the following sample: def fuctionName(int, bool): if int in range(...): if bool == True: return False else: return True Is there any way to skip the ..

Loop through list with both content and index

It is very common for me to loop through a python list to get both the contents and their indexes. What I usually do is the following: S = [1,30,20,30,2] # My list for s, i in zip(S, range(len(S))): ..

How do I fix this "TypeError: 'str' object is not callable" error?

I'm creating a basic program that will use a GUI to get a price of an item, then take 10% off of the price if the initial price is less than 10, or take 20% off of the price if the initial price is gr..

How to clear the interpreter console?

Like most Python developers, I typically keep a console window open with the Python interpreter running to test commands, dir() stuff, help() stuff, etc. Like any console, after a while the visible b..

What's the difference between select_related and prefetch_related in Django ORM?

In Django doc, select_related() "follows" foreign-key relationships, selecting additional related-object data when it executes its query. prefetch_related() does a separate lookup for each ..

Efficient way to remove keys with empty strings from a dict

I have a dict and would like to remove all the keys for which there are empty value strings. metadata = {u'Composite:PreviewImage': u'(Binary data 101973 bytes)', u'EXIF:CFAPattern2': u''..

How to plot data from multiple two column text files with legends in Matplotlib?

How do I open multiple text files from different directories and plot them on a single graph with legends?..

Create empty file using python

I'd like to create a file with path x using python. I've been using os.system(y) where y = 'touch %s' % (x). I've looked for a non-directory version of os.mkdir, but I haven't been able to find anythi..

How to deal with certificates using Selenium?

I am using Selenium to launch a browser. How can I deal with the webpages (URLs) that will ask the browser to accept a certificate or not? In Firefox, I may have a website like that asks me to accept..

Does Python have an ordered set?

Python has an ordered dictionary. What about an ordered set?..

Why doesn't list have safe "get" method like dictionary?

Why doesn't list have a safe "get" method like dictionary? >>> d = {'a':'b'} >>> d['a'] 'b' >>> d['c'] KeyError: 'c' >>> d.get('c', 'fail') 'fail' >>> l ..

Windows- Pyinstaller Error "failed to execute script " When App Clicked

I am having a tough time overcoming this error, I have searched everywhere for that error message and nothing seems relevant to my situation: "failed to execute script new-app" new-app is my pytho..

Python "expected an indented block"

Let me start off by saying that I am COMPLETELY new to programming. I have just recently picked up Python and it has consistently kicked me in the head with one recurring error -- "expected an indent..

How to implement the Softmax function in Python

From the Udacity's deep learning class, the softmax of y_i is simply the exponential divided by the sum of exponential of the whole Y vector: Where S(y_i) is the softmax function of y_i and e is th..

How do I add a placeholder on a CharField in Django?

Take this very simple form for example: class SearchForm(Form): q = forms.CharField(label='search') This gets rendered in the template: <input type="text" name="q" id="id_q" /> However..

Remove pandas rows with duplicate indices

How to remove rows with duplicate index values? In the weather DataFrame below, sometimes a scientist goes back and corrects observations -- not by editing the erroneous rows, but by appending a dupli..

Remove all special characters, punctuation and spaces from string

I need to remove all special characters, punctuation and spaces from a string so that I only have letters and numbers...

How to fix: "UnicodeDecodeError: 'ascii' codec can't decode byte"

as3:~/ngokevin-site# nano content/blog/20140114_test-chinese.mkd as3:~/ngokevin-site# wok Traceback (most recent call last): File "/usr/local/bin/wok", line 4, in Engine() File "/usr/local/lib/python2..

Iterating over Numpy matrix rows to apply a function each?

I want to be able to iterate over the matrix to apply a function to each row. How can I do it for a Numpy matrix ? ..

View RDD contents in Python Spark?

Running a simple app in pyspark. f = sc.textFile("") wc = f.flatMap(lambda x: x.split(' ')).map(lambda x: (x, 1)).reduceByKey(add) I want to view RDD contents using foreach action: wc.for..

"pip install unroll": "python egg_info" failed with error code 1

I'm new to Python and have been trying to install some packages with pip. But pip install unroll gives me Command "python egg_info" failed with error code 1 in C:\Users\MARKAN~1\AppDa..

How to use "raise" keyword in Python

I have read the official definition of "raise", but I still don't quite understand what it does. In simplest terms, what is "raise"? Example usage would help...

Get index of a row of a pandas dataframe as an integer

Assume an easy dataframe, for example A B 0 1 0.810743 1 2 0.595866 2 3 0.154888 3 4 0.472721 4 5 0.894525 5 6 0.978174 6 7 0.859449 7 8 0.541247 8 9 0.232302 9..

Extract subset of key-value pairs from Python dictionary object?

I have a big dictionary object that has several key value pairs (about 16), but I am only interested in 3 of them. What is the best way (shortest/efficient/most elegant) to achieve that? The best I k..

Windows batch command(s) to read first line from text file

How can I read the first line from a text file using a Windows batch file? Since the file is large I only want to deal with the first line...

How to find the minimum value in an ArrayList, along with the index number? (Java)

I need to get the index value of the minimum value in my arraylist in Java. MY arraylist holds several floats, and I'm trying to think of a way I can get the index number of the smallest float so I ca..

CSS hide scroll bar, but have element scrollable

I have this element called items and the content inside the element is longer than the element height, I want to make it scrollable but hide the scroll bar, how would I do that? <div class="left-s..

#include errors detected in vscode

I am using Visual Studio Code in my C++ project. I installed Microsoft C/C++ Extension for VS Code. I got the following error: #include errors detected. Please update your includePath. IntelliSens..

Java Mouse Event Right Click

On my three button mouse MouseEvent.BUTTON2= Middle Click and MouseEvent.BUTTON3 = Right Click. Is this the case on a two button mouse? Thanks..

Angular ng-repeat Error "Duplicates in a repeater are not allowed."

I am defining a custom filter like so: <div class="idea item" ng-repeat="item in items" isoatom> <div class="section comment clearfix" ng-repeat="comment in item.comments | range:1:2..

Vuejs: v-model array in multiple input

I have an input text field with a v-model attached, and every time someone hits the "Add" button, another input text get added to the DOM with the same v-model attached. I thought I'd then get an arra..

How to restore/reset npm configuration to default values?

I have played with npm set and npm config set for several times, now I want to reset to default values (a kind of factory reset). Does npm provide a command to do that? or Should I delete all configu..

must appear in the GROUP BY clause or be used in an aggregate function

I have a table that looks like this caller 'makerar' cname | wmname | avg --------+-------------+------------------------ canada | zoro | 2.0000000000000000 spain | luf..

Iterating through directories with Python

I need to iterate through the subdirectories of a given directory and search for files. If I get a file I have to open it and change the content and replace it with my own lines. I tried this: impor..

How do I show multiple recaptchas on a single page?

I have 2 forms on a single page. One of the forms has a recaptcha displaying all the time. The other should display a recaptcha only after a certain event such as maxing out login attempts. So ther..

How to divide flask app into multiple py files?

My flask application currently consists of a single file with multiple routes and the main() route defined. Is there some way I could create a file that contains routes that were not ..

Output first 100 characters in a string

Can seem to find a substring function in python. Say I want to output the first 100 characters in a string, how can I do this? I want to do it safely also, meaing if the string is 50 characters it ..

Padding between ActionBar's home icon and title

Does anybody know how to set padding between the ActionBar's home icon and the title?..

How to use SVG markers in Google Maps API v3

Can I use my converted image.svg as google map icon. I was converting my png image to svg and I want to use this like google map symbol that can be rotated. I already tried to use the google map symbo..

How do I catch an Ajax query post error?

I would like to catch the error and show the appropriate message if the Ajax request fails. My code is like the following, but I could not manage to catch the failing Ajax request. function getAjaxD..

Serialize Property as Xml Attribute in Element

I have the following class: [Serializable] public class SomeModel { [XmlElement("SomeStringElementName")] public string SomeString { get; set; } [XmlElement("SomeInfoElementName")] p..

Javascript return number of days,hours,minutes,seconds between two dates

Does anyone can link me to some tutorial where I can find out how to return days , hours , minutes, seconds in javascript between 2 unix datetimes? I have: var date_now = unixtimestamp; var date_fut..

How to execute multiple commands in a single line

I know Unix has the following command which can execute multiple commands in a single line, how can I do this in DOS? command1 ; command2 ; command3 ... ..

Convert pyQt UI to python

Is there a way to convert a ui formed with qtDesigner to a python version to use without having an extra file? I'm using Maya for this UI, and converting this UI file to a readable python version to ..

How to fetch JSON file in Angular 2

as I am new to the Angular, can anyone please give a simple solution on loading the JSON file data using angular 2. My code is like below Index.html _x000D_ _x000D_ <html>_x000D_ <head&..

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

I want to print HTML template in angular 2. I had explored about this I got solution in angularjs 1 Print Html Template in Angularjs 1 Any suggestion would be appreciated ..

Why I get 411 Length required error?

This is how I call a service with .NET: var requestedURL = "" + code + "&client_id=" + client_id + "&client_secret=" + client_secret + "&re..

How do you delete a column by name in data.table?

To get rid of a column named "foo" in a data.frame, I can do: df <- df[-grep('foo', colnames(df))] However, once df is converted to a data.table object, there is no way to just remove a column. ..

Maven2: Best practice for Enterprise Project (EAR file)

I am just switching from Ant to Maven and am trying to figure out the best practice to set up a EAR file based Enterprise project? Let's say I want to create a pretty standard project with a jar file..

Groovy - How to compare the string?

how to compare the string which is passed as a parameter the following method is not working. String str = "saveMe" compareString(str) def compareString(String str){ def str2 = "sav..

Python match a string with regex

I need a python regular expression to check if a word is present in a string. The string is separated by commas, potentially. So for example, line = 'This,is,a,sample,string' I want to search base..

How to get the title of HTML page with JavaScript?

How can I get the title of an HTML page with JavaScript?..

How to display default text "--Select Team --" in combo box on pageload in WPF?

In a WPF app, in MVP app, I have a combo box,for which I display the data fetched from Database. Before the items added to the Combo box, I want to display the default text such as " -- Select Tea..

Could not load file or assembly 'System.Data.SQLite'

I've installed ELMAH 1.1 .Net 3.5 x64 in my ASP.NET project and now I'm getting this error (whenever I try to see any page): Could not load file or assembly 'System.Data.SQLite, Version=

Insertion sort vs Bubble Sort Algorithms

I'm trying to understand a few sorting algorithms, but I'm struggling to see the difference in the bubble sort and insertion sort algorithm. I know both are O(n2), but it seems to me that bubble sort..

Upload File With Ajax XmlHttpRequest

Hi i am trying to send file with xmlhttprequest with this code. var url= "http://localhost:80/...."; $(document).ready(function(){ document.getElementById('upload').addEventListener('cha..

Sum one number to every element in a list (or array) in Python

Here I go with my basic questions again, but please bear with me. In Matlab, is fairly simple to add a number to elements in a list: a = [1,1,1,1,1] b = a + 1 b then is [2,2,2,2,2] In python this..

How to scale an Image in ImageView to keep the aspect ratio

In Android, I defined an ImageView's layout_width to be fill_parent (which takes up the full width of the phone). If the image I put to ImageView is bigger than the layout_width, Android will scale i..

making matplotlib scatter plots from dataframes in Python's pandas

What is the best way to make a series of scatter plots using matplotlib from a pandas dataframe in Python? For example, if I have a dataframe df that has some columns of interest, I find myself typi..

MySQL InnoDB not releasing disk space after deleting data rows from table

I have one MySQL table using the InnoDB storage engine; it contains about 2M data rows. When I deleted data rows from the table, it did not release allocated disk space. Nor did the size of the ibdat..

How to upgrade glibc from version 2.13 to 2.15 on Debian?

I heard I can do it using apt-get install libc6, but I need to add something to /etc/apt/sources.list to receive the newest glibc version. What should I do?..

Close application and launch home screen on Android

I have two different activities. The first launches the second one. In the second activity, I call System.exit(0) in order to force the application to close, but the first activity is automatically di..

Comparison of C++ unit test frameworks

I know there are already a few questions regarding recommendations for C++ unit test frameworks, but all the answers did not help as they just recommend one of the frameworks but do not provide any in..

Eclipse Intellisense?

How do I tell Eclipse to automatically make suggestions as I type? I'm looking for a Visual Studio Intellisense-like feature with Resharper. Currently I have to press CTRL+Space each time...

How to create hyperlink to call phone number on mobile devices?

What is the proper, universal format for creating a clickable hyperlink for users on mobile devices to call a phone number? Area code with dashes <a href="tel:555-555-1212">555-555-1212</a&..

Python pip install module is not found. How to link python to pip location?

I'm a newbie and I needed the pySerial and feedparser module for my projects. I'm running Mountain lion. I followed the following tutorial so that I could upgrade to python 2.7.3 and then use the abo..

Overflow-x:hidden doesn't prevent content from overflowing in mobile browsers

I have a website here. Viewed in a desktop browser, the black menu bar properly extends only to edge of the window, since the body has overflow-x:hidden. In any mobile browser, whether Android or ..

How to open local files in Swagger-UI

I'm trying to open my self generated swagger specification file my.json with swagger-ui on my local computer. So I downloaded the latest tag v2.1.8-M1 and extracted the zip. Then I went inside the su..

Can I run CUDA on Intel's integrated graphics processor?

I have a very simple Toshiba Laptop with i3 processor. Also, I do not have any expensive graphics card. In the display settings, I see Intel(HD) Graphics as display adapter. I am planning to learn som..

Create a HTML table where each TR is a FORM

I'm trying to create a table where each row is a form. I want that each input is in a different table division, but I still need that for example, all first inputs belong to the same table head and so..

Warning: implode() [function.implode]: Invalid arguments passed

I'm getting the error below... Warning: implode() [function.implode]: Invalid arguments passed in \wp-content/themes/mytheme/functions.php on line 1335 at... function my_get_tags_sitemap(){ if ..

split python source code into multiple files?

I have a code that I wish to split apart into multiple files. In matlab one can simply call a .m file, and as long as it is not defined as anything in particular it will just run as if it were part of..

How to set proper codeigniter base url?

when I had my site on development environment - it was url: Now on production server my codeigniter app's address has to be I moved it there, and everytime I'm trying..

Generate GUID in MySQL for existing Data?

I've just imported a bunch of data to a MySQL table and I have a column "GUID" that I want to basically fill down all existing rows with new and unique random GUID's. How do I do this in MySQL ? I t..

How can I fix "Design editor is unavailable until a successful build" error?

I started to learn Android Studio from yesterday. I try to echo out simple "Hello World": <?xml version="1.0" encoding="utf-8"?> <RelativeLayout android:id="@+id/activity_main" xmlns..

jQuery Set Cursor Position in Text Area

How do you set the cursor position in a text field using jQuery? I've got a text field with content, and I want the users cursor to be positioned at a certain offset when they focus on the field. Th..

How to handle a single quote in Oracle SQL

How do I insert a record in a column having varchar data type having single quote in it? Example: first name is ROBERT and last name is D'COSTA..

Space between two rows in a table?

Is this possible via CSS? I'm trying tr.classname { border-spacing: 5em; } to no avail. Maybe I'm doing something wrong?..

Markdown open a new window link

I'm trying to edit a website which uses a modx cms, and it's using Markdown. Now I would like to open a new link into another window. Is it possible? The Link [Registration](http://www.registration...

How to open every file in a folder

I have a python script, which in the script open a file, say file1, and then do something maybe print out the total number of characters. filename = 'file1' f = open(filename, 'r') content ..

How to get the url parameters using AngularJS

HTML source code <div ng-app=""> <div ng-controller="test"> <div ng-address-bar browser="html5"></div> <br><br> $location.url() = {{$locatio..

moment.js get current time in milliseconds?

var timeArr = moment().format('HH:mm:ss').split(':'); var timeInMilliseconds = (timeArr[0] * 3600000) + (timeArr[1] * 60000); This solution works, test it, but I'd rather just use the moment api in..

How can I remove an entry in global configuration with git config?

I ran a global configuration command in git to exclude certain files using a .gitignore_global file: git config --global core.excludesfile ~/.gitignore_global Is there a way to undo the creation of..

How to send POST in angularjs with multiple params?

I want to send multiple parameters using angularjs HTTP post service. Here is client side code: $"http://localhost:53263/api/Products/", [$scope.product, $scope.product2]). then(fu..

How do I create a dictionary with keys from a list and values defaulting to (say) zero?

I have a = [1,2,3,4] and I want d = {1:0, 2:0, 3:0, 4:0} d = dict(zip(q,[0 for x in range(0,len(q))])) works but is ugly. What's a cleaner way?..

Mockito matcher and array of primitives

With Mockito, I want to verify() a method call with byte[] in its argument list, but I didn't find how to write this. myMethod( byte[] ) I just want something like anyByteArray(), how to do that w..

Set the layout weight of a TextView programmatically

I'm trying to dynamically create TableRow objects and add them to a TableLayout. The TableRow objects has 2 items, a TextView and a CheckBox. The TextView items need to have their layout weight set to..

ios simulator: how to close an app

When you "run" the simulator from xCode, the app automatically launches, and then you can click the home button to suspend the app. What I want to do is close the app from within the simulator. So, ho..

Correct path for img on React.js

I have some problem with my images on my react project. Indeed I always thought that relative path into src attribute was built on the files architecture Here my files architecture: components f..

How does the "position: sticky;" property work?

I want to make the navigation bar stick to the top of the viewport once a user scrolls the page, but it's not working and I have no clue why. If you can please help, here is my HTML and CSS code: _x00..

How to represent empty char in Java Character class

I want to represent an empty character in Java as "" in String... Like that char ch = an empty character; Actually I want to replace a character without leaving space. I think it might be suffici..

Can a normal Class implement multiple interfaces?

I know that multiple inheritances between Interfaces is possible, e.g.: public interface C extends A,B {...} //Where A, B and C are Interfaces But is it possible to have a regular Class inherit fro..

how to save DOMPDF generated content to file?

I am using Dompdf to create PDF file but I don't know why it doesn't save the created PDF to server. Any ideas? require_once("./pdf/"); $html = '<html><body&g..

How to write a multiline command?

How do we extend a command to the next line? Basically whats the windows alternative for Linux's ls -l \ /usr/ Here we use backslashes to extend the command onto the next lines. What's the equivalent..

Android: how to make keyboard enter button say "Search" and handle its click?

I can't figure this out. Some apps have a EditText (textbox) which, when you touch it and it brings up the on-screen keyboard, the keyboard has a "Search" button instead of an enter key. I want to im..

How to call a web service from jQuery

I want to call a webservice from jQuery. How can I do that?..

How do I set the time zone of MySQL?

On one server, when I run: mysql> select now(); +---------------------+ | now() | +---------------------+ | 2009-05-30 16:54:29 | +---------------------+ 1 row in set (0.00 sec) On..

Java Loop every minute

I want to write a loop in Java that firs starts up and goes like this: while (!x){ //wait one minute or two //execute code } I want to do this so that it does not use up system resources. ..

Max length for client ip address

Possible Duplicate: Maximum length of the textual representation of an IPv6 address? What would you recommend as the maximum size for a database column storing client ip addresses? I have ..

Python equivalent of a given wget command

I'm trying to create a Python function that does the same thing as this wget command: wget -c --read-timeout=5 --tries=0 "$URL" -c - Continue from where you left off if the download is interrupted...

How to show math equations in general github's markdown(not github's blog)

After investigating, I've found mathjax can do this. But when I write some example in my markdown file, it doesn't show the correct equations: I have added this in the head of markdown file: <scr..

XPath selecting a node with some attribute value equals to some other node's attribute value

<grand id="grand"> <parent> <child age="18" id="#not-grand"/> <child age="20" id="#grand"/> <!-- This is what I want to locate --> </parent> </grand&..

Is it possible to disable scrolling on a ViewPager

I have a ViewPager which instantiates a View. I'd like to disable both the scrolling of the viewpager and the child buttons momentarily while a search result is returned to the view. I've calling view..

Insert a row to pandas dataframe

I have a dataframe: s1 = pd.Series([5, 6, 7]) s2 = pd.Series([7, 8, 9]) df = pd.DataFrame([list(s1), list(s2)], columns = ["A", "B", "C"]) A B C 0 5 6 7 1 7 8 9 [2 rows x 3 columns] ..

How to Save Console.WriteLine Output to Text File

I have a program which outputs various results onto a command line console. How do I save the output to a text file using a StreamReader or other techniques? System.Collections.Generic.IEnumerable&l..

Best programming based games

Back when I was at school, I remember tinkering with a Mac game where you programmed little robots in a sort of pseudo-assembler language which could then battle each other. They could move themselves..

Where is body in a nodejs http.get response?

I'm reading the docs at, but for some reason, I can't seem to to actually find the body/data attribute on the returned, finished response obje..

Create a Path from String in Java7

How can I create a java.nio.file.Path object from a String object in Java 7? I.e. String textPath = "c:/dir1/dir2/dir3"; Path path = ?; where ? is the missing code that uses textPath...

How to find a value in an excel column by vba code Cells.Find

I have to find a value celda in an Excel sheet. I was using this vba code to find it: Set cell = Cells.Find(What:=celda, After:=ActiveCell, LookIn:= _ xlFormulas, LookAt:=xlWhole, SearchOrder:=xl..

Spring JPA and persistence.xml

I'm trying to set up a Spring JPA Hibernate simple example WAR for deployment to Glassfish. I see some examples use a persistence.xml file, and other examples do not. Some examples use a dataSource, a..

How can I specify the schema to run an sql file against in the Postgresql command line

I run scripts against my database like this... psql -d myDataBase -a -f myInsertFile.sql The only problem is I want to be able to specify in this command what schema to run the script against. I c..

CSS background image alt attribute

This is one I have not had to tackle before. I need to use alt tags on all images in a site including those used by CSS background-image attribute. There is no CSS property like this as far as I know..

How to display Toast in Android?

I have a slider that can be pulled up and then it shows a map. I can move the slider up and down to hide or show the map. When the map is on front, I can handle touch events on that map. Everytime I t..

Appending to an object

I have an object that holds alerts and some information about them: var alerts = { 1: { app: 'helloworld', message: 'message' }, 2: { app: 'helloagain', message: 'another message' } } In a..

How to fix warning from date() in PHP"

I am using XAMPP(PHP Version 5.3.1) on winxp. When I try to call time() or date() function on my localhost. It will show warning message as this, Severity: Warning Message: date() [function.d..

SQL Server reports 'Invalid column name', but the column is present and the query works through management studio

I've hit a bit of an impasse. I have a query that is generated by some C# code. The query works fine in Microsoft SQL Server Management Studio when run against the same database. However when my code..

How to fix "containing working copy admin area is missing" in SVN?

I deleted manually a directory I just added, offline, in my repository. I can't restore the directory. Any attempt to do an update or a commit will fail with: "blabla/.svn" containing working copy ..

Disable sorting for a particular column in jQuery DataTables

I am using the jQuery DataTables plugin to sort the table fields. My question is: how do I disable sorting for a particular column? I have tried with the following code, but it did not work: "aoColum..

How to check programmatically if an application is installed or not in Android?

We have installed applications programmatically. If the application is already installed in the device the application is open automatically. Otherwise install the particular application. Guide Me..

How to Troubleshoot Intermittent SQL Timeout Errors

We've been having a few instances per day where we get a slew of SQL Timeout errors from multiple applications (System.Data.SqlClient.SqlException: Timeout expired. The timeout period elapsed prior t..

What is Teredo Tunneling Pseudo-Interface?

Running ipconfig /all shows a Teredo Tunneling Pseudo-Interface. What is that? Does this have something to do with IPv4 vs IPv6? Should I get rid of it? If so how?..

pandas: filter rows of DataFrame with operator chaining

Most operations in pandas can be accomplished with operator chaining (groupby, aggregate, apply, etc), but the only way I've found to filter rows is via normal bracket indexing df_filtered = df[df['c..

strange error in my Animation Drawable

A strange error when trying to start Activity. i think the error in my Animation Drawable LogCat: 12-31 06:37:45.138: E/AndroidRuntime(922): FATAL EXCEPTION: main 12-31 06:37:45.138: E/Andr..

Transitions on the CSS display property

I'm currently designing a CSS 'mega dropdown' menu - basically a regular CSS-only dropdown menu, but one that contains different types of content. At the moment, it appears that CSS 3 transition..

How to install plugin for Eclipse from .zip

How to install Eclipse plugin from .zip? I have installed plugins by choosing the site and then check but never from .zip. Can anybody help?..

round a single column in pandas

Is there a way to round a single column in pandas without affecting the rest of the dataframe? df: item value1 value2 0 a 1.12 1.3 1 a 1.50 2.5 2 a 0.10..

Python: AttributeError: '_io.TextIOWrapper' object has no attribute 'split'

I have a textfile, let's call it goodlines.txt and I want to load it and make a list that contains each line in the text file. I tried using the split() procedure like this: >>> f = open('g..

How to normalize a histogram in MATLAB?

How to normalize a histogram such that the area under the probability density function is equal to 1?..

How to increase font size in the Xcode editor?

To increase font-size in Xcode is a pain...

Function pointer as parameter

I try to call a function which passed as function pointer with no argument, but I can't make it work. void *disconnectFunc; void D::setDisconnectFunc(void (*func)){ disconnectFunc = func; } voi..


Is there a way to perform an HTTP GET request within a Visual Basic script? I need to get the contents of the response from a particular URL for processing...

Can I restore a single table from a full mysql mysqldump file?

I have a mysqldump backup of my mysql database consisting of all of our tables which is about 440 megs. I want to restore the contents of just one of the tables from the mysqldump. Is this possible? T..

javascript regular expression to check for IP addresses

I have several ip addresses like: What type of regular expression should I write if I want to search for the all the 3 ip addresses? Eg, if I do 115.42.15..

What is the standard naming convention for html/css ids and classes?

Does it depend on the platform you are using, or is there a common convention that most developers suggest/follow? There are several options: id="someIdentifier"' - looks pretty consistent with jav..

'this' is undefined in JavaScript class methods

I'm new to JavaScript. New as far as all I've really done with it is tweaked existing code and wrote small bits of jQuery. Now I'm attempting to write a "class" with attributes and methods, but I'm h..

Multiple SQL joins

I need to execute a query To retrieve data from multiple tables but I'm rather confused on how to do it all at once. Books: _ISBN , BookTitle, Edition, Year, PublisherID, Pages, Rating Categories: _..

What does a (+) sign mean in an Oracle SQL WHERE clause?

Possible Duplicate: Oracle: What does (+) do in a WHERE clause? Consider the simplified SQL query below, in an Oracle database environment (although I'm not sure that it's Oracle-specific):..

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

I'm trying to run the following statement but am receiving the error messages just below. I have researched answers to no end and none have worked for me. I'm running Office 365 (64bit). I have loa..

How can I get a list of locally installed Python modules?

I would like to get a list of Python modules, which are in my Python installation (UNIX server). How can you get a list of Python modules installed in your computer?..

Remove file extension from a file name string

If I have a string saying "abc.txt", is there a quick way to get a substring that is just "abc"? I can't do an fileName.IndexOf('.') because the file name could be "abc.123.txt" or something and I ob..

How to split the screen with two equal LinearLayouts?

Wanna to split a screen for my app with two LinearLayouts. What parameters should I use to make exact splitting in two equal parts - first LinearLayout on the top and the second one is just under it...

Quickly create large file on a Windows system

In the same vein as Quickly create a large file on a Linux system, I'd like to quickly create a large file on a Windows system. By large I'm thinking 5 GB. The content doesn't matter. A built-in..

Wordpress 403/404 Errors: You don't have permission to access /wp-admin/themes.php on this server

Some background: I setup six blogs this week, all using Wordpress 2.92, installed with Fantastico on a baby croc plan with Hostgator. I used the same theme (heatmap 2.5.4) and plugins for each blog...

How can I convert byte size into a human-readable format in Java?

How can I convert byte size into a human-readable format in Java? Like 1024 should become "1 Kb" and 1024*1024 should become "1 Mb". I am kind of sick of writing this utility metho..

Vue.js unknown custom element

I'm a beginner with Vue.js and I'm trying to create an app that caters my daily tasks and I ran into Vue Components. So below is what I've tried but unfortunately, it gives me this error: vue.js:1..

Difference between getContext() , getApplicationContext() , getBaseContext() and "this"

What is the difference between getContext() , getApplicationContext() , getBaseContext() , and "this"? Though this is simple question I am unable to understand the basic difference between them. Ple..

Linq to SQL how to do "where [column] in (list of values)"

I have a function where I get a list of ids, and I need to return the a list matching a description that is associated with the id. E.g.: public class CodeData { string CodeId {get; set;} str..

How do you read from stdin?

I'm trying to do some of the code golf challenges, but they all require the input to be taken from stdin. How do I get that in Python?..

Permutations between two lists of unequal length

I’m having trouble wrapping my head around a algorithm I’m try to implement. I have two lists and want to take particular combinations from the two lists. Here’s an example. names = ['a', 'b'] n..

How to start an Android application from the command line?

How to start an Android application from the command line? There are similar question asked, but I can not find good any answers...

C# using Sendkey function to send a key to another application

I want to send a specific key (e.g. k) to another program named notepad, and below is the code that I used: private void SendKey() { [DllImport ("User32.dll")] static extern int SetForeground..

Which keycode for escape key with jQuery

I have two functions. When enter is pressed the functions runs correctly but when escape is pressed it doesn't. What's the correct number for the escape key? $(document).keypress(function(e) { ..

How can I let a table's body scroll but keep its head fixed in place?

I am writing a page where I need an HTML table to maintain a set size. I need the headers at the top of the table to stay there at all times but I also need the body of the table to scroll no matter h..

Installing MySQL-python

I got the below failure while trying to get MySQL-python installed on my Ubuntu/Linux Box.From the below it seem like the issue is sh: mysql_config: not found Could someone advice me on what to do? r..

What is ROWS UNBOUNDED PRECEDING used for in Teradata?

I am just starting on Teradata and I have come across an Ordered Analytical Function called "Rows unbounded preceding" in Teradata. I tried several sites to learn about the function but all of them us..

How to get the instance id from within an ec2 instance?

How can I find out the instance id of an ec2 instance from within the ec2 instance?..

SQL Server Script to create a new user

I want to write a script to create a admin user ( with abcd password ) in SQL Server Express. Also I want to assign this user admin full rights...

sqlalchemy IS NOT NULL select

How can I add the filter as in SQL to select values that are NOT NULL from a certain column ? SELECT * FROM table WHERE YourColumn IS NOT NULL; How can I do the same with SQLAlchemy filters? sel..

How to transform numpy.matrix or array to scipy sparse matrix

For SciPy sparse matrix, one can use todense() or toarray() to transform to NumPy matrix or array. What are the functions to do the inverse? I searched, but got no idea what keywords should be the ri..

Xcode Simulator: how to remove older unneeded devices?

I'm running Xcode 4.3.1 iOS-Simulator which originally only supports iOS 5.1. I need to test my code with iOS 4.3, so I used Xcode's "Install" feature to install it as described in "Installing Xcode ..

Compare two files report difference in python

I have 2 files called "hosts" (in different directories) I want to compare them using python to see if they are IDENTICAL. If they are not Identical, I want to print the difference on the screen. S..

How to define an enumerated type (enum) in C?

I'm not sure what is the proper syntax for using C enums. I have the following code: enum {RANDOM, IMMEDIATE, SEARCH} strategy; strategy = IMMEDIATE; But this does not compile, with the following e..

How can I set the initial value of Select2 when using AJAX?

I have a select2 v4.0.0 being populated from an Ajax array. If I set the val of the select2 I can see via javascript debugging that it has selected the correct item (#3 in my case), however this is no..

Is true == 1 and false == 0 in JavaScript?

I was reading a good book on JavaScript. It started with: Boolean type take only two literal values: true and false. These are distinct from numeric values, so true is not equal to 1, and false..

How can I clear console

As in the title. How can I clear console in C++?..

iloc giving 'IndexError: single positional indexer is out-of-bounds'

I am trying to encode some information to read into a Machine Learning model using the following import numpy as np import pandas as pd import matplotlib.pyplot as py Dataset = pd.read_csv('filenam..

How do I apply a diff patch on Windows?

There are plenty of programs out there that can create a diff patch, but I'm having a heck of a time trying to apply one. I'm trying to distribute a patch, and I got a question from a user about how t..

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

I need to copy a database from a remote server to a local one. I tried to use SQL Server Management Studio, but it only backs up to a drive on the remote server. Some points: I do not have access t..

Why number 9 in kill -9 command in unix?

I understand it's off topic, I couldn't find anywhere online and I was thinking maybe programming gurus in the community might know this. I usually use kill -9 pid to kill the job. I always wonder..

Convert java.util.Date to java.time.LocalDate

What is the best way to convert a java.util.Date object to the new JDK 8/JSR-310 java.time.LocalDate? Date input = new Date(); LocalDate date = ??? ..

How to change the MySQL root account password on CentOS7?

I have installed mySQL on a Centos7 vm but I have problems logging in with root. I tried logging in without password or tried any default ones (like mysql, admin etc) I looked in the my.cnf file and t..

What does -z mean in Bash?

I'm looking at the following code: if [ -z $2 ]; then echo "usage: ... (The 3 dots are irrelevant usage details.) Maybe I'm googling it wrong, but I couldn't find an explanation for the -..

Redis command to get all available keys?

Is there a Redis command for fetching all keys in the database? I have seen some python-redis libraries fetching them. But was wondering if it is possible from redis-client...

Specifying number of decimal places in Python

When accepting user input with a decimal in Python I'm using: #will input meal subtotal def input_meal(): mealPrice = input('Enter the meal subtotal: $') mealPrice = float (mealPrice)..

Printing all properties in a Javascript Object

I am following a code academy tutorial and i am finding this difficult. The assignment is the following: Use a for-in loop to print out all the properties of nyc. var nyc = { fullName: "New..

Android XXHDPI resources

The Google Nexus 10 comes out shortly, and is the first device to use xxhdpi resources. It sports a display density of about 300 DPI (according to the Nexus 10 website and this calculator). However, ..

Send raw ZPL to Zebra printer via USB

Typically, when I plug in my Zebra LP 2844-Z to the USB port, the computer sees it as a printer and I can print to it from notepad like any other generic printer. However, my application has some bar ..

PHP PDO with foreach and fetch

The following code: <?php try { $dbh = new PDO("mysql:host=$hostname;dbname=$dbname", $username, $password); echo "Connection is successful!<br/>"; $sql = "SELECT * FROM users"; ..

Merge two json/javascript arrays in to one array

I have two json arrays like var json1 = [{id:1, name: 'xxx' ...}] var json2 = [{id:2, name: 'xyz' ...}] I want them merge in to single arrays var finalObj = [{id:1, name: 'xxx' ...},{id:2, name: '..

Using HTML data-attribute to set CSS background-image url

I plan on building a custom photo gallery for a friend and I know exactly how I am going to be producing the HTML, however I am running into a small issue with the CSS.(I would prefer to not have the ..

Current user in Magento?

I'm customizing the product view page and I need to show the user's name. How do I access the account information of the current user (if he's logged in) to get Name etc. ?..

How to get detailed list of connections to database in sql server 2005?

How to get detailed list of connections to database in sql server 2005?..

Should you commit .gitignore into the Git repos?

Do you think it is a good practice to commit .gitignore into a Git repo? Some people don't like it, but I think it is good as you can track the file's history. Isn't it?..

Regex pattern for checking if a string starts with a certain substring?

What's the regular expression to check if a string starts with "mailto" or "ftp" or "joe" or... Now I am using C# and code like this in a big if with many ors: String.StartsWith("mailto:") String.St..

No 'Access-Control-Allow-Origin' - Node / Apache Port Issue

i've created a small API using Node/Express and trying to pull data using Angularjs but as my html page is running under apache on localhost:8888 and node API is listen on port 3000, i am getting the ..

PermissionError: [Errno 13] Permission denied

I'm getting this error : Exception in Tkinter callback Traceback (most recent call last): File "C:\Python34\lib\tkinter\", line 1538, in __call__ return self.func(*args) File "C:/Users/Mar..

How to keep the console window open in Visual C++?

I'm starting out in Visual C++ and I'd like to know how to keep the console window. For instance this would be a typical "hello world" application: int _tmain(int argc, _TCHAR* argv[]) { cout &..

Spring boot: Unable to start embedded Tomcat servlet container

I'm new to Spring Boot and having with error while running my application. I'm following a tutorial and I believe I'm having proper parent and dependencies with POM, please help me main class: pack..

Selenium C# WebDriver: Wait until element is present

I want to make sure that an element is present before the webdriver starts doing stuff. I'm trying to get something like this to work: WebDriverWait wait = new WebDriverWait(driver, new TimeSpan(0, 0,..

When is null or undefined used in JavaScript?

I am really confused as to when JavaScript returns null or undefined. Also different browsers seem to be returning these differently. Could you please give some examples of null/undefined with the br..

Char Comparison in C

I'm trying to compare two chars to see if one is greater than the other. To see if they were equal, I used strcmp. Is there anything similar to strcmp that I can use?..

How to compare data between two table in different databases using Sql Server 2008?

I have two database's, named DB1 and DB2 in Sql server 2008. These two database's have the same tables and same table data also. However, I want to check if there are any differences between the dat..

#1062 - Duplicate entry for key 'PRIMARY'

So my MySQL database is behaving a little bit wierd. This is my table: Name shares id price indvprc cat 2 4 81 0 goog 4 4 20 20 fb 4 9 20 20 I'm getting th..

MySQL : transaction within a stored procedure

The basic structure of my stored procedure is, BEGIN .. Declare statements .. START TRANSACTION; .. Query 1 .. .. Query 2 .. .. Query 3 .. COMMIT; END My..

How to prevent caching of my Javascript file?

I have a simple html: <html> <body> <head> <meta charset="utf-8"> <meta http-equiv='cache-control' content='no-cache'> <meta http-equiv='expires' content='0'> <..

Color text in terminal applications in UNIX

I started to write a terminal text editor, something like the first text editors for UNIX, such as vi. My only goal is to have a good time, but I want to be able to show text in color, so I can have s..

PHP shell_exec() vs exec()

I'm struggling to understand the difference between shell_exec() and exec()... I've always used exec() to execute server side commands, when would I use shell_exec()? Is shell_exec() just a shorthan..

How to round an image with Glide library?

So, anybody know how to display an image with rounded corners with Glide? I am loading an image with Glide, but I don't know how to pass rounded params to this library. I need display image like foll..

Django: Display Choice Value class Person(models.Model): name = models.CharField(max_length=200) CATEGORY_CHOICES = ( ('M', 'Male'), ('F', 'Female'), ) gender = models.CharField(max_len..

C# nullable string error

private string? typeOfContract { get { return (string?)ViewState["typeOfContract"]; } set { ViewState["typeOfContract"] = value; } } Later in the code I use it like this: typeOfContract = Reque..

SQL Joins Vs SQL Subqueries (Performance)?

I wish to know if I have a join query something like this - Select E.Id,E.Name from Employee E join Dept D on E.DeptId=D.Id and a subquery something like this - Select E.Id,E.Name from Employee W..

Sort tuples based on second parameter

I have a list of tuples that look something like this: ("Person 1",10) ("Person 2",8) ("Person 3",12) ("Person 4",20) What I want produced, is the list sorted in ascending order, by the second valu..

Make copy of an array

I have an array a which is constantly being updated. Let's say a = [1,2,3,4,5]. I need to make an exact duplicate copy of a and call it b. If a were to change to [6,7,8,9,10], b should still be [1,2,3..

What programming languages can one use to develop iPhone, iPod Touch and iPad (iOS) applications?

What programming languages can one use to develop iPhone, iPod Touch and iPad (iOS) applications? Also are there plans in the future to expand the amount of programming languages that iOS will suppor..

isset PHP isset($_GET['something']) ? $_GET['something'] : ''

I am looking to expand on my PHP knowledge, and I came across something I am not sure what it is or how to even search for it. I am looking at isset code, and I see isset($_GET['something']) ..

Download a file from NodeJS Server using Express

How can I download a file that is in my server to my machine accessing a page in a nodeJS server? I'm using the ExpressJS and I've been trying this: app.get('/download', function(req, res){ var f..

'' is not recognized as an internal or external command, operable program or batch file

Whenever I try and run mycommand.exe from my windows cmd.exe terminal, I get this error: ''mycommand.exe' is not recognized as an internal or external command, operable program or batch file' Th..

#ifdef in C#

I would like to do the below but in C# instead of C++ #ifdef _DEBUG bool bypassCheck=TRUE_OR_FALSE;//i will decide depending on what i am debugging #else bool bypassCheck = false; //NEVER bypass it #..

How to sort an array of objects in Java?

My array does not contain any string. But its contains object references. Every object reference returns name, id, author and publisher by toString method. public String toString() { return (..

Page redirect with successful Ajax request

I have a form that uses Ajax for client-side verification. The end of the form is the following: $.ajax({ url: 'mail3.php', type: 'POST', data: 'contactName=' + name + '&c..

How to declare a global variable in JavaScript

How can I declare a global variable in JavaScript?..

How to generate .NET 4.0 classes from xsd?

What are the options to generate .NET 4.0 c# classes (entities) from an xsd file, using Visual Studio 2010?..

Query to get the names of all tables in SQL Server 2008 Database

Is it possible to write a query that will give me the names of all the tables in an SQL Server database? I'm working on some 'after the fact' documentation on a system I didn't create and am looking f..

How do you specifically order ggplot2 x axis instead of alphabetical order?

I'm trying to make a heatmap using ggplot2 using the geom_tiles function here is my code below: p<-ggplot(data,aes(Treatment,organisms))+geom_tile(aes(fill=S))+ scale_fill_gradient(low = "black"..

How to configure socket connect timeout

When the Client tries to connect to a disconnected IP address, there is a long timeout over 15 seconds... How can we reduce this timeout? What is the method to configure it? The code I'm using to set..

How to remove backslash on json_encode() function?

How to remove the (\)backslash on a string? when using echo json_encode() ? For example: <?php $str = "$(\"#output\").append(\"<p>This is a test!</p>\")"; echo json_encode($str); ?&g..

WPF Add a Border to a TextBlock

Is it possible to add a border to a textblock. I need it to be added in the setter property below code: <Style x:Key="notCalled" TargetType="{x:Type TextBlock}"> <Setter Property="Margin..

Copying HTML code in Google Chrome's inspect element

I have a website of which I want to copy an HTML code from - how do I copy all the text in inspect element - so I don't get the website's HTML code, but the code that I have already changed so that I ..

Error "Metadata file '...\Release\project.dll' could not be found in Visual Studio"

Recently I started to get this message randomly: Metadata file '...\Release\project.dll' could not be found in Visual Studio I have a solution with several projects in it. The current build mode..

iOS Safari – How to disable overscroll but allow scrollable divs to scroll normally?

I'm working on an iPad-based web app, and need to prevent overscrolling so that it seems less like a web page. I'm currently using this to freeze the viewport and disable overscroll:

Trying to use Spring Boot REST to Read JSON String from POST

Am using the latest version of Spring Boot to read in a sample JSON via Restful Web Service... Here's my pom.xml: <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache...

how to make a new line in a jupyter markdown cell

md $S$: a set of shops $I$: a set of items M wants to get I'd like to make a new line between this two sentences. We usually put " (space)" after the first sentence before a new line, but it doesn't..

Could not find a version that satisfies the requirement tensorflow

I installed the latest version of Python (3.6.4 64-bit) and the latest version of PyCharm (2017.3.3 64-bit). Then I installed some modules in PyCharm (Numpy, Pandas, etc), but when I tried installing ..

Call Stored Procedure within Create Trigger in SQL Server

I have a stored procedure named insert2Newsletter with parameters (@sex nvarchar(10), @f_name nvarchar(50), @l_name nvarchar(70), @email nvarchar(75), @ip_address nvarchar(50), @hotelID int, @maArt ..