Examples On Programing Languages

CUDA incompatible with my gcc version

I have troubles compiling some of the examples shipped with CUDA SDK. I have installed the developers driver (version 270.41.19) and the CUDA toolkit, then finally the SDK (both the 4.0.17 version). Initially it didn't compile at all giving: error ...

Creating a URL in the controller .NET MVC

I need to be able to construct a link in the Action on the controller to send an email. What is best practice to do this? I don't want to construct it myself in case my routes change. Should I have a view for each email and render that and send it?...

What do \t and \b do?

I expect this simple line of code printf("foo\b\tbar\n"); to replace "o" with "\t" and to produce the following output fo bar (assuming that tab stop occurs every 8 characters). On the contrary I get foo bar It seems that my shell int...

Do copyright dates need to be updated?

Every now and then I see a web site that has an old copyright date. In my mind, I always think "Look at the sucker who forgot to update his copyright year!" Then, while I was hard-coding a copyright year into the site I'm currently designing, it sudd...

Failed to load AppCompat ActionBar with unknown error in android studio

Below is my xml file. In preview there is two error'Failed to load AppCompat ActionBar with unknown error' & 'Failed to instaniate more than one class'. How ever am able to run the app.But the app crashes and in Logcat no errors are shown. This...

Android: ScrollView force to bottom

I would like a ScrollView to start all the way at the bottom. Any methods?...

Get pandas.read_csv to read empty values as empty string instead of nan

I'm using the pandas library to read in some CSV data. In my data, certain columns contain strings. The string "nan" is a possible value, as is an empty string. I managed to get pandas to read "nan" as a string, but I can't figure out how to get i...

update columns values with column of another table based on condition

I have two tables... table1 ( id, item, price ) values: id | item | price ------------- 10 | book | 20 20 | copy | 30 30 | pen | 10 ....table2 ( id, item, price) values: id | item | price ------------- 10 | book | 20 20 | book | 30 Now I...

How to return HTTP 500 from ASP.NET Core RC2 Web Api?

Back in RC1, I would do this: [HttpPost] public IActionResult Post([FromBody]string something) { try{ // ... } catch(Exception e) { return new HttpStatusCodeResult((int)HttpStatusCode.InternalServerError); } ...

ThreeJS: Remove object from scene

I'm using ThreeJS to develop a web application that displays a list of entities, each with corresponding "View" and "Hide" button; e.g. entityName View Hide. When user clicks View button, following function is called and entity drawn on screen succes...

Force "git push" to overwrite remote files

I want to push my local files, and have them on a remote repo, without having to deal with merge conflicts. I just want my local version to have priority over the remote one. How can I do this with Git?...

Configuration Error: <compilation debug="true" targetFramework="4.0"> ASP.NET MVC3

I'm trying to deploy my website on somee.com but keeps getting this error I've tried googling and it says I have to change my App Pool to ASP.NET 4.0. I've tried that already but with no luck:( Informations: -My site was coded in 4.0 Framework...

Understanding the ngRepeat 'track by' expression

I'm having difficulties understanding how the track by expression of ng-repeat in angularjs works. The documentation is very scarce: http://docs.angularjs.org/api/ng/directive/ngRepeat Can you explain what the difference between those two snippets o...

How to host material icons offline?

My apologies if this is a very simple question, but how do you use google material icons without a <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet"> ? I would like my app to be able to display the ico...

Float a DIV on top of another DIV

I was recently assigned the job of copying a JS popup our previous web developer made. I've got it very similar yet there's one thing I can't get, for the close button (X) to float over the popup in the top right corner (rather than being sat on top ...

'module' has no attribute 'urlencode'

When I try to follow the Python Wiki's example related to URL encoding: >>> import urllib >>> params = urllib.urlencode({'spam': 1, 'eggs': 2, 'bacon': 0}) >>> f = urllib.urlopen("http://www.musi-cal.com/cgi-bin/query", pa...

SQLite error 'attempt to write a readonly database' during insert?

I have a SQLite database that I am using for a website. The problem is that when I try to INSERT INTO it, I get a PDOException SQLSTATE[HY000]: General error: 8 attempt to write a readonly database I SSH'd into the server and checked permissions, ...

Get unique values from arraylist in java

I have an ArrayList with a number of records and one column contains gas names as CO2 CH4 SO2 etc.Now i want to retrieve different gas names(unique) only without repetation from the ArrayList. How can it be done?...

Appending an element to the end of a list in Scala

I can't add an element of type T into a list List[T]. I tried with myList ::= myElement but it seems it creates a strange object and accessing to myList.last always returns the first element that was put inside the list. How can I solve this problem?...

Rails: How to run `rails generate scaffold` when the model already exists?

I'm new to Rails so my current project is in a weird state. One of the first things I generated was a "Movie" model. I then started defining it in more detail, added a few methods, etc. I now realize I should have generated it with rails generate ...

Jquery select this + class

How can I select a class from that object this? $(".class").click(function(){ $("this .subclass").css("visibility","visible"); }) I want to select a $(this+".subclass"). How can I do this with Jquery?...

How to list all `env` properties within jenkins pipeline job?

Given a jenkins build pipeline, jenkins injects a variable env into the node{}. Variable env holds environment variables and values. For example, environment variable BRANCH_NAME can be accessed with node { echo ${env.BRANCH_NAME} ... I want...

Ignore .classpath and .project from Git

I keep myself telling me and others not to commit .classpath and .project files and use Maven. Somehow, Junior developers always ignore certain rules and commits those files and it's much better to have such files for newbies who can jump and ...

How can I insert a line break into a <Text> component in React Native?

I want to insert a new line (like \r\n, <br />) in a Text component in React Native. If I have: <text> <br /> Hi~<br /> this is a test message.<br /> </text> Then React Native renders Hi~ this is a test message. I...

What does git rev-parse do?

What does git rev-parse do? I have read the man page but it raised more questions than answers. Things like: Pick out and massage parameters Massage? What does that mean? I'm using as a resolver (to SHA1) of revision specifiers, like git rev...

How can I make a button redirect my page to another page?

I have been trying the following: <form action="/home" class="inline"> <button class="float-left submit-button" >Home</button> </form> It seems to work but it goes to the page "/home?" Is there a better way for me to m...

Laravel Unknown Column 'updated_at'

I've just started with Laravel and I get the following error: Unknown column 'updated_at' insert into gebruikers (naam, wachtwoord, updated_at, created_at) I know the error is from the timestamp column when you migrate a table but I'm not us...

Detecting touch screen devices with Javascript

In Javascript/jQuery, how can I detect if the client device has a mouse? I've got a site that slides up a little info panel when the user hovers their mouse over an item. I'm using jQuery.hoverIntent to detect the hover, but this obviously doesn'...

How to edit data in result grid in SQL Server Management Studio

I want to edit some row values once I get a query output in the result grid. Its true that we can right click the table and say open table to get an editable table output, but what I want is editable query output, only certain rows matching for my cr...

Laravel Migration Change to Make a Column Nullable

I created a migration with unsigned user_id. How can I edit user_id in a new migration to also make it nullable()? Schema::create('throttle', function(Blueprint $table) { $table->increments('id'); // this needs to also be nullable, how sh...

Changing background color of text box input not working when empty

I am having a tough time with this javascript code to change the background color of a text input if the input is empty. Here is the code: function checkFilled() { var inputVal = document.getElementById("subEmail").value; if (inputVal == ""...

How to use a DataAdapter with stored procedure and parameter

I want to fill a DataGridView control using DataAdapter. But I don't know how to do it since I'm using a stored procedure with parameter. Can someone cite an example please?...

Android widget: How to change the text of a button

How can I change the text of an Android button widget within code and not the XML file?...

os.path.dirname(__file__) returns empty

I want to get the path of the current directory under which a .py file is executed. For example a simple file D:\test.py with code: import os print os.getcwd() print os.path.basename(__file__) print os.path.abspath(__file__) print os.path.dirname(...

Eloquent: find() and where() usage laravel

I am trying to get a record from a posts database table using its id. I've been banging my head on the find() method for quite sometime now, confused as to why it wasn't working. Here is my query that looks correct to me but didn't work: $post = Pos...

How do I check if a file exists in Java?

How can I check whether a file exists, before opening it for reading in Java (the equivalent of Perl's -e $filename)? The only similar question on SO deals with writing the file and was thus answered using FileWriter which is obviously not app...

Can we add div inside table above every <tr>?

Hi am trying to add a div above every <tr> but when i look at the html console the div are showing outside the table. below is the html code. <table> <div> <tr><td></td></tr> </div> <div&g...

Populating VBA dynamic arrays

The following code gives me error 9 "subscript out of range". I meant to declare a dynamic array so that the dimension changes as I add elements to it. Do I have to create a "spot" on the array before I store something in it like in JS? Sub test_arr...

How to pass anonymous types as parameters?

How can I pass anonymous types as parameters to other functions? Consider this example: var query = from employee in employees select new { Name = employee.Name, Id = employee.Id }; LogEmployees(query); The variable query here doesn't have strong ...

Set a button background image iPhone programmatically

In Xcode, how do you set the background of a UIButton as an image? Or, how can you set a background gradient in the UIButton?...

ServletContext.getRequestDispatcher() vs ServletRequest.getRequestDispatcher()

why getRequestDispatcher(String path) of the ServletRequest interface cannot extend outside the current servlet context where as getRequestDispatcher(String path) of the ServletContext can use the getContext(String uripath) meth...

How do I extract data from a DataTable?

I have a DataTable that is filled in from an SQL query to a local database, but I don't know how to extract data from it. Main method (in test program): static void Main(string[] args) { const string connectionString = "server=localhost\\SQLExpr...

Validating an XML against referenced XSD in C#

I have an XML file with a specified schema location such as this: xsi:schemaLocation="someurl ..\localSchemaPath.xsd" I want to validate in C#. Visual Studio, when I open the file, validates it against the schema and lists errors perfectly. Some...

What is difference between INNER join and OUTER join

Difference between inner and outer join. i am using two table and want to fetch data from both table so which type join we should use owning of that we can solve our problem ...

Maven plugins can not be found in IntelliJ

After updating IntelliJ from version 12 to 13, the following Maven-related plugins cannot be resolved: org.apache.maven.plugins:maven-clean-plugin:2.4.1 org.apache.maven.plugins:maven-deploy-plugin org.apache.maven.plugins:maven-install-plugin org.ap...

Java - Access is denied java.io.FileNotFoundException

I have the following code: List<FileItem> items = uploadHandler.parseRequest(request); for (FileItem item : items) { if (!item.isFormField()) { File file = new File("D:/Data"); } } When I am trying to save a file, I am gettin...

How to delete columns in numpy.array

I would like to delete selected columns in a numpy.array . This is what I do: n [397]: a = array([[ NaN, 2., 3., NaN], .....: [ 1., 2., 3., 9]]) In [398]: print a [[ NaN 2. 3. NaN] [ 1. 2. 3. 9.]] In [399]: z = any(...

How to enable Auto Logon User Authentication for Google Chrome

I have a site I go to that allows me to auto log in with my creditentials (windows) and using Internet Explorer I can just set the option under "User Authentication" to "Automatic logon with current user name and password", but I'm wanting to use Goo...

Regex allow digits and a single dot

What would be the regex to allow digits and a dot? Regarding this \D only allows digits, but it doesn't allow a dot, I need it to allow digits and one dot this is refer as a float value I need to be valid when doing a keyup function in jQuery, but al...

Webdriver and proxy server for firefox

are there any ways to set firefox's proxy settings? I found here information about FoxyProxy but when Selenium works, plugins are unactivated in window....

jquery count li elements inside ul -> length?

If a ul has more than one li-element inside of it, something should happen, otherwise not! What am I doing wrong? if ( $('#menu ul').length > 1 ) { ...

Editing an item in a list<T>

How do I edit an item in the list in the code below: List<Class1> list = new List<Class1>(); int count = 0 , index = -1; foreach (Class1 s in list) { if (s.Number == textBox6.Text) index = count; // I found a match and I wan...

How can I parse a local JSON file from assets folder into a ListView?

I'm currently developing a physics app that is supposed to show a list of formulas and even solve some of them (the only problem is the ListView) This is my main layout <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"...

Find all matches in workbook using Excel VBA

I am trying to write a VBA routine that will take a string, search a given Excel workbook, and return to me all possible matches. I currently have an implementation that works, but it is extremely slow as it is a double for loop. Of course the buil...

How to create a temporary table in SSIS control flow task and then use it in data flow task?

I have a control flow where I create a temp database and table in a with a T-SQL Command. When I add a dataflow I would like to query the table but I can't because the table doesn't exist to grab information from. When I try I get errors about loggin...

int main() vs void main() in C

In C, I know that int main() returns an int where void main() does not. Other than that, is there a difference between them? Is the first better than the second?...

Load arrayList data into JTable

I'm trying to set items from a method called FootballClub and so far it's fine. but then I created an arrayList from it and I somehow can't find a way to store this information into a JTable. The problem is that i cant find a way to set a fixed numbe...

Regex any ASCII character

What is the regex to match xxx[any ASCII character here, spaces included]+xxx? I am trying xxx[(\w)(\W)(\s)]+xxx, but it doesn't seem to work....

How do I link to part of a page? (hash?)

How do you link (with <a>) so that the browser goes to certain subheading on the target page as opposed to the top?...

Delete specified file from document directory

I want to delete an image from my app document directory. Code I have written to delete image is: -(void)removeImage:(NSString *)fileName { fileManager = [NSFileManager defaultManager]; paths = NSSearchPathForDirectoriesInDomains(NSDocum...

Update data on a page without refreshing

I have a website where I need to update a status. Like for a flight, you are departing, cruise or landed. I want to be able to refresh the status without having my viewers to have and reload the whole page. I know there is a way to do it with AJAX an...

How to get Linux console window width in Python

Is there a way in python to programmatically determine the width of the console? I mean the number of characters that fits in one line without wrapping, not the pixel width of the window. Edit Looking for a solution that works on Linux...

WCF ServiceHost access rights

I get the following error when going through the WCF tutorial. HTTP could not register URL http://+:8000/ServiceModelSamples/Service/. Your process does not have access rights to this namespace (see http://go.microsoft.com/fwlink/?LinkId=70353 for d...

OpenSSL: unable to verify the first certificate for Experian URL

I am trying to verify an SSL connection to Experian in Ubuntu 10.10 with OpenSSL client. openssl s_client -CApath /etc/ssl/certs/ -connect dm1.experian.com:443 The problem is that the connection closes with a Verify return code: 21 (unable to ver...

Hide axis values but keep axis tick labels in matplotlib

I have this image: plt.plot(sim_1['t'],sim_1['V'],'k') plt.ylabel('V') plt.xlabel('t') plt.show() I want to hide the numbers; if I use: plt.axis('off') ...I get this image: It also hide the labels, V and t. How can I keep the labels while ...

Can you change a path without reloading the controller in AngularJS?

It's been asked before, and from the answers it doesn't look good. I'd like to ask with this sample code in consideration... My app loads the current item in the service that provides it. There are several controllers that manipulate the item data w...

enable or disable checkbox in html

I want to enable or disable checkbox in table's row on basis of condition. code - <td><input type="checkbox" name="repriseCheckBox" disabled={checkStat == 1 ? true : false}/></td> if checkStat = 1, need to disable checkbox else...

Returning Arrays in Java

I have absolutely no idea as to why this code won't return an array... I feel like there is a problem with my compiler: public class trial1{ public static void main(String[] args){ numbers(); } public static int[] numbers(){ ...

Running PowerShell as another user, and launching a script

I won't get into all the details of why I need this, but users must be able to launch PowerShell as a service account and when PowerShell loads it needs to run a script. I already can launch PowerShell with the stored credentials (stored as a secure ...

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 - as suggested in the question. The installation w...

Format a JavaScript string using placeholders and an object of substitutions?

I have a string with say: My Name is %NAME% and my age is %AGE%. %XXX% are placeholders. We need to substitute values there from an object. Object looks like: {"%NAME%":"Mike","%AGE%":"26","%EVENT%":"20"} I need to parse the object and replace the...

Android get current Locale, not default

How do I get the user's current Locale in Android? I can get the default one, but this may not be the current one correct? Basically I want the two letter language code from the current locale. Not the default one. There is no Locale.current()...

Lambda function in list comprehensions

Why is the output of the following two list comprehensions different, even though f and the lambda function are the same? f = lambda x: x*x [f(x) for x in range(10)] and [lambda x: x*x for x in range(10)] Mind you, both type(f) and type(lambda ...

What is a "bundle" in an Android application

What is a bundle in an Android application? When to use it?...

How do I shut down a python simpleHTTPserver?

So I'm trying to learn d3, and the wiki suggested that To view the examples locally, you must have a local web server. Any web server will work; for example you can run Python's built-in server: python -m SimpleHTTPServer 8888 & ...

JavaScript - document.getElementByID with onClick

I'm trying to code a simple game in an HTML document just for fun. In it, there is an image which adds to your score when clicked. I created a simple if statement within the score-adding function which should change the image and what its onClick val...

MVC4 StyleBundle not resolving images

My question is similar to this: ASP.NET MVC 4 Minification & Background Images Except that I want to stick with MVC's own bundling if I can. I'm having a brain crash trying to figure out what the correct pattern is for specifying style bund...

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

I have a strange bug in the Visual Studio text editor. All my blank spaces are replaced by a "." public class Person { int age; } looks like this public..class..Person.......................... {.................. ..int age;................... ...

document.getElementById().value doesn't set the value

Browser is chromium (under ubuntu) This is a chunk of code: (of course) The alert messages shows the right value. but the points element doesn't get the right value, it actually gets empty. Can anybody tell me why? Here's how points element is de...

How to get current language code with Swift?

I want get the language code of the device (en, es...) in my app written with Swift. How can get this? I'm trying this: var preferredLanguages : NSLocale! let pre = preferredLanguages.displayNameForKey(NSLocaleIdentifier, value: preferredLanguages)...

How to find the width of a div using vanilla JavaScript?

How do you find the current width of a <div> in a cross-browser compatible way without using a library like jQuery?...

What is the difference between float and double?

I've read about the difference between double precision and single precision. However, in most cases, float and double seem to be interchangeable, i.e. using one or the other does not seem to affect the results. Is this really the case? When are floa...

Logical operator in a handlebars.js {{#if}} conditional

Is there a way in handlebars JS to incorporate logical operators into the standard handlebars.js conditional operator? Something like this: {{#if section1 || section2}} .. content {{/if}} I know I could write my own helper, but first I'd like to m...

R barplot Y-axis scale too short

I'm trying to generate a barplot, but the y-axis scale is too short. Here's my code: barplot(as.matrix(dat), log="y", ylim=c(10000,100000000), beside=TRUE, ylab = "Number of reads", col = c("gray","black","white")) It leaves the room for...

How to remove close button on the jQuery UI dialog?

How do I remove the close button (the X in the top-right corner) on a dialog box created by jQuery UI?...

How can I run code on a background thread on Android?

I want some code to run in the background continuously. I don't want to do it in a service. Is there any other way possible? I have tried calling the Thread class in my Activity but my Activity remains in the background for sometime and then it sto...

How to see what privileges are granted to schema of another user

Consider the case : In a database , I have two users A and B and their corresponding schema. I want to know , How can I get the information : what permissions are there for USER A in Schema B . Consider the case : We have two users and their associ...

Does Python have an ordered set?

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

reading and parsing a TSV file, then manipulating it for saving as CSV (*efficiently*)

My source data is in a TSV file, 6 columns and greater than 2 million rows. Here's what I'm trying to accomplish: I need to read the data in 3 of the columns (3, 4, 5) in this source file The fifth column is an integer. I need to use this integer ...

Python: fastest way to create a list of n lists

So I was wondering how to best create a list of blank lists: [[],[],[]...] Because of how Python works with lists in memory, this doesn't work: [[]]*n This does create [[],[],...] but each element is the same list: d = [[]]*n d[0].append(1) #[...

Cannot implicitly convert type 'int' to 'short'

I wrote the following small program to print out the Fibonacci sequence: static void Main(string[] args) { Console.Write("Please give a value for n:"); Int16 n = Int16.Parse(Console.ReadLine()); Int16 firstNo = 0; Int16 secondNo = 1...

how to prevent "directory already exists error" in a makefile when using mkdir

I need to generate a directory in my makefile and I would like to not get the "directory already exists error" over and over even though I can easily ignore it. I mainly use mingw/msys but would like something that works across other shells/systems ...

What’s the best RESTful method to return total number of items in an object?

I’m developing a REST API service for a large social networking website I’m involved in. So far, it’s working great. I can issue GET, POST, PUT and DELETE requests to object URLs and affect my data. However, this data is paged (limited to 30 re...

How to change the default GCC compiler in Ubuntu?

I have installed gcc-3.3/g++-3.3 on ubuntu 11.04 which already has gcc/g++-4.4. So in my system both gcc-3.3 and 4.4 are available. I am able to call both compilers as I want. If I just call the command gcc then gcc-4.4 will get called. To call gcc-3...

"dd/mm/yyyy" date format in excel through vba

I am trying to write a date in "dd/mm/yyyy" format in excel sheet thru excel-vba. I achieved it using Cells(1, 1).Value = Format(StartDate, "dd/mm/yyyy"). and my cell value comes out to be 30/04/2014, which is good..... But there is some weird probl...

How to call a method in another class of the same package?

How to call a method, which is in another class of same package in Java? What I know is, using an object we can call a method from a different class. Is there any other way to call a method of different class?...

Convert interface{} to int

I'm trying to get a value from a JSON and cast it to int but it doesn't work, and I don't know how to do it properly. Here is the error message: ...cannot convert val (type interface {}) to type int: need type assertion And the code: var f i...

Eclipse C++: Symbol 'std' could not be resolved

I am getting this error in the TestExecute.cpp - "Symbol 'std' could not be resolved" CODE #include <iostream> using namespace std; I just created a executable project in Eclipse (in Windows 7) as shown below. It seems like I am selec...

How to apply two CSS classes to a single element

Can i apply 2 classes to a single div or span or any html element? For example: <a class="c1" class="c2">aa</a> I tried and in my case c2 does not get applied. How can i apply both classes at once?...

How can I convert an HTML element to a canvas element?

It would be incredibly useful to be able to temporarily convert a regular element into a canvas. For example, say I have a styled div that I want to flip. I want to dynamically create a canvas, "render" the HTMLElement into the canvas, hide the origi...

Python Request Post with param data

This is the raw request for an API call: POST http://192.168.3.45:8080/api/v2/event/log?sessionKey=b299d17b896417a7b18f46544d40adb734240cc2&format=json HTTP/1.1 Accept-Encoding: gzip,deflate Content-Type: application/json Content-Length: 86 Host...

www-data permissions?

So I have a directory in /var/www (called cake) and I need to allow www-data to write to it, but I also want to write to it (without having to use sudo). I'm afraid to change the permissions to 777 in case some other user on my machine (or a hacker) ...

Property 'map' does not exist on type 'Observable<Response>'

I am trying to call an API from Angular but am getting this error: Property 'map' does not exist on type 'Observable<Response>' The answers from this similar question didn't solve my issue: Angular 2 beta.17: Property 'map' does not e...

How to Display blob (.pdf) in an AngularJS app

I have been trying to display pdf file which I am getting as a blob from a $http.post response. The pdf must be displayed within the app using <embed src> for example. I came across a couple of stack posts but somehow my example doesn't seem t...

Convenient C++ struct initialisation

I'm trying to find a convenient way to initialise 'pod' C++ structs. Now, consider the following struct: struct FooBar { int foo; float bar; }; // just to make all examples work in C and C++: typedef struct FooBar FooBar; If I want to convenie...

Number of lines in a file in Java

I use huge data files, sometimes I only need to know the number of lines in these files, usually I open them up and read them line by line until I reach the end of the file I was wondering if there is a smarter way to do that...

Removing duplicate characters from a string

How can I remove duplicate characters from a string using Python? For example, let's say I have a string: foo = 'mppmt' How can I make the string: foo = 'mpt' NOTE: Order is not important...

How can I ask the Selenium-WebDriver to wait for few seconds in Java?

I'm working on a Java Selenium-WebDriver. I added driver.manage().timeouts().implicitlyWait(2, TimeUnit.SECONDS); and WebElement textbox = driver.findElement(By.id("textbox")); because my Applications takes few seconds to load the User Inter...

How do I disable "missing docstring" warnings at a file-level in Pylint?

Pylint throws errors that some of the files are missing docstrings. I try and add docstrings to each class, method and function, but it seems that Pylint also checks that files should have a docstring at the beginning of them. Can I disable this some...

Check whether user has a Chrome extension installed

I am in the process of building a Chrome extension, and for the whole thing to work the way I would like it to, I need an external JavaScript script to be able to detect if a user has my extension installed. For example: A user installs my plugin, ...

Instagram how to get my user id from username?

I'm in the process of embedding my image feed in my website using JSON, the URL needs my user id so I can retrieve this feed. So, where can I find/get my user id?...

Select Specific Columns from Spark DataFrame

I have loaded CSV data into a Spark DataFrame. I need to slice this dataframe into two different dataframes, where each one contains a set of columns from the original dataframe. How do I select a subset into a Spark dataframe, based on columns ?...

How to use if-else option in JSTL

Is there an if-else tag available in JSTL?...

C# go to next item in list based on if statement in foreach

I am using C#. I have a list of items. I loop through each item using a foreach. Inside my foreach I have a lot of if statements checking some stuff. If any of these if statements returns a false then I want it to skip that item and go to the nex...

Entity Framework Code First - two Foreign Keys from same table

I've just started using EF code first, so I'm a total beginner in this topic. I wanted to create relations between Teams and Matches: 1 match = 2 teams (home, guest) and result. I thought it's easy to create such a model, so I started coding: pu...

percentage of two int?

I want to get two ints, one divided by the other to get a decimal or percentage. How can I get a percentage or decimal of these two ints? (I'm not sure if it is right.. I'm probably way off...) for example: int correct = 25; int questionNum = 100; f...

How to get complete address from latitude and longitude?

I want to get following values from Latitude and Longitude in android Street Address City / State Zip Complete Address How to achieve this?...

How to round a number to significant figures in Python

I need to round a float to be displayed in a UI. E.g, to one significant figure: 1234 -> 1000 0.12 -> 0.1 0.012 -> 0.01 0.062 -> 0.06 6253 -> 6000 1999 -> 2000 Is there a nice way to do this using the Python library, or do I have to write it ...

Flexbox: 4 items per row

I'm using a flex box to display 8 items that will dynamically resize with my page. How do I force it to split the items into two rows? (4 per row)? Here is a relevant snip: (Or if you prefer jsfiddle - http://jsfiddle.net/vivmaha/oq6prk1p/2/) _x00...

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 the player decides to quit print("Now let'...

create a white rgba / CSS3

I'm customizing a plugin that uses css3's rgba throughout, I'm trying to figure out how to toggle it for it to render white with the opacity. At default it's near the shade of #333, and my attempts area leading it to blue or brown. Whats the white cu...

String to decimal conversion: dot separation instead of comma

I have a string read from a textbox. It contains a comma for decimal separation. I have NumberFormatInfo.CurrencyDecimalSeparator set to , (comma) but when I convert the string to decimal Convert.ToDecimal(mystring); I obtain a dot separate value fo...

Mac install and open mysql using terminal

I downloaded the mysql dmg file and went through the wizard to run. Done. I have also started mysql server under system preferences. The purpose of me doing this is to work through the exercises of my SQL text book. The terminal commands are new to ...

open_basedir restriction in effect. File(/) is not within the allowed path(s):

I'm getting this error on an avatar upload on my site. I've never gotten it before and nothing was changed recently for me to begin getting this error... Warning: is_writable() [function.is-writable]: open_basedir restriction in effect. File(/) i...

Line Break in XML?

I'm a beginner in web development, and I'm trying to insert line breaks in my XML file. This is what my XML looks like: <musicpage> <song> <title>Song Title</title> <lyric>Lyrics</lyric> </son...

How to use "not" in xpath?

I want to write something of the sort: //a[not contains(@id, 'xx')] (meaning all the links that there 'id' attribute doesn't contain the string 'xx') I can't find the right syntax....

How to check if a file is empty in Bash?

I have a file called diff.txt. I Want to check whether it is empty. I wrote a bash script something like below, but I couldn't get it work. if [ -s diff.txt ] then touch empty.txt rm full.txt else touch full.txt rm emt...

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: "aoColumns": [ { "bSearchable": false }, null ] I...

Print a div content using Jquery

I want to print the content of a div using jQuery. This question is already asked in SO, but I can't find the correct (working) answer. This is is my HTML: <div id='printarea'> <p>This is a sample text for printing purpose.</p>...

Proper usage of Optional.ifPresent()

I am trying to understand the ifPresent() method of the Optional API in Java 8. I have simple logic: Optional<User> user=... user.ifPresent(doSomethingWithUser(user.get())); But this results in a compilation error: ifPresent(java.util.fun...

How to change colour of blue highlight on select box dropdown

How do I change the blue highlight on this dropdown please? link to select box demo I'd like to change the highlight color to gray if this is possible. _x000D_ _x000D_ select {_x000D_ border: 0;_x000D_ color: #EEE;_x000D_ background: transpa...

How do I add a Fragment to an Activity with a programmatically created content view

I want to add a Fragment to an Activity that implements its layout programmatically. I looked over the Fragment documentation but there aren't many examples describing what I need. Here is the type of code I tried to write: public class DebugExample...

How do I change the background of a Frame in Tkinter?

I have been creating an Email program using Tkinter, in Python 3.3. On various sites I have been seeing that the Frame widget can get a different background using Frame.config(background="color"). However, when I use this in my Frames it gives the fo...

Calling a function when ng-repeat has finished

What I am trying to implement is basically a "on ng repeat finished rendering" handler. I am able to detect when it is done but I can't figure out how to trigger a function from it. Check the fiddle:http://jsfiddle.net/paulocoelho/BsMqq/3/ JS var ...

Center the nav in Twitter Bootstrap

I want to be able to center the nav dead middle of a page and have it stayed centered in different resolutions. I don't want to use offsets to push it over or margin-left as this would just screw it up in different browser widths. This is the typical...

How to delete images from a private docker registry?

I run a private docker registry, and I want to delete all images but the latest from a repository. I don't want to delete the entire repository, just some of the images inside it. The API docs don't mention a way to do this, but surely it's possible?...

How do you add a JToken to an JObject?

I'm trying to add a JSON object from some text to an existing JSON file using JSON.Net. For example if I have the JSON data as below: { "food": { "fruit": { "apple": { "colour": "red", "size": "small" }, "or...

Javascript to stop HTML5 video playback on modal window close

I've got a html5 video element on a modal window. When I close the window the video continues to play. I'm a total newbie to JS. Is there an easy way to tie a video playback stop function to the window close button? Below is my html page: <!D...

Primitive type 'short' - casting in Java

I have a question about the primitive type short in Java. I am using JDK 1.6. If I have the following: short a = 2; short b = 3; short c = a + b; the compiler does not want to compile - it says that it "cannot convert from int to short" and sug...

Error occurred during initialization of VM (java/lang/NoClassDefFoundError: java/lang/Object)

I'm trying to install Java to use Eclipse (I followed all instructions to install Java and Eclipse) but my Eclipse is not starting due to some bad configuration I guess. I can't figure out why it's not working for me. Eclipse Installation: Extract...

Call to undefined method mysqli_stmt::get_result

Here's my code: include 'conn.php'; $conn = new Connection(); $query = 'SELECT EmailVerified, Blocked FROM users WHERE Email = ? AND SLA = ? AND `Password` = ?'; $stmt = $conn->mysqli->prepare($query); $stmt->bind_param('sss', $_POST['Emai...

Xcode build failure "Undefined symbols for architecture x86_64"

An Xcode beginner's question: It is my first experience with Xcode 4.6.3. I am trying to write a very simple console program, that searches for paired BT devices and prints them to an NSLog. It builds with the following error: Undefined symbols f...

Paging with LINQ for objects

How would you implement paging in a LINQ query? Actually for the time being, I would be satisfied if the sql TOP function could be imitated. However, I am sure that the need for full paging support comes up sooner later anyway. var queryResult = fr...

Where does Android emulator store SQLite database?

I'm working on an Android application that stores data in a SQLite database. My question is, where does this database file get stored on the filesystem when you're using an emulator? I have seen that it's stored in /data/data/package_name/databas...

SQL How to Select the most recent date item

Hello I have a table with columns: *using oracle ID NUMBER USER_ID NUMBER DATE_ADDED DATE DATE_VIEWED DATE DOCUMENT_ID VARCHAR2 URL VARCHAR2 DOCUMENT_TITLE VARCHAR2 DOCUMENT_DAT...

How can I remove or replace SVG content?

I have a piece of JavaScript code which creates (using D3.js) an svg element which contains a chart. I want to update the chart based on new data coming from a web service using AJAX, the problem is that each time I click on the update button, it gen...

PHP Warning: POST Content-Length of 8978294 bytes exceeds the limit of 8388608 bytes in Unknown on line 0

I am getting this error when trying to upload an import on WordPress on my XAMPP local dev environment: Warning: POST Content-Length of 8978294 bytes exceeds the limit of 8388608 bytes in Unknown on line 0 I changed the upload_max_filesize from 2M ...

Are there other whitespace codes like &nbsp for half-spaces, em-spaces, en-spaces etc useful in HTML?

Wondering if there are other codes available to use in an HTML newsletter. I would use cell padding or margins but I'm new to this HTML/CSS thing and I can't find a change that does effect both the Main Title line and the sub-head under it. Being a...

Reading numbers from a text file into an array in C

I'm a programming noob so please bear with me. I'm trying to read numbers from a text file into an array. The text file, "somenumbers.txt" simply holds 16 numbers as so "5623125698541159". #include <stdio.h> main() { FILE *myFile; my...

SQL JOIN and different types of JOINs

What is a SQL JOIN and what are different types?...

addEventListener not working in IE8

I have created a checkbox dynamically. I have used addEventListener to call a function on click of the checkbox, which works in Google Chrome and Firefox but doesn't work in Internet Explorer 8. This is my code: var _checkbox = document.createEleme...

Regex allow a string to only contain numbers 0 - 9 and limit length to 45

I am trying to create a regex to have a string only contain 0-9 as the characters and it must be at least 1 char in length and no more than 45. so example would be 00303039 would be a match, and 039330a29 would not. So far this is what I have but I ...

How do I get the directory of the PowerShell script I execute?

I run a PowerShell script. How do I get the directory path of this script I run? How to do this?...

Xml Parsing in C#

http://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/2.5_day.atom on this site, I wrote the following code to retrieve the data. protected void Button1_Click(object sender, EventArgs e) { string adresal = "http://" + txtAd.Text; ...

How can I make my layout scroll both horizontally and vertically?

I am using a TableLayout. I need to have both horizontal and vertical scrolling for this layout. By default I am able to get vertical scrolling in the view but horizontal scrolling is not working. I am using Android SDK 1.5 r3. I have already tried...

Nested lists python

Can anyone tell me how can I call for indexes in a nested list? Generally I just write: for i in range (list) but what if I have a list with nested lists as below: Nlist = [[2,2,2],[3,3,3],[4,4,4]...] and I want to go through the indexes of e...

Where do I mark a lambda expression async?

I've got this code: private async void ContextMenuForGroupRightTapped(object sender, RightTappedRoutedEventArgs args) { CheckBox ckbx = null; if (sender is CheckBox) { ckbx = sender as CheckBox; } if (null == ckbx) { ...

How to change Maven local repository in eclipse

I'm importing a multiple-module Maven project from the root directory on a shared drive on another server A. On server A, mvn install will run successfully, and Maven is set up properly with repository/ and settings.xml in /home/user/.m2. However, a...

Print in Landscape format

Possible Duplicate: Landscape printing from HTML I am using below code to show print window on button click: function print_onclick() { window.print(); return false; } I want the page to be printed in Landscape format. Is there ...

How do I add a newline to command output in PowerShell?

I run the following code using PowerShell to get a list of add/remove programs from the registry: Get-ChildItem -path hklm:\software\microsoft\windows\currentversion\uninstall ` | ForEach-Object -Process { Write-Output $_.GetValue("DisplayName")...

Calling a Sub in VBA

This my simplified script: Sub SomeOtherSub(Stattyp As String) 'Daty and the other variables are defined here CatSubProduktAreakum(Stattyp, Daty + UBound(SubCategories) + 2) End Sub Sub CatSubProduktAreakum(Stattyp As ...

What does "wrong number of arguments (1 for 0)" mean in Ruby?

What does "Argument Error: wrong number of arguments (1 for 0)" mean?...

Opening a .ipynb.txt File

I have got downloaded a file that got downloaded in a format .pynb.txt extension. Can anyone help me to figure how to make it in a readable format? Attaching a screenshot of the file when i tried opening in python notebook. Output of the python note...

Outlets cannot be connected to repeating content iOS

I have just created an app and have started hooking up @IBOutlet's to the storyboard. I am connecting some of them to labels in a UITableViewCell Prototype Cell with a Basic Style. When I connect it though I get this error in the Storyboard: The ...

How to scroll to top of the page in AngularJS?

I want to scroll to the top of the page after getting an ajax call response using angularjs. Basically, I am displaying alert messages on top of the page and I want to focus the alert message as the ajax response received. Thanks...

Java: How to insert CLOB into oracle database

I need to write an XML file content into oracle database where the column is of CLOB datatype. How will I do that?...

How to run PowerShell in CMD

I'm trying to run a PowerShell script inside cmd command line. Someone gave me an example and it worked: powershell.exe -noexit "& 'c:\Data\ScheduledScripts\ShutdownVM.ps1'" But the problem is my PowerShell script has input parameters, so I tr...

Comparing Class Types in Java

I want to compare the class type in Java. I thought I could do this: class MyObject_1 {} class MyObject_2 extends MyObject_1 {} public boolean function(MyObject_1 obj) { if(obj.getClass() == MyObject_2.class) System.out.println("true"); } I w...

How to center-justify the last line of text in CSS?

How can I center-justify text? Currently, justify does not center the last line....

Pretty print in MongoDB shell as default

Is there a way to tell Mongo to pretty print output? Currently, everything is output to a single line and it's difficult to read, especially with nested arrays and documents....

Initialize Array of Objects using NSArray

I'm pretty new to Objective-C and iOS so I've been playing around with the Picker View. I've defined a Person Class so that when you create a new Person it automatically gives that person a name and age. #import "Person.h" @implementation Person @...

How do I enable MSDTC on SQL Server?

Is this even a valid question? I have a .NET Windows app that is using MSTDC and it is throwing an exception: System.Transactions.TransactionManagerCommunicationException: Network access for Distributed Transaction Manager (MSDTC) has been disabl...

How to download a file with Node.js (without using third-party libraries)?

How do I download a file with Node.js without using third-party libraries? I don't need anything special. I only want to download a file from a given URL, and then save it to a given directory....

Populate unique values into a VBA array from Excel

Can anyone give me VBA code that will take a range (row or column) from an Excel sheet and populate a list/array with the unique values, i.e.: table table chair table stool stool stool chair when the macro runs would create an array some thing l...

node.js http 'get' request with query string parameters

I have a Node.js application that is an http client (at the moment). So I'm doing: var query = require('querystring').stringify(propertiesObject); http.get(url + query, function(res) { console.log("Got response: " + res.statusCode); }).on('error...

How to print a string at a fixed width?

I have this code (printing the occurrence of the all permutations in a string) def splitter(str): for i in range(1, len(str)): start = str[0:i] end = str[i:] yield (start, end) for split in splitter(end): ...

Cron job every three days

Is it possible to run a cronjob every three days? Or maybe 10 times/month....

SqlServer: Login failed for user

I've written a very simple JDBC login test program. And after all kinds of problems I've almost got it working. Almost, just can't seem to get past this "SQLServerException: Login failed for user xxxxx" problem. I created a simple database ...

onClick function of an input type="button" not working

I have this code which on clicking the button "Get more fields" will create a copy of the entire div and create fields. But on clicking the button nothing is happening. All the other buttons are working fine. Don't know what I'm doing wrong. Thanks f...

django - get() returned more than one topic

When I tried to relate an attribute with another one which has an M to M relation I received this error: get() returned more than one topic -- it returned 2! Can you guys tell me what that means and maybe tell me in advance how to avoid this er...

Passing dynamic javascript values using Url.action()

Could anyone please tell how to pass dynamic values using Url.action(). Something Like, var firstname="abc"; var username = "abcd"; location.href = '@Html.Raw(@Url.Action("Display", "Customer", new { uname = firstname ,name = username}))'; firstn...

How do I sort a list of dictionaries by a value of the dictionary?

I have a list of dictionaries and want each item to be sorted by a specific value. Take into consideration the list: [{'name':'Homer', 'age':39}, {'name':'Bart', 'age':10}] When sorted by name, it should become: [{'name':'Bart', 'age':10}, {'name':'...

how to generate a unique token which expires after 24 hours?

I have a WCF Webservice which checks if the user is valid. If the user is valid I want to generate a token which expires after 24 hours. public bool authenticateUserManual(string userName, string password,string language,string token) { if (Me...

Creating a dynamic choice field

I'm having some trouble trying to understand how to create a dynamic choice field in django. I have a model set up something like: class rider(models.Model): user = models.ForeignKey(User) waypoint = models.ManyToManyField(Waypoint) class...

CodeIgniter - How to return Json response from controller

How do I return response from the controller back to the Jquery Javascript? Javascript $('.signinform').submit(function() { $(this).ajaxSubmit({ type : "POST", url: 'index.php/user/signin', // target element(s) to be updated with...

Foreach loop in java for a custom object list

I have an ArrayList for type Room (my custom object) Defined as below ArrayList<Room> rooms = new ArrayList<Room>(); After then adding a series of objects to the ArrayList I want to go through them all and check various things. I am no...

Pseudo-terminal will not be allocated because stdin is not a terminal

I am trying to write a shell script that creates some directories on a remote server and then uses scp to copy files from my local machine onto the remote. Here's what I have so far: ssh -t user@server<<EOT DEP_ROOT='/home/matthewr/releases' d...

android - setting LayoutParams programmatically

I putting an in-game chat module into an app. I am adding text messages as they are received into a LinearLayout view. I want to set the layout params to the TextView but the following code is crashing and the error messages befuddle me. private voi...

How to save a Seaborn plot into a file

I tried the following code (test_seaborn.py): import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt matplotlib.style.use('ggplot') import seaborn as sns sns.set() df = sns.load_dataset('iris') sns_plot = sns.pairplot(df, hue='speci...

How to get the new value of an HTML input after a keypress has modified it?

I have an HTML input box <input type="text" id="foo" value="bar"> I've attached a handler for the 'keyup' event, but if I retrieve the current value of the input box during the event handler, I get the value as it was, and not as it will be!...

Extracting hours from a DateTime (SQL Server 2005)

I can extract the month and day by using Day(Date()), Month(Date()). I can't extract hours, with HOUR(Date()). I get the following error. 'HOUR' is not a recognized built-in function name. How can I extract hours?...

Bootstrap 3 - Responsive mp4-video

I tried to find a good solution on the bootstrap site but I didn't get an answer to this yet. I think I can't be the only one struggling with this, but I couldn't find anything that helped me. I'm trying to embed an mp4-video on my website. The prob...

How to hide axes and gridlines in Matplotlib (python)

I would like to be able to hide the axes and gridlines on a 3D matplotlib graph. I want to do this because when zooming in and out the image gets pretty nasty. I'm not sure what code to include here but this is what I use to create the graph. fig =...

Run C++ in command prompt - Windows

I know that everyone uses an IDE nowadays, but I just find it simpler to write my code in notepad++, compile it using a command prompt command, and run it from there too. At least that works for Java and Python. I've tried to get my head around how t...

vi/vim editor, copy a block (not usual action)

In vi/vim editor, I need to copy a block. There are many ways, but one way is very quick. label the first line by some way, then label the end line by some way, then put some command to copy the labeled lines. then copy, may using 'p', but not sure...

How can I specify working directory for popen

Is there a way to specify the running directory of command in Python's subprocess.Popen()? For example: Popen('c:\mytool\tool.exe', workingdir='d:\test\local') My Python script is located in C:\programs\python Is is possible to run C:\mytool\too...

How to catch an Exception from a thread

I have Java main class, in the class, I start a new thread, in the main, it waits until the thread dies. At some moment, I throw a runtime exception from the thread, but I can't catch the exception thrown from the thread in the main class. Here is ...

Run R script from command line

I have a file, called a.r, it has a chmod of 755, sayHello <- function(){ print('hello') } sayHello() How can I run this via command-line?...

Select columns in PySpark dataframe

I am looking for a way to select columns of my dataframe in PySpark. For the first row, I know I can use df.first(), but not sure about columns given that they do not have column names. I have 5 columns and want to loop through each one of them. +--+...

CORS: Cannot use wildcard in Access-Control-Allow-Origin when credentials flag is true

I have a setup involving Frontend server (Node.js, domain: localhost:3000) <---> Backend (Django, Ajax, domain: localhost:8000) Browser <-- webapp <-- Node.js (Serve the app) Browser (webapp) --> Ajax --> Django(Serve ajax POST requests) ...

Jquery change <p> text programmatically

EDIT: The solution was to add this to the profile page instead of the gender page. $('#profile').live( 'pageinit',function(event){ $('p#pTest').text(localStorage.getItem('gender')); }); I have a paragraph with som text in a listview that I want t...

Expand/collapse section in UITableView in iOS

Could somebody tell me the way to perform UITableView expandable/collapsible animations in sections of UITableView as below? or ...

Git cli: get user info from username

Is there a way to get the name of the user, given only their username? Something like this output git show <username> (I know this doesn't work) username: username name: First Last email: email@address I know I can do this with a GitHub api...

What is the purpose of the HTML "no-js" class?

I notice that in a lot of template engines, in the HTML5 Boilerplate, in various frameworks and in plain php sites there is the no-js class added onto the <HTML> tag. Why is this done? Is there some sort of default browser behavior that react...

How to insert a timestamp in Oracle?

I have an Oracle DB with a timestamp field in it. What is the correct SQL code to insert a timestamp into this field?...

Does C# have extension properties?

Does C# have extension properties? For example, can I add an extension property to DateTimeFormatInfo called ShortDateLongTimeFormat which would return ShortDatePattern + " " + LongTimePattern?...

Percentage width in a RelativeLayout

I am working on a form layout for a Login Activity in my Android App. The image below is how I want it to look like: I was able to achieve this layout with the following XML. The problem is, it's a bit hackish. I had to hard-code a width for the h...

Parsing huge logfiles in Node.js - read in line-by-line

I need to do some parsing of large (5-10 Gb)logfiles in Javascript/Node.js (I'm using Cube). The logline looks something like: 10:00:43.343423 I'm a friendly log message. There are 5 cats, and 7 dogs. We are in state "SUCCESS". We need to read ea...

SQL Server: combining multiple rows into one row

I have a SQL query like this; SELECT * FROM Jira.customfieldvalue WHERE CUSTOMFIELD = 12534 AND ISSUE = 19602 And that's the results; What I want is; showing in one row (cell) combined all STRINGVALUE's and they are separated with a comma. Lik...

Anaconda / Python: Change Anaconda Prompt User Path

I want to change my Anaconda Prompt User file path. Currently it is as follows: I want it to change to: C:\Users\u354590 How do I do this? The current version of anaconda I have is: Python 3.6.3 |Anaconda, Inc.| (default, Oct 15 2017, 03:27:4...

writing to serial port from linux command line

From windows I can communicate with a serial port device using following commands: mode com1: baud=9600 data=8 parity=n stop=1 copy con com1 alt+18alt+2ctrl+z Device starts the requested operation. When I try to accomplish the same operation from...

AngularJS - Find Element with attribute

I'm new to AngularJS. I've learned that I can find elements in the DOM using queries like the following: var e = angular.element(document.querySelector('#id')); var e = angular.element(elem.querySelector('.classname')); This is useful for finding ...

OR, AND Operator

Newbie question. How to calculate the value of the formula A f B, where f - the binary function OR or AND?...

How to explicitly obtain post data in Spring MVC?

Is there a way to obtain the post data itself? I know spring handles binding post data to java objects. But, given two fields that I want to process, how can I obtain that data? For example, suppose my form had two fields: <input type="text" na...

What does Python's eval() do?

In the book that I am reading on Python, it keeps using the code eval(input('blah')) I read the documentation, and I understand it, but I still do not see how it changes the input() function. What does it do? Can someone explain?...

Virtual Memory Usage from Java under Linux, too much memory used

I have a problem with a Java application running under Linux. When I launch the application, using the default maximum heap size (64 MB), I see using the tops application that 240 MB of virtual Memory are allocated to the application. This creates ...

Vertically align text to top within a UILabel

I have a UILabel with space for two lines of text. Sometimes, when the text is too short, this text is displayed in the vertical center of the label. How do I vertically align the text to always be at the top of the UILabel? ...

More Pythonic Way to Run a Process X Times

Which is more pythonic? While loop: count = 0 while count < 50: print "Some thing" count = count + 1 For loop: for i in range(50): print "Some thing" Edit: not duplicate because this has answers to determine which is clearer, vs...

grep for special characters in Unix

I have a log file (application.log) which might contain the following string of normal & special characters on multiple lines: *^%Q&$*&^@$&*!^@$*&^&^*&^& I want to search for the line number(s) which contains this s...

How to copy a directory structure but only include certain files (using windows batch files)

As the title says, how can I recursively copy a directory structure but only include some files. E.g given the following directory structure: folder1 folder2 folder3 data.zip info.txt abc.xyz folder4 folder5 dat...

EXCEL Multiple Ranges - need different answers for each range

I have spent a few hours working out how to do this which is why im posting it here now... If you want to return different values in a cell based on which range the value entered in another cell comes under then I have worked out how to do it!! (bear...

Setting background color for a JFrame

Just how do you set the background color for a JFrame?...

Ubuntu says "bash: ./program Permission denied"

I am running Ubuntu on computer 1 and computer 2. I compiled a C++ program on computer 1, and I can execute it from the terminal using ./program_name. It runs fine. However, when I try to do this on computer 2, it says: bash: ./program_name: permiss...

How do I measure a time interval in C?

I would like to measure time in C, and I am having a tough time figuring it out, all I want is something like this: start a timer run a method stop the timer report the time taken (at least to micro accuracy) Any help would be appreciated. (I am...

Can you append strings to variables in PHP?

Why does the following code output 0? It works with numbers instead of strings just fine. I have similar code in JavaScript that also works. Does PHP not like += with strings? <?php $selectBox = '<select name="number">'; for ($i=1;...

redirect to current page in ASP.Net

How can I perform a redirect with Server.Transfer() to the same page that is currently shown? I want to have A cleared form after submit. What other/better methods can I use to achieve the same?...

List of zeros in python

How can I create a list which contains only zeros? I want to be able to create a zeros list for each int in range(10) For example, if the int in the range was 4 I will get: [0,0,0,0] and for 7: [0,0,0,0,0,0,0] ...

How do I negate a condition in PowerShell?

How do I negate a conditional test in PowerShell? For example, if I want to check for the directory C:\Code, I can run: if (Test-Path C:\Code){ write "it exists!" } Is there a way to negate that condition, e.g. (non-working): if (Not (Test-Pat...

Where do I download JDBC drivers for DB2 that are compatible with JDK 1.5?

Where do I download JDBC drivers for DB2 that are compatible with JDK 1.5? They seem to be very elusive and I hit many dead-ends at IBM's website. I managed to find versions of the driver bundled with some tools such as IBM Data Studio. Unfortunately...

Parsing HTTP Response in Python

I want to manipulate the information at THIS url. I can successfully open it and read its contents. But what I really want to do is throw out all the stuff I don't want, and to manipulate the stuff I want to keep. Is there a way to convert the str...

Rotating a Div Element in jQuery

Trying to rotate a div element...This might be DOM blasphemy, could it work possibly with a canvas element? I'm not sure - if anybody has any ideas of how this could work or why it doesn't, I'd love to know. Thanks....

Quick way to create a list of values in C#?

I'm looking for a quick way to create a list of values in C#. In Java I frequently use the snippet below: List<String> l = Arrays.asList("test1","test2","test3"); Is there any equivalent in C# apart from the obvious one below? IList<stri...

Repository access denied. access via a deployment key is read-only

After successfully cloning my repo from heroku and added another remote 1/ git clone [email protected]:[APP].git 2/ git remote add bitbucket ssh://[email protected]/[ACCOUNT]/[REPO].git 3/ git push bitbucket master I am still getting this error after...

How do you make Git work with IntelliJ?

I am going to use Git version control by IntelliJ Community Edition in order to make branches of the programs I intend to develop. I am striving to accustom myself to its functionality and I come accross obstacles. I follow the instructions of the...

Converting a char to ASCII?

I have tried lots of solutions to convert a char to Ascii. And all of them have got a problem. One solution was: char A; int ValeurASCII = static_cast<int>(A); But VS mentions that static_cast is an invalid type conversion!!! PS: my A is a...

Difference between & and && in Java?

Possible Duplicates: What's the difference between | and || in Java? Difference in & and && I was just wondering what the difference between & and && is? A few days I wrote a condition for an if statement the ...

Google Play on Android 4.0 emulator

How can I install the Google Play .apk onto my Android 4.0 emulator?...

Saving timestamp in mysql table using php

I have a field in a MySQL table which has a timestamp data type. I am saving data into that table. But when I pass the timestamp (1299762201428) to the record, it automatically saves the value 0000-00-00 00:00:00 into that table. How can I store the...

Error:Failed to open zip file. Gradle's dependency cache may be corrupt

I updated android studio 2.3 and there is a bug, gradle doesn't build and it keeps giving me the same error for all projects. Error:Failed to open zip file. Gradle's dependency cache may be corrupt (this sometimes occurs after a network connection ...

Centering Bootstrap input fields

I am new with this, especially with Bootstrap. I have this code: <div class="row"> <div class="col-lg-3"> <div class="input-group"> <input type="text" class="form-control"> <span class="input-g...

Recommended SQL database design for tags or tagging

I've heard of a few ways to implement tagging; using a mapping table between TagID and ItemID (makes sense to me, but does it scale?), adding a fixed number of possible TagID columns to ItemID (seems like a bad idea), Keeping tags in a text column th...

Regex: ignore case sensitivity

How can I make the following regex ignore case sensitivity? It should match all the correct characters but ignore whether they are lower or uppercase. G[a-b].* ...

How to add external fonts to android application

I was looking for some stylish fonts for my android application. but the problem is how can i make my android application supportable for external fonts. Thank you....

Change header text of columns in a GridView

I have a GridView which i programmatically bind using c# code. The problem is, the columns get their header texts directly from Database, which can look odd when presented on websites. So basically, i would like to modify the column header text, but ...

How to detect the end of loading of UITableView

I want to change the offset of the table when the load is finished and that offset depends on the number of cells loaded on the table. Is it anyway on the SDK to know when a uitableview loading has finished? I see nothing neither on delegate nor on...

How do I fix the error 'Named Pipes Provider, error 40 - Could not open a connection to' SQL Server'?

I can't seem to connect to my database from a site. I get this error: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server I tried using the local IP address to connect as well as a public one. I've tried: Yes, the site...

Generate UML Class Diagram from Java Project

Is there a good tool that can help to reverse engineer Java classes to UML that will show an overview of how my classes are related to each other? It doesn't need to decompile from JAR file because I have the sources. I know there are quite a few out...

Can you split a stream into two streams?

I have a data set represented by a Java 8 stream: Stream<T> stream = ...; I can see how to filter it to get a random subset - for example Random r = new Random(); PrimitiveIterator.OfInt coin = r.ints(0, 2).iterator(); Stream<T> he...

Flutter Circle Design

I want to make this kind of design with these white circles as a raised button....

How to subtract date/time in JavaScript?

I have a field at a grid containing date/time and I need to know the difference between that and the current date/time. What could be the best way of doing so? The dates are stored like "2011-02-07 15:13:06"....

HTML img align="middle" doesn't align an image

I want a image to be centered aligned. Image size is fixed in pixels. So what I want is like this- . What I have done is- <!DOCTYPE html> <html> <body> <img src="http://icons.iconarchive.com/icons/rokey/p...

How to push elements in JSON from javascript array

I want to add javascript array values into JSON values object. The other element is also replaced my element like recipients, subject, message. I got Json like: Below is my code. var BODY = { "recipients": { "values": [ ] }, ...

What is the C++ function to raise a number to a power?

How do I raise a number to a power? 2^1 2^2 2^3 etc......

The remote host closed the connection. The error code is 0x800704CD

I receive error emails from my website whenever an exception occurs. I am getting this error: The remote host closed the connection. The error code is 0x800704CD and don't know why. I get about 30 a day. I can't reproduce the error either so ca...

Difference between Groovy Binary and Source release?

i have been seeing the words binary and source release in many websites download sections. What do they actually mean? For example, I have seen this in Groovy download page. My question is how they differ? Both tend to install Groovy, but what...

How does Content Security Policy (CSP) work?

I'm getting a bunch of errors in the developer console: Refused to evaluate a string Refused to execute inline script because it violates the following Content Security Policy directive Refused to load the script Refused to load the stylesheet What...

How to get resources directory path programmatically

I have the following directory layout: src main java resources sql (scripts for database) spring (configuration) webapp Within a ServletContextListener class, I want to access the files under the SQL direc...

Gradle: How to Display Test Results in the Console in Real Time?

I would like to see test results ( system.out/err, log messages from components being tested ) as they run in the same console I run: gradle test And not wait until tests are done to look at the test reports ( that are only generated when tests ar...

_DEBUG vs NDEBUG

Which preprocessor define should be used to specify debug sections of code? Use #ifdef _DEBUG or #ifndef NDEBUG or is there a better way to do it, e.g. #define MY_DEBUG? I think _DEBUG is Visual Studio specific, is NDEBUG standard?...

Move a view up only when the keyboard covers an input field

I am trying to build an input screen for the iPhone. The screen has a number of input fields. Most of them on the top of the screen, but two fields are at the bottom. When the user tries to edit the text on the bottom of the screen, the keyboard wil...

Pandas dataframe fillna() only some columns in place

I am trying to fill none values in a Pandas dataframe with 0's for only some subset of columns. When I do: import pandas as pd df = pd.DataFrame(data={'a':[1,2,3,None],'b':[4,5,None,6],'c':[None,None,7,8]}) print df df.fillna(value=0, inplace=True)...

Disable all table constraints in Oracle

How can I disable all table constrains in Oracle with a single command? This can be either for a single table, a list of tables, or for all tables....

Multiple radio button groups in MVC 4 Razor

I need to have multiple radio button groups in my form like this: I know it's simply done by specifying the same "name" html attribute for each group. HOWEVER MVC doesn't let you specify your own name attribute when using html helper like this: ...

How to hide form code from view code/inspect element browser?

I want to hide form code from view code/inspect element browser , how can i do that ? This is my code, please see below: <div style=" text-align: center; padding: 300px; font-family: lato; "> Please wait redirect page ......<br> ...

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?...

Multiple radio button groups in one form

Is it possible to have multiple radio button groups in a single form? Usually selecting one button deselects the previous, I just need to have one of a group deselected. <form> <fieldset id="group1"> <input type="radio" va...

Pandas merge two dataframes with different columns

I'm surely missing something simple here. Trying to merge two dataframes in pandas that have mostly the same column names, but the right dataframe has some columns that the left doesn't have, and vice versa. >df_may id quantity attr_1 attr...

Why does instanceof return false for some literals?

"foo" instanceof String //=> false "foo" instanceof Object //=> false true instanceof Boolean //=> false true instanceof Object //=> false false instanceof Boolean //=> false false instanceof Object //=> false ...

import httplib ImportError: No module named httplib

I got this error when run test.py C:\Python32>python.exe test.py Traceback (most recent call last): File "test.py", line 5, in <module> import httplib ImportError: No module named httplib How to correct it? Code block for test.py: ...

How do I get the base URL with PHP?

I am using XAMPP on Windows Vista. In my development, I have http://127.0.0.1/test_website/. How do I get http://127.0.0.1/test_website/ with PHP? I tried something like these, but none of them worked. echo dirname(__FILE__) or echo basename(...

How to call a button click event from another method

How can I call SubGraphButton_Click(object sender, RoutedEventArgs args) from another method? private void SubGraphButton_Click(object sender, RoutedEventArgs args) { } private void ChildNode_Click(object sender, RoutedEventArgs args) { // call...

Method with a bool return

I was making a method with a bool return value and I had a problem: This works private bool CheckAll() { //Do stuff return true; } But this dosn't, the method can't detect a return value if it's in a IF-statement. private bool CheckAll() { ...

Exporting to .xlsx using Microsoft.Office.Interop.Excel SaveAs Error

I am in the process of writing a module to export a DataTable to Excel using Microsoft.Office.Interop.Excel but before starting in earnest I want to get the very basics working: open file, save as, and close. I have succeeded in opening and saving a...

Using a remote repository with non-standard port

I am setting up my local git project for a remote repository. The remote repository is being served on a non-standard port (4019). But it doesn't work. Instead I get the following error message: ssh: connect to host git.host.de:4019 port 22: Connec...

Android: How do I prevent the soft keyboard from pushing my view up?

I have a vertical sliding drawer at the bottom of my app. When the soft keyboard opens, it pushes the tab for the drawer up, so it sits atop the keyboard. I actually want it to remain at the bottom of the screen, becoming hidden when the keyboard is ...

How to use Switch in SQL Server

I want to use CASE in my stored procedure. I am getting some syntax error in my code: select case @Temp when 1 then (@selectoneCount=@selectoneCount+1) when 2 then (@selectoneCount=@selectoneCount+1) end When running, I'm getting: ...

What does 'killed' mean when a processing of a huge CSV with Python, which suddenly stops?

I have a Python script that imports a large CSV file and then counts the number of occurrences of each word in the file, then exports the counts to another CSV file. But what is happening is that once that counting part is finished and the exporting...

Setting dynamic scope variables in AngularJs - scope.<some_string>

I have a string I have gotten from a routeParam or a directive attribute or whatever, and I want to create a variable on the scope based on this. So: $scope.<the_string> = "something". However, if the string contains one or more dots I want...

Calling a function from a string in C#

I know in php you are able to make a call like: $function_name = 'hello'; $function_name(); function hello() { echo 'hello'; } Is this possible in .Net?...

Running a cron every 30 seconds

Ok so I have a cron that I need to run every 30 seconds. Here is what I have: */30 * * * * /bin/bash -l -c 'cd /srv/last_song/releases/20120308133159 && script/rails runner -e production '\''Song.insert_latest'\''' It runs, but is this ru...

Automated way to convert XML files to SQL database?

We have a bunch of XML files, following a schema which is essentially a serialised database form: <table1> <column1>value</column1> <column2>value</column2> </table1> <table1> <column1>another...

Regex for parsing directory and filename

I'm trying to write a regex that will parse out the directory and filename of a fully qualified path using matching groups. so... /var/log/xyz/10032008.log would recognize group 1 to be "/var/log/xyz" and group 2 to be "10032008.log" Seems simpl...

Create HTML table using Javascript

My question will ultimately be related to this site: http://dbtest.net16.net/ethanol-01.html EDIT: View unencrypted page source code here >>> http://dbtest.net16.net/ethanol-22.html This is an HTML form with results calculated using JavaScript. M...

Set auto height and width in CSS/HTML for different screen sizes

I have 2 issues with this layout : .feature_content (grey background) adapt it's height and width to different screen sizes. Right now, on big screens .feature_content is far from the footer. There is a horizontal scrollbar that I want to remove re...

Is there a cross-browser onload event when clicking the back button?

For all major browsers (except IE), the JavaScript onload event doesn’t fire when the page loads as a result of a back button operation — it only fires when the page is first loaded. Can someone point me at some sample cross-browser code (Firefo...

Android Spinner : Avoid onItemSelected calls during initialization

I created an Android application with a Spinner and a TextView. I want to display the selected item from the Spinner's drop down list in the TextView. I implemented the Spinner in the onCreate method so when I'm running the program, it shows a value ...

PHP & localStorage;

I've searched around for use of localStorage in PHP, as I need to get localStorage data as a $var, in PHP and do stuff in PHP with it. Is this possible? P.S. If anybody knows any good HTML5 resources, other than what can be easily found on Google, p...

how to setup ssh keys for jenkins to publish via ssh

Jenkins requires a certificate to use the ssh publication and ssh commands. It can be configured under "manage jenkins" -> "Configure System"-> "publish over ssh". The question is: How does one create the certificates? I have two ubuntu serve...

If greater than batch files

I wrote a simple batch file to run Frequently Used websites based on a number selection. Here's the code I have. I am trying to set it so if someone inputs a number 6 or greater it will go to :N but whenever I type 6 the batch file exits. I have trie...

Check string for nil & empty

Is there a way to check strings for nil and "" in Swift? In Rails, I can use blank() to check. I currently have this, but it seems overkill: if stringA? != nil { if !stringA!.isEmpty { ...blah blah } } ...

JQuery: How to get selected radio button value?

How do I default the value of a non-selected radio button to 0? I have the following HTML: <input type="radio" name="myradiobutton" value="1" />1 <input type="radio" name="myradiobutton" value="2" />2 <input type="radio" name="myradi...

How to import keras from tf.keras in Tensorflow?

import tensorflow as tf import tensorflow from tensorflow import keras from keras.layers import Dense I am getting the below error from keras.layers import Input, Dense Traceback (most recent call last): File "<ipython-input-6-b5da44e251a5...

How to import component into another root component in Angular 2

I am trying to import component from one file another root component file. it give error as .. zone.js:484 Unhandled Promise rejection: Template parse errors: 'courses' is not a known element: 1. If 'courses' is an Angular component, then ver...

What is the difference between a symbolic link and a hard link?

Recently I was asked this during a job interview. I was honest and said I knew how a symbolic link behaves and how to create one, but do not understand the use of a hard link and how it differs from a symbolic one....

Apache SSL Configuration Error (SSL Connection Error)

I'm trying to configure Apache on my server to work with ssl, but everytime I visit my site, I get the following message in my browser: SSL connection error. Unable to make a secure connection to the server. This may be a problem with the server, or...

Java Security: Illegal key size or default parameters?

I had asked a question about this earlier, but it didn't get answered right and led nowhere. So I've clarified few details on the problem and I would really like to hear your ideas on how could I fix this or what should I try. I have Java 1.6.0.12...

How do I add to the Windows PATH variable using setx? Having weird problems

I want to modify the Windows PATH variable using setx. The following works at least 50% of the time on Windows 8: setx PATH %PATH%;C:\Python27\;C:\Python27\Scripts\ If it gives the error "the default argument can only be used 2 times", then the fo...

Convert Rows to columns using 'Pivot' in SQL Server

I have read the stuff on MS pivot tables and I am still having problems getting this correct. I have a temp table that is being created, we will say that column 1 is a Store number, and column 2 is a week number and lastly column 3 is a total of som...

How to set Navigation Drawer to be opened from right to left

First of all I know this question appeared here before but after trying a lot I still didn't succeed. I working on the example from Android Developers site. I'm trying to set the menu to be opened from right to left instead of how its implementing ...

Frequency table for a single variable

One last newbie pandas question for the day: How do I generate a table for a single Series? For example: my_series = pandas.Series([1,2,2,3,3,3]) pandas.magical_frequency_function( my_series ) >> { 1 : 1, 2 : 2, 3 : 3 } ...

Cross-browser bookmark/add to favorites JavaScript

Is there any cross-browser bookmark/add to favorites using JavaScript. Searched for some list but none is working. Can you please suggest any?...

Android: Go back to previous activity

I want to do something simple on android app. How is it possible to go back to a previous activity. What code do I need to go back to previous activity...

Add primary key to existing table

I have an existing table called Persion. In this table I have 5 columns: persionId Pname PMid Pdescription Pamt When I created this table, I set PersionId and Pname as the primary key. I now want to include one more column in the primary key - ...

clk'event vs rising_edge()

I had always used this for detecting a rising edge: if (clk'event and clk='1') then but this can also be used: if rising_edge(clk) then Reading this post, rising_edge(clk) is recommended, but there is also a comment indicating that rising_edge(cl...

How to find good looking font color if background color is known?

There seem to be so many color wheel, color picker, and color matcher web apps out there, where you give one color and the they'll find a couple of other colors that will create a harmonic layout when being used in combination. However most of them f...

How do I get this javascript to run every second?

How do I get this javascript to run every second? source code: <script type="text/javascript"> $(function() { //More Button $('.more').live("click",function() { var ID = $(this).attr("id"); ...

Passing parameters to click() & bind() event in jquery?

I want to pass few parameters to Click() event in jquery, I tried following but its not working, commentbtn.click(function(id, name){ alert(id); }); And also if we use bind then how we'll do that commentbtn.bind('click', function(id, name){ ...

How to fill a datatable with List<T>

How can convert a list to a datatable [Serializable] public class Item { public string Name { get; set; } public double Price { get; set; } public string @URL { get; set; } public Item(string Name, string Price, string @URL) { ...

How to Correctly handle Weak Self in Swift Blocks with Arguments

In my TextViewTableViewCell, I have a variable to keep track of a block and a configure method where the block is passed in and assigned. Here is my TextViewTableViewCell class: // // TextViewTableViewCell.swift // import UIKit class TextViewTab...

Downgrade npm to an older version

I tried updating npm to see if it would solve some dependency problems we were having, and now I want to downgrade to the version the rest of the development team is using. How can I install an older version? I updated npm according to the instructio...

How to embed a YouTube channel into a webpage

Can anyone suggest how I embed a youtube channel into a webpage - I am getting conflicting information from various sites, ideally using the custom player if possible? thanks...

App crashing when trying to use RecyclerView on android 5.0

I'm trying to mess with the new RecyclerView and whenever I try to run it, my app immediately crashes. It gives me NullPointerException for trying to access methods from android.support.v7.widget.RecyclerView. I've looked at other posts and saw that ...

java: use StringBuilder to insert at the beginning

I could only do this with String, for example: String str=""; for(int i=0;i<100;i++){ str=i+str; } Is there a way to achieve this with StringBuilder? Thanks....

Creating all possible k combinations of n items in C++

There are n people numbered from 1 to n. I have to write a code which produces and print all different combinations of k people from these n. Please explain the algorithm used for that. ...

How to compare strings in Bash

How do I compare a variable to a string (and do something if they match)?...

Multiple REPLACE function in Oracle

I am using the REPLACE function in oracle to replace values in my string like; SELECT REPLACE('THE NEW VALUE IS #VAL1#','#VAL1#','55') from dual So this is OK to replace one value, but what about 20+, should I use 20+ REPLACE function or is there...

Jquery checking success of ajax post

how do i define the success and failure function of an ajax $.post?...

Hiding an Excel worksheet with VBA

I have an Excel spreadsheet with three sheets. One of the sheets contains formulas for one of the other sheets. Is there a programmatic way to hide the sheet which contains these formulas?...

int *array = new int[n]; what is this function actually doing?

I am confused about how to create a dynamic defined array: int *array = new int[n]; I have no idea what this is doing. I can tell it's creating a pointer named array that's pointing to a new object/array int? Would someone care to explain?...

jinja2.exceptions.TemplateNotFound error

i use flask and i got this error when i call this url: /login Here's my login method: @app.route('/login') def login(): if authenticateForPanel(): return redirect(url_for("panel")) else: getParam = request.args.getlist('redi...

Disabling swap files creation in vim

Is there a way to disable .swp files creation in vim? or at least create them all in one place so I can find and delete them easily. I find them especially annoying when I copy the parent directory while editing at the same time. Of course I know th...

Excel formula to get week number in month (having Monday)

Using excel formula I need to get week number in month from a given date. But, the condition is it should have Monday in it. Monday through Sunday is the work days. I have tried this: But, week number is given as 5, where as it should be 4 becaus...

Linux - Install redis-cli only

I have a Linux server with Redis installed and I want to connect to it via command line from my local Linux machine. Is it possible to install redis-cli only (without redis-server and other tools)? If I just copy redis-cli file to my local machine ...

How do I get the current mouse screen coordinates in WPF?

How to get current mouse coordination on the screen? I know only Mouse.GetPosition() which get mousePosition of element, but I want to get the coordination without using element....

incompatible character encodings: ASCII-8BIT and UTF-8

I use Ruby 1.9.2 and Rails 3.0.5 I have the following error: incompatible character encodings: ASCII-8BIT and UTF-8 It has nothing to do with the database i think. The error is happinging on this line in a view (just a div haml call): #conte...

what is the difference between GROUP BY and ORDER BY in sql

When do you use which in general? Examples are highly encouraged! I am referring so MySql, but can't imagine the concept being different on another DBMS...

How to use awk sort by column 3

I have a file (user.csv)like this ip,hostname,user,group,encryption,aduser,adattr want to print all column sort by user, I tried awk -F ":" '{print|"$3 sort -n"}' user.csv , it doesn't work....

Xcode doesn't see my iOS device but iTunes does

I have a strange problem. I have an iPad with iOS 5.0.1 (9A405) and iOS SDK 5.0.1 with Xcode 4.2 (Build 4C199) installed on my Mac. Xcode doesn't see my device. It says "iOS Device" not "Sauron's iPad" as usual. (I am sure that device is connected ...

Pandas/Python: Set value of one column based on value in another column

I need to set the value of one column based on the value of another in a Pandas dataframe. This is the logic: if df['c1'] == 'Value': df['c2'] = 10 else: df['c2'] = df['c3'] I am unable to get this to do what I want, which is to simply cre...

Difference in days between two dates in Java?

I need to find the number of days between two dates: one is from a report and one is the current date. My snippet: int age=calculateDifference(agingDate, today); Here calculateDifference is a private method, agingDate and today are Date objects,...

Getting String Value from Json Object Android

I am beginner in Android. In my Project, I am getting the Following json from the HTTP Response. [{"Date":"2012-1-4T00:00:00", "keywords":null, "NeededString":"this is the sample string I am needed for my project", "others":"not needed"}] I want t...

Android Studio - Failed to notify project evaluation listener error

Following is the build.gradle code in Android Studio apply plugin: 'com.android.application' android { compileSdkVersion 23 buildToolsVersion "23.0.2" defaultConfig { applicationId "com.sg.blahblah" minSdkVersion 15 ...

Convert Iterator to ArrayList

Given Iterator<Element>, how can we convert that Iterator to ArrayList<Element> (or List<Element>) in the best and fastest way possible, so that we can use ArrayList's operations on it such as get(index), add(element), etc....

Running a cron job at 2:30 AM everyday

How to configure a cron job to run every night at 2:30? I know how to make it run at 2, but not 2:30....

Is it possible to see more than 65536 rows in Excel 2007?

I have an excel file which has more than 65536 rows. However, I can see only first 65536 of them. Is it possible to see all of them in Excel 2007?...

How to use LogonUser properly to impersonate domain user from workgroup client

ASP.NET: Impersonate against a domain on VMWare This question is what I am asking, but the answer does not provide details on how the _token is derived. It seems to only use WindowsIdentity.GetCurrent().Token so there's no impersonation happening. ...

Trying to include a library, but keep getting 'undefined reference to' messages

I am attempting to use the libtommath library. I'm using the NetBeans IDE for my project on Ubuntu linux. I have downloaded and built the library, I have done a 'make install' to put the resulting .a file into /usr/lib/ and the .h files into /usr/inc...

Turn off constraints temporarily (MS SQL)

I'm looking for a way to temporarily turn off all DB's constraints (eg table relationships). I need to copy (using INSERTs) one DB's tables to another DB. I know I can achieve that by executing commands in proper order (to not break relationships). ...

You have to be inside an angular-cli project in order to use the build command after reinstall of angular-cli

I had the latest angular-cli installed globally and my project was building successfully. While reading a suggested solution for another issue, (https://github.com/angular/angular-cli/issues/917) I uninstalled the global angular-cli and installed...

Cannot install packages inside docker Ubuntu image

I installed Ubuntu 14.04 image on docker. After that, when I try to install packages inside the ubuntu image, I'm getting unable to locate package error: apt-get install curl Reading package lists... Done Building dependency tree Reading st...

How to use new PasswordEncoder from Spring Security

As of Spring Security 3.1.4.RELEASE, the old org.springframework.security.authentication.encoding.PasswordEncoder has been deprecated in favour of org.springframework.security.crypto.password.PasswordEncoder. As my application has not been released t...

Use jQuery to change value of a label

I have a label, costLabel. What I want to be able to do is change the value of this label depending on the selected value of a dropdownlist. This is my HTML: <table> <tr> <td width="343">Package*</td> <td col...

How to convert a String to a Date using SimpleDateFormat?

I have this code snippet: DateFormat formatter1; formatter1 = new SimpleDateFormat("mm/DD/yyyy"); System.out.println((Date)formatter1.parse("08/16/2011")); When I run this, I get this as the output: Sun Jan 16 00:10:00 IST 2011 I expected: Tue...

What's the difference between a Future and a Promise?

What's the difference between Future and Promise? They both act like a placeholder for future results, but where is the main difference?...

Eclipse keyboard shortcut to indent source code to the left?

I've looked in the keyboard shortcuts list in Eclipse but can't find keyboard shortcut to indent source code to the left. Surely there is one?...

Warning: require_once(): http:// wrapper is disabled in the server configuration by allow_url_include=0

I am trying to include a php file in a page via require_once(http://localhost/web/a.php) I am getting an error Warning: require_once(): http:// wrapper is disabled in the server configuration by allow_url_include=0 I changed allow_url_inc...

jQuery.ajax handling continue responses: "success:" vs ".done"?

I have been working with jQuery and AJAX for a few weeks now and I saw two different ways to 'continue' the script once the call has been made: success: and .done. From the synopsis from the jQuery documentation we get: .done(): Description: Add han...

How can I format date by locale in Java?

I need to format date to app that has many languages, what is best way to format date, because every country has different kind of date formatting, so is it possible to format date by locale?...

Meaning of 'const' last in a function declaration of a class?

What is the meaning of const in declarations like these? The const confuses me. class foobar { public: operator int () const; const char* foo() const; }; ...

How to pass form input value to php function

I want to write a php page in which there is a html form. I want to send all input (number for example) of my form to a php function (instead of a javascript function; I make this to hide my javascript function code). How can I send input value to...

Hidden features of Windows batch files

What are some of the lesser know, but important and useful features of Windows batch files? Guidelines: One feature per answer Give both a short description of the feature and an example, not just a link to documentation Limit answers to native fu...

Jquery: how to sleep or delay?

i want move up the object, delay 1000ms , then hide it, i get the code: $("#test").animate({"top":"-=80px"},1500) .animate({"top":"-=0px"},1000) .animate({"opacity":"0"},500); i use ".animate({"top":"-=0px"},1000)" to implement delay,...

Catching FULL exception message

Consider: Invoke-WebRequest $sumoApiURL -Headers @{"Content-Type"= "application/json"} -Credential $cred -WebSession $webRequestSession -Method post -Body $sumojson -ErrorAction Stop This throws the following exception: How can I catch it entir...

Fully backup a git repo?

Is there a simple way to backup an entire git repo including all branches and tags?...

"ArrayAdapter requires the resource ID to be a TextView" xml problems

I am getting an error when trying to set my view to display the ListView for the file I want to display(text file). I am pretty sure it has something to do with the xml. I just want to display the information from this.file = fileop.ReadFileAsList("I...

PHP - Redirect and send data via POST

I have an online gateway which requires an HTML form to be submitted with hidden fields. I need to do this via a PHP script without any HTML forms (I have the data for the hidden fields in a DB) To do this sending data via GET: header('Location: ht...

Setting user agent of a java URLConnection

I'm trying to parse a webpage using Java with URLConnection. I try to set up the user-agent like this: java.net.URLConnection c = url.openConnection(); c.setRequestProperty("User-Agent", "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.4; en-US; rv:1.9...

Test if numpy array contains only zeros

We initialize a numpy array with zeros as bellow: np.zeros((N,N+1)) But how do we check whether all elements in a given n*n numpy array matrix is zero. The method just need to return a True if all the values are indeed zero....

How to call URL action in MVC with javascript function?

I´m trying to render url action with javascript in an MVC project. I capture an event on my page which calls this function but I´m not sure how to call this certain URL. Can anyone help me please? :) function onDropDownChange(e) { var url =...

npm ERR! registry error parsing json - While trying to install Cordova for Ionic Framework in Windows 8

I was trying to instal Ionic framework in my Windows 8 system and was trying to install Cordova first. I'm getting this error while trying to install Cordova, that says Your environment has been set up for using Node.js 0.12.4 (x64) and npm. C:\U...

Jquery button click() function is not working

I am trying to create dynamic form where user can add dynamic text-fields based on their requirement. Here is my jquery code .. $(document).ready(function() { $("#add").click(function() { var intId = $("#buildyourform div").length +1; ...

Calculate the date yesterday in JavaScript

How can I calculate yesterday as a date in JavaScript?...

React Native Border Radius with background color

In React Native, borderRadius is working but the background color given to the button stays a square. What is going on here? JS <TouchableHighlight style={styles.submit} onPress={() => this.submitSuggestion(this.props)} underlayColor='#...

CSS selector for first element with class

I have a bunch of elements with a class name red, but I can't seem to select the first element with the class="red" using the following CSS rule: _x000D_ _x000D_ .red:first-child {_x000D_ border: 5px solid red;_x000D_ }_x000D_ <p class="red"&...

Pandas: sum DataFrame rows for given columns

I have the following DataFrame: In [1]: import pandas as pd df = pd.DataFrame({'a': [1,2,3], 'b': [2,3,4], 'c':['dd','ee','ff'], 'd':[5,9,1]}) df Out [1]: a b c d 0 1 2 dd 5 1 2 3 ee 9 2 3 4 ff 1 I would like to add a column 'e...

Could not install packages due to an EnvironmentError: [WinError 5] Access is denied:

I have windows 10. I have completed installing Tensorflow. It works. It says "Hello Tensorflow!". But it has all of this before it: 2018-08-18 18:16:01.500579: I T:\src\github\tensorflow\tensorflow\core\platform\cpu_feature_guard.cc:141] Yo...

How to delete files recursively from an S3 bucket

I have the following folder structure in S3. Is there a way to recursively remove all files under a certain folder (say foo/bar1 or foo or foo/bar2/1 ..) foo/bar1/1/.. foo/bar1/2/.. foo/bar1/3/.. foo/bar2/1/.. foo/bar2/2/.. foo/bar2/3/.. ...

Open URL in new window with JavaScript

I'm making a "share button" to share the current page. I would like to take the current page URL and open it in a new window. I have the current URL part working, but can't seem to get the next part working. I'm struggling with the syntax. I would ...

What is the significance of load factor in HashMap?

HashMap has two important properties: size and load factor. I went through the Java documentation and it says 0.75f is the initial load factor. But I can't find the actual use of it. Can someone describe what are the different scenarios where we ne...

Spring MVC Missing URI template variable

I have a Controller class with a function that saves a record to the Database. I am passing several parameters to the Controller function however i think i may be writing the @RequestMapping incorrectly. Under is the code Controller @RequestMappin...

ERROR: Google Maps API error: MissingKeyMapError

The following JavaScript error suddenly appeared: Google Maps API error: Google Maps API error: MissingKeyMapError ...

Python - Move and overwrite files and folders

I have a directory, 'Dst Directory', which has files and folders in it and I have 'src Directory' which also has files and folders in it. What I want to do is move the contents of 'src Directory' to 'Dst Directory' and overwrite anyfiles that exist w...

Javascript .querySelector find <div> by innerTEXT

How can I find DIV with certain text? For example: <div> SomeText, text continues. </div> Trying to use something like this: var text = document.querySelector('div[SomeText*]').innerTEXT; alert(text); But ofcourse it will not work. ...

Initializing entire 2D array with one value

With the following declaration int array[ROW][COLUMN]={0}; I get the array with all zeroes but with the following one int array[ROW][COLUMN]={1}; I don’t get the array with all one value. The default value is still 0. Why this behavior and ...

Get root view from current activity

I know how to get the root view with View.getRootView(). I am also able to get the view from a button's onClick event where the argument is a View. But how can I get the view in an activity?...

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 anything. Is there a tool like this to create a file wit...

MySQL SELECT LIKE or REGEXP to match multiple words in one record

The field table.name contains 'Stylus Photo 2100' and with the following query SELECT `name` FROM `table` WHERE `name` LIKE '%Stylus 2100%' I get no results. Of course i would if i searched SELECT `name` FROM `table` WHERE `name` LIKE '%Photo 210...

Which icon sizes should my Windows application's icon include?

I have a Windows application which will run in Windows XP and newer (i.e. Vista/7). According to the Vista UI Guidelines, the standard sizes are 16x16, 32x32, 48x48, 256x256 (XP standard sizes do not include the 256x256 icon). In addition to those si...

Amazon S3 exception: "The specified key does not exist"

I am using the AmazonS3Client in an Android app using a getObject request to download an image from my Amazon S3 bucket. Currently, I am getting this exception: com.amazonaws.services.s3.model.AmazonS3Exception: The specified key does not exist. ...

Remove part of string in Java

I want to remove a part of string from one character, that is: Source string: manchester united (with nice players) Target string: manchester united ...

Wheel file installation

How do I install a .whl file? I have the Wheel library but I don't know how to use it to install those files. I have the .whl file but I don't know how to run it. Please help....

Global variables in header file

I have a 2 modules (.c files) and one .h header file: file1.c: #include <stdio.h> #include "global.h" int main() { i = 100; printf("%d\n",i); foo(); return 0; } file2.c #include <stdio.h> #include "global.h" void fo...

Absolute vs relative URLs

I would like to know the differences between these two types of URLs: relative URLs (for pictures, CSS files, JS files, etc.) and absolute URLs. In addition, which one is better to use?...

Android java.lang.NoClassDefFoundError

I have an Android project in eclipse IDE which was working. After some imports and tests, I get the error: java.lang.NoClassDefFoundError. In my project I have two packages: the main one and the second one with some classes. When I try to instanti...

array_push() with key value pair

I have an existing array to which I want to add a value. I'm trying to achieve that using array_push() to no avail. Below is my code: $data = array( "dog" => "cat" ); array_push($data['cat'], 'wagon'); What I want to achieve is to add ca...

Will iOS launch my app into the background if it was force-quit by the user?

I am triggering a background fetch by using the content-available flag on a push notification. I have the fetch and remote-notification UIBackgroundModes enabled. Here is the implementation I am using in my AppDelegate.m: - (void)application:(UIApp...

Styling Google Maps InfoWindow

I've been attempting to style my Google Maps InfoWindow, but the documentation is very limited on this topic. How do you style an InfoWindow?...

Downcasting in Java

Upcasting is allowed in Java, however downcasting gives a compile error. The compile error can be removed by adding a cast but would anyway break at the runtime. In this case why Java allows downcasting if it cannot be executed at the runtime? Is...

Convert a numpy.ndarray to string(or bytes) and convert it back to numpy.ndarray

I'm having a little trouble here, I'm trying to convert a numpy.ndarray to string, I've already done that like this: randomArray.tostring() It works, but I'm wondering if I can transform it back to a numpy.ndarray. What's the best way to do this...

How can I perform static code analysis in PHP?

Is there a static analysis tool for PHP source files? The binary itself can check for syntax errors, but I'm looking for something that does more, like: unused variable assignments arrays that are assigned into without being initialized first and po...

Calculating powers of integers

Is there any other way in Java to calculate a power of an integer? I use Math.pow(a, b) now, but it returns a double, and that is usually a lot of work, and looks less clean when you just want to use ints (a power will then also always result in an ...

MAVEN_HOME, MVN_HOME or M2_HOME

What's the correct Maven environment variable name: MAVEN_HOME, MVN_HOME or M2_HOME? I've found some details about MAVEN_HOME and M2_HOME here. But I also have seen MVN_HOME around....

Constraint Layout Vertical Align Center

How to vertically align and center objects in constraint layout? It is possible to align vertically or horizontally but I have not found a way to center at the same time beside constraining the views between two gridlines. Vertical Align Center: ...

Entitlements file do not match those specified in your provisioning profile.(0xE8008016)

The executable was signed with invalid entitlements. The entitlements specified in your application’s Code Signing Entitlements file do not match those specified in your provisioning profile.(0xE8008016). I am getting this error. please help me. I ...

Windows Bat file optional argument parsing

I need my bat file to accept multiple optional named arguments. mycmd.bat man1 man2 -username alice -otheroption For example my command has 2 mandatory parameters, and two optional parameters (-username) that has an argument value of alice, and -o...

CALL command vs. START with /WAIT option

How is the START command with a WAIT option START /wait notepad.exe START /wait notepad.exe ...any different from using a CALL command? CALL notepad.exe CALL notepad.exe Is there a situation where one may behave differently that the other...

List rows after specific date

I have a column in my database called "dob" of type datetime. How do I select all the rows after a specific DoB in SQL Server 2005?...

Magento - How to add/remove links on my account navigation?

I am trying to remove links on my account navigation. I looked at the customer/account/navigation.phtml template. The template grabs links by $this->getLinks(). How do I edit getLinks() method so that I can remove some of links?...

Does HTML5 <video> playback support the .avi format?

I am wondering if the HTML5 <video> tag now supports playback of .avi format video files....

How to check the version of GitLab?

How to check which version of GitLab is installed on the server? I am about version specified in GitLab changelog: https://gitlab.com/gitlab-org/gitlab-foss/blob/master/CHANGELOG.md For example: "6.5.0", "6.4.3", etc. ?an this be done only thro...

Private pages for a private Github repo

Couldn't find anything in the github documentation and also here on SO. But I was wondering if there could be a http://foo.github.com for a private repository named foo which is accessible only one had access to the foo repository itself. I remember...

How to fix nginx throws 400 bad request headers on any header testing tools?

I have my site which is using nginx, and testing site with header testing tools e.g. http://www.webconfs.com/http-header-check.php but every time it says 400 bad request below is the out put from the tool. Though all my pages load perfectly fine in b...

Introducing FOREIGN KEY constraint may cause cycles or multiple cascade paths - why?

I've been wrestling with this for a while and can't quite figure out what's happening. I have a Card entity which contains Sides (usually 2) - and both Cards and Sides have a Stage. I'm using EF Codefirst migrations and the migrations are failing w...

pandas resample documentation

So I completely understand how to use resample, but the documentation does not do a good job explaining the options. So most options in the resample function are pretty straight forward except for these two: rule : the offset string or object repr...

Find TODO tags in Eclipse

When I used Eclipse to add unimplemented methods to a Java class to fix an error, methods were auto-generated and include // TODO Auto-generated method stub Is there an easy way to view all methods which contain this comment? Some sort of menu optio...

How can I write output from a unit test?

Any call in my unit tests to either Debug.Write(line) or Console.Write(Line) simply gets skipped over while debugging and the output is never printed. Calls to these functions from within classes I'm using work fine. I understand that unit testing is...

Restful API service

I'm looking to make a service which I can use to make calls to a web-based REST API. Basically I want to start a service on app init then I want to be able to ask that service to request a url and return the results. In the meantime I want to be ab...

How to upsert (update or insert) in SQL Server 2005

I have table in which I am inserting rows for employee but next time when I want to insert row I don't want to insert again data for that employee just want to update with required columns if it exits there if not then create new row How can we do t...

Most pythonic way to delete a file which may not exist

I want to delete the file filename if it exists. Is it proper to say if os.path.exists(filename): os.remove(filename) Is there a better way? A one-line way? ...

How do I make a semi transparent background?

I need to make a white background 50% transparent without affecting anything else. How do I do it?...

How to use the ConfigurationManager.AppSettings

I've never used the "appSettings" before. How do you configure this in C# to use with a SqlConnection, this is what I use for the "ConnectionStrings" SqlConnection con = new SqlConnection(); con.ConnectionString = ConfigurationManager.ConnectionStri...

How can I read user input from the console?

I want to get a number from the user, and then multiply that number with Pi. my attempt at this is below. But a contains gibberish. For example, if I insert 22, then a contains 50. What am I doing wrong? I don't get any compiler errors. double a,b; ...

How to use global variables in React Native?

In React Native I want to use global variables when I am moving between different screens Can anyone help me how to achieve it?...

How to Get enum item name from its value

I declared a enum type as this, enum WeekEnum { Mon = 0; Tue = 1; Wed = 2; Thu = 3; Fri = 4; Sat = 5; Sun = 6; }; How can I get the item name "Mon, Tue, etc" when I already have the item value "0, 1, etc." I already have a function as this Log(T...

Checking for duplicate strings in JavaScript array

I have JS array with strings, for example: var strArray = [ "q", "w", "w", "e", "i", "u", "r"]; I need to compare for duplicate strings inside array, and if duplicate string exists, there should be alert box pointing to that string. I was trying t...

Connection reset by peer: mod_fcgid: error reading data from FastCGI server

I am having issue on PHP where my app is trying to run a php backup file and suddenly getting HTTP Error 500 Code. I have checked the logs and this what it saying. [Tue Aug 28 14:17:28 2012] [warn] [client x.x.x.x] (104)Connection reset by peer: ...

json_decode returns NULL after webservice call

There is a strange behaviour with json_encode and json_decode and I can't find a solution: My php application calls a php web service. The webservice returns json that looks like this: var_dump($foo): string(62) "{"action":"set","user":"1231231231...

Entity Framework Core: DbContextOptionsBuilder does not contain a definition for 'usesqlserver' and no extension method 'usesqlserver'

I am new to EF core and I'm trying to get it to work with my ASP.NET Core project. I get the above error in my startup.cs when trying configure the DbContext to use a connection string from config. I am following this tutorial. The problematic code i...

Insert the same fixed value into multiple rows

I've got a table with a column, lets call it table_column that is currently null for all rows of the table. I'd like to insert the value "test" into that column for all rows. Can someone give me the SQL for this? I've tried INSERT INTO table (tab...

CSS align one item right with flexbox

https://jsfiddle.net/vhem8scs/ Is it possible to have two items align left and one item align right with flexbox? The link shows it more clearly. The last example is what I want to achieve. In flexbox I have one block of code. With float I have fou...

Left function in c#

what is the alternative for Left function in c# i have this in Left(fac.GetCachedValue("Auto Print Clinical Warnings").ToLower + " ", 1) == "y"); ...

Check if value exists in enum in TypeScript

I recieve a number type = 3 and have to check if it exists in this enum: export const MESSAGE_TYPE = { INFO: 1, SUCCESS: 2, WARNING: 3, ERROR: 4, }; The best way I found is by getting all Enum Values as an array and using indexOf o...

Why do I get access denied to data folder when using adb?

I connected to my live device using the adb and the following commands: C:\>adb -s HT829GZ52000 shell $ ls ls sqlite_stmt_journals cache sdcard etc system sys sbin proc logo.rle init.trout.rc init.rc init.goldfish.rc init default.prop data root d...

Chrome, Javascript, window.open in new tab

In chrome this opens in a new tab: <button onclick="window.open('newpage.html', '_blank')" /> this opens in a new window (but I'd like this to open in a new tab as well: <script language="javascript"> window.open('newpage.html', '_b...

Bash: infinite sleep (infinite blocking)

I use startx to start X which will evaluate my .xinitrc. In my .xinitrc I start my window manager using /usr/bin/mywm. Now, if I kill my WM (in order to f.e. test some other WM), X will terminate too because the .xinitrc script reached EOF. So I adde...

Import CSV into SQL Server (including automatic table creation)

I have several CSV files, which I want to import into an SQL Server database. I know if this is possible with BULK insert, but I want a solution, so that also the import table is automatically created before on basis the first row of the CSV files,ar...

How to change the color of the axis, ticks and labels for a plot in matplotlib

I'd like to Change the color of the axis, as well as ticks and value-labels for a plot I did using matplotlib and PyQt. Any ideas?...

How do I write to the console from a Laravel Controller?

So I have a Laravel controller: class YeahMyController extends BaseController { public function getSomething() { Console::info('mymessage'); // <-- what do I put here? return 'yeahoutputthistotheresponse'; } } Currently,...

Is it safe to delete a NULL pointer?

Is it safe to delete a NULL pointer? And is it a good coding style?...

Android - How to regenerate R class?

Possible Duplicate: Developing for Android in Eclipse: R.java not generating I have imported a project into my Eclipse IDE, but it's giving me an error since R file is not generated automatically. How can I edit the R file so that it matc...

Double precision floating values in Python?

Are there data types with better precision than float?...

Fastest way to list all primes below N

This is the best algorithm I could come up. def get_primes(n): numbers = set(range(n, 1, -1)) primes = [] while numbers: p = numbers.pop() primes.append(p) numbers.difference_update(set(range(p*2, n+1, p))) re...

How do I check two or more conditions in one <c:if>?

How do I check two conditions in one <c:if>? I tried this, but it raises an error: <c:if test="${ISAJAX == 0} && ${ISDATE == 0}"> ...

how to add css class to html generic control div?

I created a div tag like this: System.Web.UI.HtmlControls.HtmlGenericControl dynDiv = new System.Web.UI.HtmlControls.HtmlGenericControl("DIV"); I added style to the div tag like this: dynDiv.Style.Add(HtmlTextWriterStyle.BorderStyle, "1px so...

Html/PHP - Form - Input as array

I got a form like this <form> <input type="text" class="form-control" placeholder="Titel" name="levels[level]"> <input type="text" class="form-control" placeholder="Titel" name="levels[build_time]"> <input type="text" class="fo...

Use tab to indent in textarea

I have a simple html textarea on my side. Right now if you click tab in it, it goes to the next field. I would like to make the tab button indent a few spaces instead. How can I do this? Thanks....

Get the contents of a table row with a button click

I need to extract the details of each column in my table. For example, column "Name/Nr.". The table contains a number of addresses The very last column of each row has a button that lets a user choose a listed address. Problem: My code only picks...

How to select unique records by SQL

When I perform "SELECT * FROM table" I got results like below: 1 item1 data1 2 item1 data2 3 item2 data3 4 item3 data4 As you can see, there are dup records from column2 (item1 are dupped). So how could I just get result like this: 1 item1 data1 ...

Changing fonts in ggplot2

Once upon a time, I changed my ggplot2 font using using windowsFonts(Times=windowsFont("TT Times New Roman")) to change it. Now I can't get it off of this. In trying to set family="" in ggplot2 theme() I can't seem to generate a change in fonts as ...

Javascript/jQuery: Set Values (Selection) in a multiple Select

I have a multiple select: <select name='strings' id="strings" multiple style="width:100px;"> <option value="Test">Test</option> <option value="Prof">Prof</option> <option value="Live">Live</option&g...

print memory address of Python variable

How do I print the memory address of a variable in Python 2.7? I know id() returns the 'id' of a variable or object, but this doesn't return the expected 0x3357e182 style I was expecting to see for a memory address. I want to do something like prin...

Manifest Merger failed with multiple errors in Android Studio

So, I am a beginner into Android and Java. I just began learning. While I was experimenting with Intent today, I incurred an error. Error:Execution failed for task ':app:processDebugManifest'. > Manifest merger failed with multiple errors, see lo...

Path.Combine for URLs?

Path.Combine is handy, but is there a similar function in the .NET framework for URLs? I'm looking for syntax like this: Url.Combine("http://MyUrl.com/", "/Images/Image.jpg") which would return: "http://MyUrl.com/Images/Image.jpg"...

Checking if a list is empty with LINQ

What's the "best" (taking both speed and readability into account) way to determine if a list is empty? Even if the list is of type IEnumerable<T> and doesn't have a Count property. Right now I'm tossing up between this: if (myList.Count() ==...

What's the difference between UTF-8 and UTF-8 without BOM?

What's different between UTF-8 and UTF-8 without a BOM? Which is better? ...

TypeScript sorting an array

I've been trying to figure out a very strange issue I ran into with typescript. It was treating an inline Boolean expression as whatever the first value's type was instead of the complete expression. So if you try something simple like the following...

How do I merge a specific commit from one branch into another in Git?

I have BranchA which is 113 commits ahead of BranchB. But I only want the last 10 or so commits from BranchA merged into BranchB. Is there a way to do this?...

How should I deal with "package 'xxx' is not available (for R version x.y.z)" warning?

I tried to install a package, using install.packages("foobarbaz") but received the warning Warning message: package 'foobarbaz' is not available (for R version x.y.z) Why doesn't R think that the package is available? See also these questions ...

Use string value from a cell to access worksheet of same name

I have 2 worksheets: Summary and SERVER-ONE. In cell A5 on the Summary worksheet, I have added the value SERVER-ONE. Next to it, in cell B5, I would like a formula that uses the value in A5 to display the value of G7 in the worksheet of the same na...

how to use LIKE with column name

Normally LIKE statement is used to check the pattern like data. example: select * from table1 where name like 'ar%' My problem is to use one column of table with LIKE statement. example: select * from table1, table2 where table1.x is like tab...

Function ereg_replace() is deprecated - How to clear this bug?

I have written following PHP code: $input="menu=1&type=0&"; print $input."<hr>".ereg_replace('/&/', ':::', $input); After running above code, it gives following warning, Deprecated: Function ereg_replace() is deprecated Ho...

How do I pass variables and data from PHP to JavaScript?

I have a variable in PHP, and I need its value in my JavaScript code. How can I get my variable from PHP to JavaScript? I have code that looks like this: <?php ... $val = $myService->getValue(); // Makes an API and database call ?&g...

Decoding JSON String in Java

I am new to using the json-simple library in Java and I've been through both the encoding and decoding samples. Duplicating the encoding examples was fine, but I have not been able to get the decoding ones to work with mixed type JSON. One of my pro...

How to create a multi line body in C# System.Net.Mail.MailMessage

If create the body property as System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage(); message.Body ="First Line \n second line"; I also tried message.Body ="First Line" + system.environment + "second line"; Both of these wer...

How Do I Get the Query Builder to Output Its Raw SQL Query as a String?

Given the following code: DB::table('users')->get(); I want to get the raw SQL query string that the database query builder above will generate. In this example, it would be SELECT * FROM users. How do I do this?...

How to draw vectors (physical 2D/3D vectors) in MATLAB?

I want to know the simplest way to plot vectors in MATLAB. For example: a = [2 3 5]; b = [1 1 0]; c = a + b; I want to visualize this vector addition as head-to-tail/parallelogram method. How do I plot these vectors with an arrow-head?...

Subset of rows containing NA (missing) values in a chosen column of a data frame

We have a data frame from a CSV file. The data frame DF has columns that contain observed values and a column (VaR2) that contains the date at which a measurement has been taken. If the date was not recorded, the CSV file contains the value NA, for m...

How to find the array index with a value?

Say I've got this imageList = [100,200,300,400,500]; Which gives me [0]100 [1]200 etc. Is there any way in JavaScript to return the index with the value? I.e. I want the index for 200, I get returned 1....

How to launch another aspx web page upon button click?

I have an asp.net application, where the user would click a button and launch another page (within the same application). The issue I am facing is that the original page and the newly launched page should both be launched. I tried response.redire...

Scrolling to an Anchor using Transition/CSS3

I have a series of links which are using an anchor mechanism: <div class="header"> <p class="menu"><a href="#S1">Section1</a></p> <p class="menu"><a href="#S2">Section2</a></p> ... &l...

"Python version 2.7 required, which was not found in the registry" error when attempting to install netCDF4 on Windows 8

I use Anaconda 1.7, 32 bit. I downloaded the correct version of the netCDF4 installer from here. I attempted to copy the HKEY_LOCAL_MACHINE\SOFTWARE\Python folder into HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node. No luck. Does anyone have any idea why ...

What key in windows registry disables IE connection parameter "Automatically Detect Settings"?

I'm trying to set all the connection settings in IE. I've found how to modify most of them, in the path : HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Internet Settings But I can't find the parameter that sets or unsets "Automatical...

When should null values of Boolean be used?

Java boolean allows values of true and false while Boolean allows true, false, and null. I have started to convert my booleans to Booleans. This can cause crashes in tests such as Boolean set = null; ... if (set) ... while the test if (set != nul...

Printf width specifier to maintain precision of floating-point value

Is there a printf width specifier which can be applied to a floating point specifier that would automatically format the output to the necessary number of significant digits such that when scanning the string back in, the original floating point valu...

RegEx to extract all matches from string using RegExp.exec

I'm trying to parse the following kind of string: [key:"val" key2:"val2"] where there are arbitrary key:"val" pairs inside. I want to grab the key name and the value. For those curious I'm trying to parse the database format of task warrior. He...

Angular 2 / 4 / 5 - Set base href dynamically

We have an enterprise app that uses Angular 2 for the client. Each of our customers has their own unique url, ex: https://our.app.com/customer-one and https://our.app.com/customer-two. Currently we are able to set the <base href...> dynamically...

How to find the UpgradeCode and ProductCode of an installed application in Windows 7

I have an application installed on my machine. I also have its source code but somehow the ProductCode and UpgradeCode of this application were changed. Now I want to get the UpgradeCode and ProductCode of this installed application. I feel there m...

document.getElementById('btnid').disabled is not working in firefox and chrome

I'm using JavaScript for disabling a button. Works fine in IE but not in FireFox and chrome, here is the script what I'm working on: function disbtn(e) { if ( someCondition == true ) { document.getElementById('btn1').disabled = true; ...

ValueError : I/O operation on closed file

import csv with open('v.csv', 'w') as csvfile: cwriter = csv.writer(csvfile, delimiter=' ', quotechar='|', quoting=csv.QUOTE_MINIMAL) for w, c in p.items(): cwriter.writerow(w + c) Here, p is a dictionary, w and c both are strings. W...

ImportError: No module named PytQt5

following are my python, qt and sip versions root@thura:~# python -V Python 2.7.3 root@thura:~# qmake --version QMake version 3.0 Using Qt version 5.0.2 in /usr/lib/i386-linux-gnu root@thura:~# sip -V 4.15.3 I tried to import the PyQt5 by followin...

Remove Item from ArrayList

I have an ArrayList suppose list, and it has 8 items A-H and now I want to delete 1,3,5 position Item stored in int array from the list how can I do this. I am trying to do this with ArrayList<String> list = new ArrayList<String>(); li...

How to disable spring security for particular url

I am using stateless spring security,but in case of signup i want to disable spring security.I disabled using antMatchers("/api/v1/signup").permitAll(). but it is not working,i am getting error below: message=An Authentication object was not ...

How to iterate through table in Lua?

So, I have a table something along these lines: arr = { apples = { 'a', "red", 5 }, oranges = { 'o', "orange", 12 }, pears = { 'p', "green", 7 } } It doesn't seem like it's possible to access them based on their index, and the values themsel...

How do I increase the RAM and set up host-only networking in Vagrant?

I would like to increase the RAM to at least 1 GB and I would like to configure “Host-Only” networking to use "199.188.44.20". This is my Vagrantfile: # -*- mode: ruby -*- # vi: set ft=ruby : Vagrant::Config.run do |config| config.vm.cust...

Reading rather large json files in Python

Possible Duplicate: Is there a memory efficient and fast way to load big json files in python? So I have some rather large json encoded files. The smallest is 300MB, but this is by far the smallest. The rest are multiple GB, anywhere from ...

How to kill an Android activity when leaving it so that it cannot be accessed from the back button?

In an given Android activity, I would like to start a new activity for the user at some point. Once they leave the first activity and arrive at the second, the first activity is stale and I want to remove it completely so it can not be accessed again...

Difference between text and varchar (character varying)

What's the difference between the text data type and the character varying (varchar) data types? According to the documentation If character varying is used without length specifier, the type accepts strings of any size. The latter is a PostgreS...

C++ printing spaces or tabs given a user input integer

I need to turn user input (a number) into an output of TAB spaces. Example I ask user: cout << "Enter amount of spaces you would like (integer)" << endl; cin >> n; the (n) i need to turn it into an output like: cout << n ,...

Is there a list of screen resolutions for all Android based phones and tablets?

If not, is there a list of screen resolutions for the most popular Android phones and tablets....

javascript window.location in new tab

I am diverting user to some url through window.location but this url opens in the same tab in browser. I want it to be open in new tab. Can I do so with window.location? Is there another way to do this action?...

What is the difference between the | and || or operators?

I have always used || (two pipes) in OR expressions, both in C# and PHP. Occasionally I see a single pipe used: |. What is the difference between those two usages? Are there any caveats when using one over the other or are they interchangeable?...

How to draw checkbox or tick mark in GitHub Markdown table?

I am able to draw checkbox in Github README.md lists using - [ ] (for unchecked checkbox) - [x] (for checked checkbox) But this is not working in table. Does anybody know how to implement checkbox or checkmark in GitHub Markdown table?...

How to get the ASCII value of a character

How do I get the ASCII value of a character as an int in Python?...

How to place the "table" at the middle of the webpage?

I have a very basic Table structure to be placed in middle/center of the web page. I Have a code below, I know its incomplete to make this happen, as I am bad in structuring the HTML part, please help me <div align="center" style="vertical-align:...

How to concatenate a std::string and an int?

I thought this would be really simple but it's presenting some difficulties. If I have std::string name = "John"; int age = 21; How do I combine them to get a single string "John21"?...

Can't bind to 'dataSource' since it isn't a known property of 'table'

I am new in angular 5 development. I am trying to develop a data table with angular material using the example provided here: "https://material.angular.io/components/table/examples". I am getting an error saying Can't bind to 'dataSource' since it i...

Parse String date in (yyyy-MM-dd) format

I have a string in the form "2013-09-18". I want to convert it into a java.util.Date. I am doing this SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); Date convertedCurrentDate = sdf.parse(currentDateText); The convertedCurrentDate is c...

How to test an Oracle Stored Procedure with RefCursor return type?

I'm looking for a good explanation on how to test an Oracle stored procedure in SQL Developer or Embarcardero Rapid XE2. Thank you....

How can I get the last character in a string?

If I have the following variable in javascript var myString = "Test3"; what is the fastest way to parse out the "3" from this string that works in all browsers (back to IE6)...

find first sequence item that matches a criterion

What would be the most elegant and efficient way of finding/returning the first list item that matches a certain criterion? For example, if I have a list of objects and I would like to get the first object of those with attribute obj.val==5. I could...

How does DHT in torrents work?

I'm coding a p2p implementation that I would like to make decentralized however I'm having some trouble grasping how DHT in protocols like bittorrent work. How does the client know where the peers are if there is no tracker? Are peers stored in the a...

How do I lowercase a string in C?

How can I convert a mixed case string to a lowercase string in C?...

SonarQube not picking up Unit Test Coverage

I am having issues with sonar picking up the jacoco analysis report. Jenkins however is able to pick up the report and display the results. My project is a maven build, built by Jenkins. The jacoco report is generated by maven (configured in the pom)...

'ssh' is not recognized as an internal or external command

I have been trying to deploy my app into the Fortrabbit servers using the command line. I'm using windows. Here is what I tried : C:\projects\riwaya>git remote add fort [email protected]:riwaya.git C:\projects\riwaya>git remote fort C:\p...

SQL query to find record with ID not in another table

I have two tables with binding primary key in database and I desire to find a disjoint set between them. For example, Table1 has columns (ID, Name) and sample data: (1 ,John), (2, Peter), (3, Mary) Table2 has columns (ID, Address) and sample data:...

The type or namespace name 'DbContext' could not be found

I am VERY new to ASP.NET MVC (3) and am having a hard time resolving a build error in Visual Studio: The type or namespace name 'DbContext' could not be found (are you missing a using directive or an assembly reference?) using System; using System....

Exception: Serialization of 'Closure' is not allowed

So I am not sure exactly what I would have to show you guys, how ever if you need more code please do not hesitate to ask: So this method will set up the initMailer for Zend with in our application: protected function _initMailer() { if ('testi...

How to draw border around a UILabel?

Is there a way for UILabel to draw a border around itself? This is useful for me to debug the text placement and to see the placement and how big the label actually is....

Cast IList to List

I am trying to cast IList type to List type but I am getting error every time. List<SubProduct> subProducts= Model.subproduct; Model.subproduct returns IList<SubProduct>....

what is the difference between ajax and jquery and which one is better?

I am confused about using ajax or jquery so I want to know what the differences are and which one is better such as performance and complexity ....