Examples On Programing Languages

Define css class in django Forms

Assume I have a form class SampleClass(forms.Form): name = forms.CharField(max_length=30) age = forms.IntegerField() django_hacker = forms.BooleanField(required=False) Is there a way for me to define css classes on each field such that...

UL has margin on the left

For some reason in my footer there's a space to the left of my ul so it isn't lined up with the content above it (membership text etc) If I were to put text outside this ul (but still within the footer wrapper) there is no such space. Here's what it...

Get type of a generic parameter in Java with reflection

Is it possible to get the type of a generic parameter? An example: public final class Voodoo { public static void chill(List<?> aListWithTypeSpiderMan) { // Here I'd like to get the Class-Object 'SpiderMan' Class typeOfThe...

Why use $_SERVER['PHP_SELF'] instead of ""

In a form on a PHP page, you can use: <form action="<?php echo $_SERVER['PHP_SELF']; ?>" ...> or <form action="#" ...> or <form action="" ...> in the action attribute of the form. Since echo $_SERVER['PHP_SELF'] does...

Remove file extension from a file name string

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

ValueError: math domain error

I was just testing an example from Numerical Methods in Engineering with Python. from numpy import zeros, array from math import sin, log from newtonRaphson2 import * def f(x): f = zeros(len(x)) f[0] = sin(x[0]) + x[1]**2 + log(x[2]) - 7.0 ...

Creating the checkbox dynamically using JavaScript?

I am trying to create a checkbox dynamically using following HTML/JavaScript. Any ideas why it doesn't work? <div id="cb"></div> <script type="text/javascript"> var cbh = document.getElementById('cb'); var val = '1'; va...

Add disabled attribute to input element using Javascript

I have an input box and I want it to be disabled and at the same time hide it to avoid problems when porting my form. So far I have the following code to hide my input: $(".shownextrow").click(function() { $(this).closest("tr").next().show().f...

Difference between DOM parentNode and parentElement

Can somebody in explain me in as simple as possible terms, what is the difference between classical DOM parentNode and newly introduced in Firefox 9 parentElement...

How do I initialize a dictionary of empty lists in Python?

My attempt to programmatically create a dictionary of lists is failing to allow me to individually address dictionary keys. Whenever I create the dictionary of lists and try to append to one key, all of them are updated. Here's a very simple test cas...

Set textarea width to 100% in bootstrap modal

Was trying all possible ways, but never succeeded: <div style="float: right"> <button type="button" value="Decline" class="btn btn-danger" data-toggle="modal" data-target="#declineModal">Decline</button> </div>...

How to set root password to null

How can I change the password for root user of MySQL to null -- meaning no password or '' -- from the MySQL command line client?...

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

finding multiples of a number in Python

I'm trying to write a code that lets me find the first few multiples of a number. This is one of my attempts: def printMultiples(n, m): for m in (n,m): print(n, end = ' ') I figured out that, by putting for m in (n, m):, it would run through t...

Autoresize View When SubViews are Added

I am developing an app using iOS 7 and auto layout. I am adding a simple textfield to a UIView. But the view is not getting resized. I even tried to change the frame manually but it did not work. I believe it is because I am using auto layout. Here i...

Access parent DataContext from DataTemplate

I have a ListBox which binds to a child collection on a ViewModel. The listbox items are styled in a datatemplate based on a property on the parent ViewModel: <Style x:Key="curveSpeedNonConstantParameterCell"> <Style.Triggers> &...

Android: How to rotate a bitmap on a center point

I've been looking for over a day for a solution to this problem but nothing helps, even the answers here. Documentation doesn't explain anything too. I am simply trying to get a rotation in the direction of another object. The problem is that the bi...

Passing multiple values for same variable in stored procedure

I have a variable that passes multiple values to stored procedure. When I see through fidler I see values being passed correctly like arg1=331 arg1=222 arg1=876 arg1=932 In my stored procedure I am reading as procedure main...

How do change the color of the text of an <option> within a <select>?

I am trying to change the color of the first option to grey color, that only the text (select one option) but here it's not working here: _x000D_ _x000D_ .grey_color {_x000D_ color: #ccc;_x000D_ font-size: 14px;_x000D_ }_x000D_ <select id="se...

How are parameters sent in an HTTP POST request?

In an HTTP GET request, parameters are sent as a query string: http://example.com/page?parameter=value&also=another In an HTTP POST request, the parameters are not sent along with the URI. Where are the values? In the request header? In the reques...

Is there a "previous sibling" selector?

The plus sign (+) is for the next sibling. Is there an equivalent for the previous sibling?...

Count the Number of Tables in a SQL Server Database

I have a SQL Server 2012 database called MyDatabase. How can I find how many tables are in the database? I'm assuming the format of the query would be something like the following, but I don't know what to replace database_tables with: USE MyDataba...

How to change the DataTable Column Name?

I have one DataTable which has four columns such as StudentID CourseID SubjectCode Marks ------------ ---------- ------------- -------- 1 100 MT400 8...

jQuery AJAX Call to PHP Script with JSON Return

I've been smashing my head against a brick wall with this one, i've tried loads of the solutions on stackoverflow but can't find one that works! Basically when I POST my AJAX the PHP returns JSON but the AJAX shows Undefined instead of the value: ...

JSON ValueError: Expecting property name: line 1 column 2 (char 1)

I am having trouble using json.loads to convert to a dict object and I can't figure out what I'm doing wrong.The exact error I get running this is ValueError: Expecting property name: line 1 column 2 (char 1) Here is my code: from kafka.client i...

How to delete a file via PHP?

How do I delete a file from my server with PHP if the file is in another directory? Here is my page layout: projects/backend/removeProjectData.php (this file deletes all my entries for the database and should also delete the related file) public_...

'invalid value encountered in double_scalars' warning, possibly numpy

As I run my code I get these warnings, always in groups of four, sporadically. I have tried to locate the source by placing debug messages before and after certain statements to pin-point its origin. Warning: invalid value encountered in double_scal...

Model summary in pytorch

Is there any way, I can print the summary of a model in PyTorch like model.summary() method does in Keras as follows? Model Summary: ____________________________________________________________________________________________________ Layer (type) ...

How to get default gateway in Mac OSX

I need to retrieve the default gateway on a Mac machine. I know that in Linux route -n will give an output from which I can easily retrieve this information. However this is not working in Mac OSX(Snow Leopard). I also tried netstat -nr | grep 'def...

Smooth scrolling with just pure css

How can I make a smooth scrolling with just pure css. I have this code Fiddle HTML <a id="up" href="#down">down</a> <div class="up"></div> <a id="down" href="#up">up</a> <div class="down"></div> ...

Two-dimensional array in Swift

I get so confused about 2D arrays in Swift. Let me describe step by step. And would you please correct me if I am wrong. First of all; declaration of an empty array: class test{ var my2Darr = Int[][]() } Secondly fill the array. (such as my2D...

Running multiple async tasks and waiting for them all to complete

I need to run multiple async tasks in a console application, and wait for them all to complete before further processing. There's many articles out there, but I seem to get more confused the more I read. I've read and understand the basic principles...

What does "The code generator has deoptimised the styling of [some file] as it exceeds the max of "100KB"" mean?

I added a new npm package to my project and require it in one of my modules. Now I get this message from webpack, build modulesNote: The code generator has deoptimised the styling of "D:/path/to/project/node_modules/ramda/dist/ramda.js" as it excee...

Laravel 5.1 API Enable Cors

I've looked for some ways to enable cors on laravel 5.1 specifically, I have found some libs like: https://github.com/neomerx/cors-illuminate https://github.com/barryvdh/laravel-cors but none of them has a implementation tutorial specifically to L...

Mongoose limit/offset and count query

Bit of an odd one on query performance... I need to run a query which does a total count of documents, and can also return a result set that can be limited and offset. So, I have 57 documents in total, and the user wants 10 documents offset by 20. ...

How to set JAVA_HOME in Linux for all users

I am new to Linux system and there seem to be too many Java folders. java -version gives me: java version "1.7.0_55" OpenJDK Runtime Environment (rhel-2.4.7.1.el6_5-x86_64 u55-b13) OpenJDK 64-Bit Server VM (build 24.51-b03, mixed mode) When I a...

OpenCV - Saving images to a particular folder of choice

I'm learning OpenCV and Python. I captured some images from my webcam and saved them. But they are being saved by default into the local folder. I want to save them to another folder from direct path. How do I fix it? ...

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

C++ Pass A String

Quick probably obvious question. If I have: void print(string input) { cout << input << endl; } How do I call it like so: print("Yo!"); It complains that I'm passing in char *, instead of std::string. Is there a way to typecast i...

Java - removing first character of a string

In Java, I have a String: Jamaica I would like to remove the first character of the string and then return amaica How would I do this?...

How to parse a string to an int in C++?

What's the C++ way of parsing a string (given as char *) into an int? Robust and clear error handling is a plus (instead of returning zero)....

Regular expression "^[a-zA-Z]" or "[^a-zA-Z]"

Is there a difference between ^[a-zA-Z] and [^a-zA-Z]? When I check in C#, Regex.IsMatch("t", "^[a-zA-Z]") // Returns true (I think it's correct) Regex.IsMatch("t", "[^a-zA-Z]") // Returns false There are a lot of web sites using [^a-zA-Z] fo...

.trim() in JavaScript not working in IE

I tried to apply .trim() to a string in one of my JavaScript programs. It's working fine under Mozilla, but an error displays when I try it in IE8. Does anyone know what is going on here? Is there anyway I can make it work in IE? code: var ID = do...

Warning: X may be used uninitialized in this function

I am writing a custom "vector" struct. I do not understand why I'm getting a Warning: "one" may be used uninitialized here. This is my vector.h file #ifndef VECTOR_H #define VECTOR_H typedef struct Vector{ int a; int b; int c; }Vector;...

MySQL: Grant **all** privileges on database

I've created database, for example 'mydb'. CREATE DATABASE mydb CHARACTER SET utf8 COLLATE utf8_bin; CREATE USER 'myuser'@'%' IDENTIFIED BY PASSWORD '*HASH'; GRANT ALL ON mydb.* TO 'myuser'@'%'; GRANT ALL ON mydb TO 'myuser'@'%'; GRANT CREATE ON my...

Facebook API: Get fans of / people who like a page

I'd like to get a list of users who like a certain page or a fan of it. The FB API documentation states that you can only get the count of the fans of a certain page using the social graph, but not a list of the fans. A discussion here Retrieve Fa...

Why is my CSS style not being applied?

I've got this html: <p> <span class="fancify">Parting is such sweet sorrow!</span><span> - Bill Rattleandrollspeer</span> </p> ...and this css (added to the bottom of Site.css): .fancify { font-size: 1....

Injecting $scope into an angular service function()

I have a Service: angular.module('cfd') .service('StudentService', [ '$http', function ($http) { // get some data via the $http var path = 'data/people/students.json'; var students = $http.get(path).then(function (resp) { ret...

How to open a web page automatically in full screen mode

How do I open a web page automatically in full screen mode? I am looking for a solution to open an web page automatically in full screen mode, without expecting user to users press F11 or any other browser-specifc key. I've searched a lot, but I j...

How to implement swipe gestures for mobile devices?

I have an application made in AngularJS which has arrow key navigation to switch views. I want to implement this navigation using swipe for touch devices. I tried jGestures library but it doesn't go well with swipe. I have been recommended NOT to us...

Can I convert long to int?

I want to convert long to int. If the value of long > int.MaxValue, I am happy to let it wrap around. What is the best way?...

SQL JOIN - WHERE clause vs. ON clause

After reading it, this is not a duplicate of Explicit vs Implicit SQL Joins. The answer may be related (or even the same) but the question is different. What is the difference and what should go in each? If I understand the theory correctly, the ...

Labeling file upload button

How can I internationalize the button text of the file picker? For example, what this code presents to the user: <input type="file" .../> ...

Python Traceback (most recent call last)

I am getting an error executing this code: nameUser=input("What is your name ? ") print (nameUser) The error message is Traceback (most recent call last): File "C:/Users/DALY/Desktop/premier.py", line 1, in File "", line 1, in ...

Utils to read resource text file to String (Java)

Is there any utility that helps to read a text file in the resource into a String. I suppose this is a popular requirement, but I couldn't find any utility after Googling....

git pull aborted with error filename too long

I'm using Windows as my OS, and working on a project with a friend who's using a Mac. He checked in code to our Github. I was trying to git pull everything he did and it aborted with "filename too long" errors of 3rd party code. What can I do?...

Updating a date in Oracle SQL table

I am trying to update a date in a SQL table. I am using Peoplesoft Oracle. When I run this query: Select ASOFDATE from PASOFDATE; I get 4/16/2012 I tried running this query UPDATE PASOFDATE SET ASOFDATE = '11/21/2012'; but it is not working....

How to run Node.js as a background process and never die?

I connect to the linux server via putty SSH. I tried to run it as a background process like this: $ node server.js & However, after 2.5 hrs the terminal becomes inactive and the process dies. Is there anyway I can keep the process alive even ...

Unity 2d jumping script

Does anyone have a good jumping script for 2d games in unity? The code I have works but still is far from jumping, it looks like it is flying. using UnityEngine; using System.Collections; public class movingplayer : MonoBehaviour { public Vector2 ...

Set Focus on EditText

I have an EditText-Field and set an OnFocusChangeListener for it. When it has lost focus, a method is called, which checks the value of the EditText with one in the database. If the return-value of the method is true, a toast is shown and the focus s...

Decoding UTF-8 strings in Python

I'm writing a web crawler in python, and it involves taking headlines from websites. One of the headlines should've read : And the Hip's coming, too But instead it said: And the Hip’s coming, too What's going wrong here?...

Create an array of integers property in Objective-C

I'm having troubles creating a property of an array of integers in Objective-C. I'm not sure whether this is even possible to do in Obj-C so I'm hoping someone can help me in finding out either how to do it correctly or provide an alternative solutio...

How to handle invalid SSL certificates with Apache HttpClient?

I know, there are many different questions and so many answers about this problem... But I can't understand... I have: ubuntu-9.10-desktop-amd64 + NetBeans6.7.1 installed "as is" from off. rep. I need connecting to some site over the HTTPS. For this...

NoClassDefFoundError for code in an Java library on Android

I am experiencing an error quite often among my users. The app crashes during startup. When the MainActivity is supposed to be loaded the VM apparently cannot find the class. I cannot figure out why. The architecture of the app is that there is a com...

Read lines from a file into a Bash array

I am trying to read a file containing lines into a Bash array. I have tried the following so far: Attempt1 a=( $( cat /path/to/filename ) ) Attempt2 index=0 while read line ; do MYARRAY[$index]="$line" index=$(($index+1)) done < /pat...

jQuery hasClass() - check for more than one class

With: if(element.hasClass("class")) I can check for one class, but is there an easy way to check whether "element" has any of many classes? I am using: if(element.hasClass("class") || element.hasClass("class") ... ) Which isn't too bad, but I ...

How to quickly clear a JavaScript Object?

With a JavaScript Array, I can reset it to an empty state with a single assignment: array.length = 0; This makes the Array "appear" empty and ready to reuse, and as far as I understand is a single "operation" - that is, constant time. Is there a ...

How to get text of an element in Selenium WebDriver, without including child element text?

<div id="a">This is some <div id="b">text</div> </div> Getting "This is some" is non-trivial. For instance, this returns "This is some text": driver.find_element_by_id('a').text How does one, in a general way, get the...

Call An Asynchronous Javascript Function Synchronously

First, this is a very specific case of doing it the wrong way on-purpose to retrofit an asynchronous call into a very synchronous codebase that is many thousands of lines long and time doesn't currently afford the ability to make the changes to "do i...

How to compare two JSON have the same properties without order?

I have tried to compare those two JSON objects: <input type="hidden" id="remoteJSON" name="remoteJSON" value='{"allowExternalMembers": "false", "whoCanJoin": "CAN_REQUEST_TO_JOIN"}' /><br /> <input type="hidden" id="localJSON" name="l...

json: cannot unmarshal object into Go value of type

I can't decode the json code below ... any ideas why it doesn't work ? See also play.golang package main import ( "encoding/json" ) type LocationReadable struct { District string City string State s...

How to include an HTML page into another HTML page without frame/iframe?

I want to include an HTML page inside an HTML page. Is it possible? I don't want to do it in PHP, I know that in PHP, we can use include for this situation, how can I achieve the same purely in HTML without using the iframe and frame concept?...

How do I combine the first character of a cell with another cell in Excel?

I have an Excel sheet with first names in Column A and surnames in Column B. I want to create a third Column C that contains the first character from the first name and adds it to the surname, creating first initial + surname. First Name Last Nam...

Reading an integer from user input

What I am looking for is how to read an integer that was given by the user from the command line (console project). I primarily know C++ and have started down the C# path. I know that Console.ReadLine(); only takes a char/string. So in short I am loo...

Trigger a Travis-CI rebuild without pushing a commit?

Using Travis-CI, is it possible to trigger a rebuild without pushing a new commit to GitHub? Use case: A build fails due to an externality. The source is actually correct. It would build OK and pass if simply re-run. For instance, an apt-get fails ...

Retain precision with double in Java

public class doublePrecision { public static void main(String[] args) { double total = 0; total += 5.6; total += 5.8; System.out.println(total); } } The above code prints: 11.399999999999 How would I get ...

Evaluate a string with a switch in C++

I want to evaluate a string with a switch but when I read the string entered by the user throws me the following error. #include<iostream> using namespace std; int main() { string a; cin>>a; switch (string(a)...

PHP: Count a stdClass object

I have a stdClass object created from json_decode that won't return the right number when I run the count($obj) function. The object has 30 properties, but the return on the count() function is say 1. Any ideas? Below is an example of one of the o...

Why is __init__() always called after __new__()?

I'm just trying to streamline one of my classes and have introduced some functionality in the same style as the flyweight design pattern. However, I'm a bit confused as to why __init__ is always called after __new__. I wasn't expecting this. Can any...

understanding private setters

I don't understand the need of having private setters which started with C# 2. Having a setter method for me is letting the user to set some variables in that class. In doing so, we will not expose the variables directly to the users. Instead we le...

C++ JSON Serialization

I want a way to serialize and deserialize Objects to JSON, as automatic as possible. Serialize: For me, the ideal way is that if I call in an instance JSONSerialize() it returns an string with a JSON object that has all the public properties of the ...

How to calculate the 95% confidence interval for the slope in a linear regression model in R

Here is an exercise from Introductory Statistics with R: With the rmr data set, plot metabolic rate versus body weight. Fit a linear regression model to the relation. According to the fitted model, what is the predicted metabolic rate for a body wei...

How to convert MySQL time to UNIX timestamp using PHP?

There are a lot of questions that ask about 'UNIX timestamp to MySQL time'. I needed the reversed way, yea... Any idea?...

XPath: How to select elements based on their value?

I am new to using XPath and this may be a basic question. Kindly bear with me and help me in resolving the issue. I have an XML file like this: <RootNode> <FirstChild> <Element attribute1="abc" attribute2="xyz">Data</Eleme...

How to read a file into vector in C++?

I need to read from a .data or .txt file containing a new float number on each line into a vector. I have searched far and wide and applied numerous different methods but every time I get the same result, of a Main.size() of 0 and an error saying "...

How to put scroll bar only for modal-body?

I have the following element: <div class="modal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"> <div class="modal-dialog" style="overflow-y: scroll; max-height:85%; margin-top: 50px; margin-bottom:50px;...

How To Convert A Number To an ASCII Character?

I want to create an application where user would input a number and the program will throw back a character to the user. Edit: How about vice versa, changing a ascii character into number?...

Using Alert in Response.Write Function in ASP.NET

I have database code like this try { string strConnectionString = ConfigurationManager.ConnectionStrings["SqlServerCstr"].ConnectionString; SqlConnection myConnection = new SqlConnection(strConnectionString); myConnection.Open(); ...

In Visual Studio Code How do I merge between two local branches?

In Visual Studio Code it seems that I am only allowed to push, pull and sync. There is documented support for merge conflicts but I can't figure out how to actually merge between two branches. The Git command line within VSC (press F1) only facillita...

Code coverage with Mocha

I am using Mocha for testing my NodeJS application. I am not able to figure out how to use its code coverage feature. I tried googling it but did not find any proper tutorial. Please help....

Convert an array to string

How do I make this output to a string? List<string> Client = new List<string>(); foreach (string listitem in lbClients.SelectedItems) { Client.Add(listitem); } ...

Best way to check if an PowerShell Object exist?

I am looking for the best way to check if a Com Object exists. Here is the code that I have; I'd like to improve the last line: $ie = New-Object -ComObject InternetExplorer.Application $ie.Navigate("http://www.stackoverflow.com") $ie.Visible = $tru...

Defining TypeScript callback type

I've got the following class in TypeScript: class CallbackTest { public myCallback; public doWork(): void { //doing some work... this.myCallback(); //calling callback } } I am using the class like this: var test =...

Convert date to YYYYMM format

I want to select value = 201301 select getdate(), cast(datepart(year, getdate()) as varchar(4))+cast(datepart(MONTH, getdate()) as varchar(2)) it returns 20131 what is the normal way to do this?...

how to add picasso library in android studio

I am getting this error, please help me. Error:A problem occurred configuring project ':app'. > Cannot evaluate module picasso-master : Configuration with name 'default' not found. Done so far : 1. download the picaso 2.unzip the zip f...

Proxy with express.js

To avoid same-domain AJAX issues, I want my node.js web server to forward all requests from URL /api/BLABLA to another server, for example other_domain.com:3000/BLABLA, and return to user the same thing that this remote server returned, transparently...

Eclipse Optimize Imports to Include Static Imports

Is there anyway to get Eclipse to automatically look for static imports? For example, now that I've finally upgraded to Junit 4, I'd like to be able to write: assertEquals(expectedValue, actualValue); hit Ctrl + Shift + O and have Eclipse add: im...

How to determine whether a given Linux is 32 bit or 64 bit?

When I type uname -a, it gives the following output. Linux mars 2.6.9-67.0.15.ELsmp #1 SMP Tue Apr 22 13:50:33 EDT 2008 i686 i686 i386 GNU/Linux How can I know from this that the given OS is 32 or 64 bit? This is useful when writing configure scr...

How to remove symbols from a string with Python?

I'm a beginner with both Python and RegEx, and I would like to know how to make a string that takes symbols and replaces them with spaces. Any help is great. For example: how much for the maple syrup? $20.99? That's ricidulous!!! into: how much ...

How to make an autocomplete TextBox in ASP.NET?

How do I make an autocomplete TextBox in C# that binds to a data source?...

Grep regex NOT containing string

I am passing a list of regex patterns to grep to check against a syslog file. They are usually matching an IP address and log entry; grep "1\.2\.3\.4.*Has exploded" syslog.log It's just a list of patterns like the "1\.2\.3\.4.*Has exp...

Mobile overflow:scroll and overflow-scrolling: touch // prevent viewport "bounce"

On a mobile (Safari, webviews, wherever), overflow:scroll and overflow-scrolling: touch give a pretty smooth scroll, which is cool. But, it makes the page "bounce" (area circled below), which is not the case when you are not using it, but ...

Passing multiple parameters to pool.map() function in Python

I need some way to use a function within pool.map() that accepts more than one parameter. As per my understanding, the target function of pool.map() can only have one iterable as a parameter but is there a way that I can pass other parameters in as w...

telnet to port 8089 correct command

I am using telnet to port 8089 on remote server. Can any tell me which of the following commands are true. telnet 74.255.12.25 8089 or telnet 74.255.12.25 89 Thanks in Advance....

JQuery .each() backwards

I'm using JQuery to select some elements on a page and then move them around in the DOM. The problem I'm having is I need to select all the elements in the reverse order that JQuery naturally wants to select them. For example: <ul> <li&g...

Commands out of sync; you can't run this command now

I am trying to execute my PHP code, which calls two MySQL queries via mysqli, and get the error "Commands out of sync; you can't run this command now". Here is the code I am using <?php $con = mysqli_connect("localhost", "user", "password", "db"...

How do I convert hex to decimal in Python?

I have some Perl code where the hex() function converts hex data to decimal. How can I do it on Python?...

jQuery get specific option tag text

All right, say I have this: <select id='list'> <option value='1'>Option A</option> <option value='2'>Option B</option> <option value='3'>Option C</option> </select> What would the selecto...

Can't specify the 'async' modifier on the 'Main' method of a console app

I am new to asynchronous programming with the async modifier. I am trying to figure out how to make sure that my Main method of a console application actually runs asynchronously. class Program { static void Main(string[] args) { Boo...

How can I flush GPU memory using CUDA (physical reset is unavailable)

My CUDA program crashed during execution, before memory was flushed. As a result, device memory remained occupied. I'm running on a GTX 580, for which nvidia-smi --gpu-reset is not supported. Placing cudaDeviceReset() in the beginning of the progra...

Javascript add method to object

Suppose I have a Foo object How can I extend this object by adding a bar() method and also ensure that future instances of Foo have this method?...

How to create .ipa file using Xcode?

Please tell me the complete procedure to build my app & use it on a real iPhone....

Extracting text from a PDF file using PDFMiner in python?

I am looking for documentation or examples on how to extract text from a PDF file using PDFMiner with Python. It looks like PDFMiner updated their API and all the relevant examples I have found contain outdated code(classes and methods have changed)...

How to deal with ModalDialog using selenium webdriver?

I am unable to switch to Modal Dialog of given example http://samples.msdn.microsoft.com/workshop/samples/author/dhtml/refs/showModalDialog2.htm I don't know how to get element on modal Dialog ...

How to update column with null value

I am using mysql and need to update a column with a null value. I have tried this many different ways and the best I have gotten is an empty string. Is there a special syntax to do this?...

FirstOrDefault returns NullReferenceException if no match is found

Here is my code: string displayName = Dictionary.FirstOrDefault(x => x.Value.ID == long.Parse(options.ID)).Value.DisplayName; The code works fine if x.Value.ID matches options.ID. However, I get a NullReferenceException if it doesn't....

How to grant "grant create session" privilege?

How to grant the privilege of giving the privilege of creating a session to a user or role in Oracle?...

How to define dimens.xml for every different screen size in android?

When supporting different screen sizes (densities) in Android often the focus is on creating different layouts for every possible screen. I.E. ldpi mdpi hdpi xhdpi xxhdpi xxxhdpi I designed a layout for an xhdpi screen as a reference, and defined...

How to add an image to the "drawable" folder in Android Studio?

I need to add an image to the res/drawable folder... When I choose new > Image Asset, it comes out a dialog to choose Asset Type... How can I add an image to res/drawable folder?...

Detect changed input text box

I've looked at numerous other questions and found very simple answers, including the code below. I simply want to detect when someone changes the content of a text box but for some reason it's not working... I get no console errors. When I set a b...

How to delete rows from a pandas DataFrame based on a conditional expression

I have a pandas DataFrame and I want to delete rows from it where the length of the string in a particular column is greater than 2. I expect to be able to do this (per this answer): df[(len(df['column name']) < 2)] but I just get the error: ...

How to implement an STL-style iterator and avoid common pitfalls?

I made a collection for which I want to provide an STL-style, random-access iterator. I was searching around for an example implementation of an iterator but I didn't find any. I know about the need for const overloads of [] and * operators. What are...

Object passed as parameter to another class, by value or reference?

In C#, I know that by default, any parameters passed into a function would be by copy, that's, within the function, there is a local copy of the parameter. But, what about when an object is passed as parameter to another class? Would a scenario lik...

5.7.57 SMTP - Client was not authenticated to send anonymous mail during MAIL FROM error

I have to send mails using my web application. Given the below code showing The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.7.57 SMTP; Client was not authenticated to send anonymous ma...

How to use multiple @RequestMapping annotations in spring?

Is it possible to use multiple @RequestMapping annotations over a method? Like : @RequestMapping("/") @RequestMapping("") @RequestMapping("/welcome") public String welcomeHandler(){ return "welcome"; } ...

Get the current displaying UIViewController on the screen in AppDelegate.m

The current UIViewController on the screen need to response to push-notifications from APNs, by setting some badge views. But how could I get the UIViewController in methodapplication:didReceiveRemoteNotification: of AppDelegate.m? I tried use self....

How to set Internet options for Android emulator?

I've been using this method to gain access to internet from my Android emulator emulator -http-proxy <<proxy-name>> -avd <<avd_name>> It works but is that the best way to do it? It just doesn't feel right that I need to open ...

How do I get an element to scroll into view, using jQuery?

I have an HTML document with images in a grid format using <ul><li><img.... The browser window has both vertical & horizontal scrolling. Question: When I click on an image <img>, how then do I get the whole document to scr...

jQuery: If this HREF contains

Why can't I get this to work?? $("a").each(function() { if ($(this[href$="?"]).length()) { alert("Contains questionmark"); } }); Ps.: This is just at simplifyed example, to make it easier for you to get an overview....

How to create a multiline UITextfield?

I am developing an application where user has to write some information. For this purpose I need a UITextField which is multi-line (in general UITextField is a single line). As I'm Googling I find a answer of using UITextView instead of UITextfield ...

How to set Apache Spark Executor memory

How can I increase the memory available for Apache spark executor nodes? I have a 2 GB file that is suitable to loading in to Apache Spark. I am running apache spark for the moment on 1 machine, so the driver and executor are on the same machine. Th...

SQL DROP TABLE foreign key constraint

If I want to delete all the tables in my database like this, will it take care of the foreign key constraint? If not, how do I take care of that first? GO IF OBJECT_ID('dbo.[Course]','U') IS NOT NULL DROP TABLE dbo.[Course] GO IF OBJECT_ID('dbo....

Make $JAVA_HOME easily changable in Ubuntu

In Ubuntu, I'd like to switch my JAVA_HOME environment variable back and forth between Java 5 and 6. I open a terminal and type in the following to set the JAVA_HOME environment variable: export JAVA_HOME=/usr/lib/jvm/java-1.5.0-sun And in that s...

How to split a string literal across multiple lines in C / Objective-C?

I have a pretty long sqlite query: const char *sql_query = "SELECT statuses.word_id FROM lang1_words, statuses WHERE statuses.word_id = lang1_words.word_id ORDER BY lang1_words.word ASC"; How can I break it in a number of lines to make it easier t...

SQL set values of one column equal to values of another column in the same table

I have a table with two DATETIME columns. One of them is never NULL, but one of them is sometimes NULL. I need to write a query which will set all the NULL rows for column B equal to the values in column A. I have tried this example but the SQL in...

How to hide a div from code (c#)

I have a div element on my page that I wish to show/hide based on a session value in my code-behind. How can I do this?...

WebView link click open default browser

Right now I have an app that loads a webview and all the clicks are kept within the app. What I would like to do is when a certain link, for example, http://www.google.com is clicked within the app it opens the default browser. If anyone has some ide...

JQuery datepicker not working

Good day! I am trying to use jquery for the first time. And i cannot make it work. My code is as follows: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://ww...

Put a Delay in Javascript

I need to add a delay of about 100 miliseconds to my Javascript code but I don't want to use the setTimeout function of the window object and I don't want to use a busy loop. Does anyone have any suggestions?...

Cannot open solution file in Visual Studio Code

I have installed the Visual Studio Code on Windows. When I try to open a solution file in VS Code it opens the solution file, instead of opening all projects in solution. Is there a way to open existing project solutions in VS Code?...

How to convert float value to integer in php?

I want to convert float value (Eg:1.0000124668092E+14) to Integer in php,what is the best method for this in php.output should be "100001246680920"...

What Regex would capture everything from ' mark to the end of a line?

I have a text file that denotes remarks with a single '. Some lines have two quotes but I need to get everything from the first instance of a ' and the line feed. I AL01 ' A-LINE '091398 GDK 33394178 ...

opening a window form from another form programmatically

I am making a Windows Forms application. I have a form. I want to open a new form at run time from the original form on a button click. And then close this new form (after 2,3 sec) programatically but from a thread other than gui main thread. Can ...

How to use SSH to run a local shell script on a remote machine?

I have to run a local shell script (windows/Linux) on a remote machine. I have SSH configured on both machine A and B. My script is on machine A which will run some of my code on a remote machine, machine B. The local and remote computers can be eith...

Is it possible to program Android to act as physical USB keyboard?

What I really want to know is whether it is a hardware problem, or a software problem. Could I plug my android phone into a computer via USB and have it act as a hardware keyboard. I do not want to install anything on the computer, I want android to ...

How to convert string to Title Case in Python?

Example: HILO -> Hilo new york -> New York SAN FRANCISCO -> San Francisco Is there a library or standard way to perform this task? ...

Pick any kind of file via an Intent in Android

I would like to start an intentchooser for apps which can return any kind of file Currently I use (which I copied from the Android email source code for file attachment) Intent intent = new Intent(Intent.ACTION_GET_CONTENT); intent.addCategory(Inte...

What do .c and .h file extensions mean to C?

It's all in the title; super-simple I reckon, but it's so hard to search for syntactical things anywhere. These are two library files that I'm copying from CS50.net, and I'm wondering why they have two different extensions....

How to get attribute of element from Selenium?

I'm working with Selenium in Python. I would like to get the .val() of a <select> element and check that it is what I expect. This is my code: def test_chart_renders_from_url(self): url = 'http://localhost:8000/analyse/' self.browser....

how to merge 200 csv files in Python

Guys, I here have 200 separate csv files named from SH (1) to SH (200). I want to merge them into a single csv file. How can I do it?...

How to format dateTime in django template?

That: {{ wpis.entry.lastChangeDate|date:"D d M Y" }} gives me (why?): 2009-07-24 21:45:38.986156 and i don't know how to skip fraction part... In my model i have: addedDate = models.DateTimeField(default=datetime.now) ...

How do I create a GUI for a windows application using C++?

I am deciding on how to develop a GUI for a small c++/win32 api project (working Visual Studio C++ 2008). The project will only need a few components to start off the main process so it will be very light weight (just 1 button and a text box pretty m...

How can I adjust DIV width to contents

I have a div element with style attached: .mypost { border: 1px solid Peru; font-family: arial; margin: auto; min-width: 700px; width: 700px; } I am diplaying WordPress post contents inside the DIV block but for simplicity let ...

START_STICKY and START_NOT_STICKY

What is the difference between START_STICKY and START_NOT_STICKY while implementing services in android? Could anyone point out to some standard examples.. ?...

PostgreSQL: FOREIGN KEY/ON DELETE CASCADE

I have two tables like here: DROP TABLE IF EXISTS schemas.book; DROP TABLE IF EXISTS schemas.category; DROP SCHEMA IF EXISTS schemas; CREATE SCHEMA schemas; CREATE TABLE schemas.category ( id BIGSERIAL PRIMARY KEY, name ...

How to center cell contents of a LaTeX table whose columns have fixed widths?

Consider the following piece of LaTeX code: \begin{tabular}{p{1in}p{1in}} A & B\\ C & D\\ \end{tabular} How can I make the contents of each cell aligned in the center of the cell rather than the left? Note that I want to make sure that t...

How can I see an the output of my C programs using Dev-C++?

I'm looking to follow along with The C Programming Language (Second Addition) on a machine running Vista. So far, I've found Dev-C++ the easiest IDE to do this in. However, I still have one problem. Whenever I run my compiled code, for example: a si...

How to place a text next to the picture?

I want to place 2 pictures, one on top of the page and the other right below it. Then, I want to write something about each picture and I want the text to be located to the right of each picture. How can this be done? I am formatting my pictures as...

Python Tkinter clearing a frame

I am trying to clear out a frame in the tkinter so that the new contents can be written (refresh information) but i could not manage to do it. I am aware of these frame.destroy() frame.pack_forget() frame.grid_forget() but frame.destroy() will to...

Difference between x86, x32, and x64 architectures?

Please explain the difference between x86, x32 and x64? Its a bit confusing when it comes to x86 and x32 because most of the time 32-bit programs run on x86... ...

Django: Display Choice Value

models.py: class Person(models.Model): name = models.CharField(max_length=200) CATEGORY_CHOICES = ( ('M', 'Male'), ('F', 'Female'), ) gender = models.CharField(max_length=200, choices=CATEGORY_CHOICES) to_be_liste...

How can I make a SQL temp table with primary key and auto-incrementing field?

What am I missing here? I'm trying to get the ID field to be the primary key and auto increment so that I don't need to insert it explicitly. CREATE TABLE #tmp ( ID INT IDENTITY(1, 1) , AssignedTo NVARCHAR(100), AltBusinessSeverity NVARCHAR(100), De...

Copy file from source directory to binary directory using CMake

I'm trying to create a simple project on CLion. It uses CMake (I'm new here) to generate Makefiles to build project (or some sort of it) All I need to is transfer some non-project file (some sort of resource file) to binary directory each time when ...

Create a map with clickable provinces/states using SVG, HTML/CSS, ImageMap

I am trying to create an interactive map where users can click on different provinces in the map to get info specific to that province. Example: archived: http://www.todospelaeducacao.org.br/ archived: http://code.google.com/p/svg2imap/ So far I...

Cannot kill Python script with Ctrl-C

I am testing Python threading with the following script: import threading class FirstThread (threading.Thread): def run (self): while True: print 'first' class SecondThread (threading.Thread): def run (self): wh...

How can I insert new line/carriage returns into an element.textContent?

As silly as it may sound, I still haven't found an appropriate answer. Let's say I want to dynamically create a new DOM element and fill up its textContent/innerText with a JS string literal. The string is so long I would like to split it into three...

jQuery looping .each() JSON key/value not working

I am having problems in looping the key/value of JSON by jQuery .each() function Initially I have a JSON like this: json = {"aaa":[ {"id":"1","data":"aaa1data"} ,{"id":"2","data":"aaa2data"} ], "bbb...

What is the difference between baud rate and bit rate?

I am really having hard time understanding the difference. Some say they are same, while others say there is a slight difference. What's the difference, exactly? I would like it if you explained with some analogy....

Android: How to Programmatically set the size of a Layout

As part of an Android App I am building a button set. The buttons are part of a nested set of LinearLayouts. Using weight I have the set resizing itself automatically based on the size of the containing parent LinearLayout. The idea is, based on the ...

Returning boolean if set is empty

I am struggling to find a more clean way of returning a boolean value if my set is empty at the end of my function I take the intersection of two sets, and want to return True or False based on if the resulting set is empty. def myfunc(a,b): c ...

Android "hello world" pushnotification example

I am new to android application development and I am learning little bit. I am in a hard mission for sending push notification ( cloud messaging ) from my web server ( PHP ) to android application ( just a "helloworld" ). I did some "googling" and fe...

80-characters / right margin line in Sublime Text 3

You can have 80-characters / right margin line in Netbeans, Text Mate and probably many, many more other IDEs. Is it possible to have it in Sublime Text 3 as well? Any option, plugin etc.?...

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

Use FontAwesome or Glyphicons with css :before

Is there any way to embed HTML in the css content: element when using a :before pseudo-element? I want to use a Font Awesome (or Glyphicon) in a use case like this: h1:before { content: "X"; padding-right: 10px; padding-...

Using :focus to style outer div?

When I begin writing text in the textarea, I want the outer div, with a class box, to have it's border turned solid instead of dashed, but somehow the :focus doesn't apply in this case. If it works with :active, how come it doesn't work with :focus? ...

json.decoder.JSONDecodeError: Extra data: line 2 column 1 (char 190)

I am running the following code- import json addrsfile = open("C:\\Users\file.json", "r") addrJson = json.loads(addrsfile.read()) addrsfile.close() if addrJson: print("yes") But giving me following error- Traceback (most recent call last):...

How can I increase the size of a bootstrap button?

For example I've made my button <div class="btn btn-default"> Active </div> and it looks like the following However I would like to have my button like this How can I enlarge the width of the bootstrap button regardless of text...

SQL "IF", "BEGIN", "END", "END IF"?

Not a SQL person at all. Have the following code a consultant wrote. First, it makes sure only an elementary school has been chosen - then, after the BEGIN, if the variable @Term equals a 3 we want to do the stuff under that IF statement. Here'...

use a javascript array to fill up a drop down select box

I have a text file which I am reading and storing the data in a javascript array, it's a list of cuisines. I want to use the array to fill up a drop down select box. I know how to hard code in the values for the drop down box (using correct me if i'...

MySQL: update a field only if condition is met

Is it possible to do an UPDATE query in MySQL which updates field value only if certain condition is met? Something like this: UPDATE test SET CASE WHEN true THEN field = 1 END WHERE id = 123 In other words: UPDATE test S...

dismissModalViewControllerAnimated deprecated

I've just upgraded to XCode 4.5 to update my iOS app to run on the 4 inch display for the iPhone 5, but I'm getting a build error saying dismissModalViewControllerAnimated:' is deprecated on the line: [self dismissModalViewControllerAnimated:NO]; ...

Windows batch - concatenate multiple text files into one

I need to create a script, which concatenates multiple text files into one. I know it's simple to use type *.txt > merged.txt But the requirement is to "concatenate files from same day into file day_YYYY-DD-MM.txt" I am a Linux user and...

How do I add all new files to SVN

I am using an ORM which generates large amounts of files from a CLI. Is there an easy way to run the svn add on all files within a directory which appear as ? when I run svn status? Edit These files exist in a directory tree so adding * for one di...

IF EXISTS, THEN SELECT ELSE INSERT AND THEN SELECT

How do you say the following in Microsoft SQL Server 2005: IF EXISTS (SELECT * FROM Table WHERE FieldValue='') THEN SELECT TableID FROM Table WHERE FieldValue='' ELSE INSERT INTO TABLE(FieldValue) VALUES('') SELECT TableID FROM Table WHERE ...

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

How to prevent browser to invoke basic auth popup and handle 401 error using Jquery?

I need to send authorization request using basic auth. I have successfully implemented this using jquery. However when I get 401 error basic auth browser popup is opened and jquery ajax error callback is not called....

Passing javascript variable to html textbox

i need help on html form. I got a javascript variable, and I am trying to pass the variable to a html form texbox. I want to display the variable on the textbox dynamically. but i do not know how to pass the variable to the html form and call the va...

Printf long long int in C with GCC?

How do I printf long long int and also unsigned long long int in C99 using GCC? I have searched the other posts which suggest to use %lld but it gives these warnings: warning#1: unknown conversion type character 'l' in format [-Wformat]| warn...

Comparison of C++ unit test frameworks

I know there are already a few questions regarding recommendations for C++ unit test frameworks, but all the answers did not help as they just recommend one of the frameworks but do not provide any information about a (feature) comparison. I think t...

Get escaped URL parameter

I'm looking for a jQuery plugin that can get URL parameters, and support this search string without outputting the JavaScript error: "malformed URI sequence". If there isn't a jQuery plugin that supports this, I need to know how to modify it to suppo...

Flutter: Run method on Widget build complete

I would like to be able to run functions once a Widget has finished building/loading but I am unsure how. My current use case is to check if a user is authenticated and if not, redirect to a login view. I do not want to check before and push either ...

Using Ajax.BeginForm with ASP.NET MVC 3 Razor

Is there a tutorial or code example of using Ajax.BeginForm within Asp.net MVC 3 where unobtrusive validation and Ajax exist? This is an elusive topic for MVC 3, and I cannot seem to get my form to work properly. It will do an Ajax submit but ignore...

Create a date from day month and year with T-SQL

I am trying to convert a date with individual parts such as 12, 1, 2007 into a datetime in SQL Server 2005. I have tried the following: CAST(DATEPART(year, DATE)+'-'+ DATEPART(month, DATE) +'-'+ DATEPART(day, DATE) AS DATETIME) but this results in...

Python convert set to string and vice versa

Set to string. Obvious: >>> s = set([1,2,3]) >>> s set([1, 2, 3]) >>> str(s) 'set([1, 2, 3])' String to set? Maybe like this? >>> set(map(int,str(s).split('set([')[-1].split('])')[0].split(','))) set([1, 2, 3])...

Visual Studio: ContextSwitchDeadlock

I have been getting an error message that I can't resolve. It originates from Visual Studio or the debugger. I'm not sure whether the ultimate error condition is in VS, the debugger, my program, or the database. This is a Windows app. Not a web app...

How to Change Font Size in drawString Java

How to make the font size bigger in g.drawString("Hello World",10,10); ?...

Don't understand why UnboundLocalError occurs (closure)

What am I doing wrong here? counter = 0 def increment(): counter += 1 increment() The above code throws an UnboundLocalError....

QLabel: set color of text and background

How do I set color of text and background of a QLabel ?...

How do I prevent DIV tag starting a new line?

I want to output a single line of text to the browser that contains a tag. When this is rendered it appears that the DIV causes a new line. How can I include the content in the div tag on the same line - here is my code. <?php echo("<a hre...

Why should I use a container div in HTML?

I have noticed a common technique is to place a generic container div in the root of the body tag: <html> <head> ... </head> <body> <div id="container"> ... </div> </body> </html...

AngularJs .$setPristine to reset form

I been struggling to reset form once form is submitted. Someone posted this Here which I want to make it work but no success. Here is my My Code Example. $scope.form.$setPristine(); is not setting Pristine: {{user_form.$pristine}} to true. See examp...

Can't start Eclipse - Java was started but returned exit code=13

I am trying to get my first taste of Android development using Eclipse. I ran into this problem when trying to run Eclipse, having installed version 4.2 only minutes ago. After first trying to start Eclipse without any parameters to specify the Java...

window.close() doesn't work - Scripts may close only the windows that were opened by it

I'm having a problem always when I'm trying to close a window through the window.close() method of the Javascript, while the browser displays the below message on the console: "Scripts may close only the windows that were opened by it." This occur...

Gradle proxy configuration

I need web access from Gradle through a proxy server to use the Gradle/Artifactory integration for Jenkins. To reduce possible causes for issues, I manually add the Artifactory plugin in build.gradle and run it from command line: apply { apply f...

Explain the concept of a stack frame in a nutshell

It seems that I get the idea of call stack in programming language design. But I cannot find (probably, I just don't search hard enough) any decent explanation of what stack frame is. So I would like to ask someone to explain it to me in a few words...

How do I reset a sequence in Oracle?

In PostgreSQL, I can do something like this: ALTER SEQUENCE serial RESTART WITH 0; Is there an Oracle equivalent?...

How to get the absolute coordinates of a view

I'm trying to get the absolute screen pixel coordinates of the top left corner of a view. However, all methods I can find such as getLeft() and getRight() don't work as they all seem to be relative to the parent of the view, thus giving me 0. What is...

How to do something before on submit?

i have a form which has a button that submits the form. I need to do something before submits happen. I tried doing onClick on that button but it happens after the submit. I can't share the code but, generally, what should I do in jQuery or JS to ha...

Class is inaccessible due to its protection level

I have three classes. all are part of the same namespace. here are the basics of the three classes. //FBlock.cs namespace StubGenerator.PropGenerator { class FBlock : IDesignRegionInserts, IFormRegionInserts, IAPIRegionInserts, IConfigurationIn...

No notification sound when sending notification from firebase in android

I am sending push notification from firebase to my Android Application. but when my app is in background firebase onMessageReceived method is not called instead firebase send notification to system for showing notification in system tray. notificatio...

How to send 100,000 emails weekly?

How can one send an email to 100,000 users on a weekly basis in PHP? This includes mail to subscribers using the following providers: AOL G-Mail Hotmail Yahoo It is important that all e-mail actually be delivered, to the extent that it is possibl...

java.lang.ClassCastException

Normally whats the reason to get java.lang.ClassCastException ..? I get the following error in my application java.lang.ClassCastException: [Lcom.rsa.authagent.authapi.realmstat.AUTHw ...

Pass Method as Parameter using C#

I have several methods all with the same parameter types and return values but different names and blocks. I want to pass the name of the method to run to another method that will invoke the passed method. public int Method1(string) { // Do somet...

MySQL Error: : 'Access denied for user 'root'@'localhost'

$ ./mysqladmin -u root -p 'redacted' Enter password: mysqladmin: connect to server at 'localhost' failed error: 'Access denied for user 'root'@'localhost' (using password: YES)' How can I fix this?...

Why does "npm install" rewrite package-lock.json?

I just recently upgraded to npm@5. I now have a package-lock.json file with everything from package.json. I would expect that, when I run npm install that the dependency versions would be pulled from the lock file to determine what should be instal...

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

Write to custom log file from a Bash script

In Linux, I know how to write a simply message to the /var/log/messages file, in a simple shell script I created: #!/bin/bash logger "have fun!" I want to stop throwing messages into the default /var/log/messages file, and create my own. I tried ...

How do I use sudo to redirect output to a location I don't have permission to write to?

I've been given sudo access on one of our development RedHat linux boxes, and I seem to find myself quite often needing to redirect output to a location I don't normally have write access to. The trouble is, this contrived example doesn't work: sud...

The service cannot be started, either because it is disabled or because it has no enabled devices associated with it

I have SQL Server 2008 R2 inside Windows Server 2008. But when I tried to start the "SQL Server Browser" service, I got the following error: The service cannot be started, either because it is disabled or because it has no enabled devices associa...

Display only 10 characters of a long string?

How do I get a long text string (like a querystring) to display a maximum of 10 characters, using JQuery? Sorry guys I'm a novice at JavaScript & JQuery :S Any help would be greatly appreciated....

jQuery Find and List all LI elements within a UL within a specific DIV

I have 3 Columns of ULs each a Dynamic UL container that can have anywhere from 0-9 LI containers (eventually more). All my LI elements have an attribute "rel" which I am trying to ultimately find that attribute and use it for something else on all L...

How to include External CSS and JS file in Laravel 5

I am Using Laravel 5.0 , the Form and Html Helper are removed from this version , i dont know how to include external css and js files in my header file. Currently i am using this code. <link rel="stylesheet" href="/css/bootstrap.min.css"> <...

Deep copy an array in Angular 2 + TypeScript

I have an array of objects that is an input. Lets call it content. When trying to deep copy it, it still has a reference to the previous array. I need to duplicate that input array, and change one property of the duplicated part. So long I've tri...

Python - Module Not Found

I am a beginner with Python. Before I start, here's my Python folder structure -project ----src ------model --------order.py ------hello-world.py Under src I have a folder named model which has a Python file called order.py which contents follow: ...

Uncaught TypeError: Cannot read property 'appendChild' of null

I'm getting the following error Uncaught TypeError: Cannot read property 'appendChild' of null myRequest.onreadystatechange @ script.js:20 with my following code // index.html <html> <head> <title>Simple Pag...

Passing route control with optional parameter after root in express?

I'm working on a simple url-shortening app and have the following express routes: app.get('/', function(req, res){ res.render('index', { link: null }); }); app.post('/', function(req, res){ function makeRandom(){ var text = ""; va...

Recursive Lock (Mutex) vs Non-Recursive Lock (Mutex)

POSIX allows mutexes to be recursive. That means the same thread can lock the same mutex twice and won't deadlock. Of course it also needs to unlock it twice, otherwise no other thread can obtain the mutex. Not all systems supporting pthreads also su...

WAITING at sun.misc.Unsafe.park(Native Method)

One of my applications hangs under some period of running under load, does anyone know what could cause such output in jstack: "scheduler-5" prio=10 tid=0x00007f49481d0000 nid=0x2061 waiting on condition [0x00007f494e8d0000] java.lang.Thread.Stat...

How to add List<> to a List<> in asp.net

Is there a short way to add List<> to List<> instead of looping in result and add new result one by one? var list = GetViolations(VehicleID); var list2 = GetViolations(VehicleID2); list.Add(list2); ...

Maximum number of threads in a .NET app?

What is the maximum number of threads you can create in a C# application? And what happens when you reach this limit? Is an exception of some kind thrown?...

How do I download/extract font from chrome developers tools?

I have tired many things but i can't get it even though my computer has it. How can I access this wont files? They have the .woff extension. Double clicking them in chrome inspector just takes to some url. Which doesn't work. Nor this font is instal...

Send raw ZPL to Zebra printer via USB

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

What are some examples of commonly used practices for naming git branches?

I've been using a local git repository interacting with my group's CVS repository for several months, now. I've made an almost neurotic number of branches, most of which have thankfully merged back into my trunk. But naming is starting to become an...

Direct casting vs 'as' operator?

Consider the following code: void Handler(object o, EventArgs e) { // I swear o is a string string s = (string)o; // 1 //-OR- string s = o as string; // 2 // -OR- string s = o.ToString(); // 3 } What is the difference between the...

How to auto-indent code in the Atom editor?

How do you auto-indent your code in the Atom editor? In other editors you can usually select some code and auto-indent it. Is there a keyboard shortcut as well?...

How to add google-services.json in Android?

The error is: File google-services.json is missing from module root folder. The Google Quickstart Plugin cannot function without it. ...

How to Convert datetime value to yyyymmddhhmmss in SQL server?

How to convert datetime value to yyyymmddhhmmss? for example From 2014-04-17 13:55:12 To 20140417135512 ...

eval command in Bash and its typical uses

After reading the bash man pages and with respect to this post. I am still having trouble understanding what exactly the eval command does and which would be its typical uses. For example if we do: bash$ set -- one two three # sets $1 $2 $3 bash$ ...

How to use and style new AlertDialog from appCompat 22.1 and above

I am trying to migrate from default android AlertDialog to the new one included in appCompat-22.1 So far I understand you only have to import android.support.v7.app.AlertDialog package in order to use it. But how can I style it? For example change ...

Border around tr element doesn't show?

It seems like Chrome/Firefox do not render borders on tr, but it renders the border if the selector is table tr td. How can I set a border on a tr ? My try, which doesn't work: _x000D_ _x000D_ table tr {_x000D_ border: 1px solid black;_x000D_ }_...

What is the proper way to re-attach detached objects in Hibernate?

I have a situation in which I need to re-attach detached objects to a hibernate session, although an object of the same identity MAY already exist in the session, which will cause errors. Right now, I can do one of two things. getHibernateTemplate...

How to change button background image on mouseOver?

I have img1, and img2 in my resources. I have easily set btn.backgroundImage as img1 in btn properties. Images paths are: c:\Project\Resources... Now I don't know how to set btn.backgroundImage to be img2, I want to do it on event "MouseEnter". So I...

'uint32_t' does not name a type

I'm trying to compile a C++ software package that was written in 2007 and I'm getting this error: error: ‘uint32_t’ does not name a type This is happening in 64-bit Ubuntu using g++ 4.5.2. It compiles fine on 64-bit CentOS using g++ 4.1.2. Is ...

"ssl module in Python is not available" when installing package with pip3

I've install Python 3.4 and Python 3.6 on my local machine successfully, but am unable to install packages with pip3. When I execute pip3 install <package>, I get the following SSL related error: pip is configured with locations that requir...

What's the best way to convert a number to a string in JavaScript?

What's the "best" way to convert a number to a string (in terms of speed advantage, clarity advantage, memory advantage, etc) ? Some examples: String(n) n.toString() ""+n n+"" ...

What is the difference between `git merge` and `git merge --no-ff`?

Using gitk log, I could not spot a difference between the two. How can I observe the difference (with a git command or some tool)?...

How to Call a JS function using OnClick event

I am trying to call my JS function that I added in the header. Please find below code that shows my problem scenario. Note: I don't have access to the body in my application. Everytime I click on the element with id="Save" it only calls f1() but n...

Get the last item in an array

Here is my JavaScript code so far: var linkElement = document.getElementById("BackButton"); var loc_array = document.location.href.split('/'); var newT = document.createTextNode(unescape(capWords(loc_array[loc_array.length-2]))); linkElement.append...

Tensorflow set CUDA_VISIBLE_DEVICES within jupyter

I have two GPUs and would like to run two different networks via ipynb simultaneously, however the first notebook always allocates both GPUs. Using CUDA_VISIBLE_DEVICES, I can hide devices for python files, however I am unsure of how to do so withi...

Clang vs GCC for my Linux Development project

I'm in college, and for a project we're using C. We've explored GCC and Clang, and Clang appears to be much more user friendly than GCC. As a result, I'm wondering what the advantages or disadvantages are to using clang, as opposed to GCC, for devel...

Android: where are downloaded files saved?

I am trying to develop a "document manager" I have the necessity of accessing the files downloaded from the internet, from Gmail, for other mail clients, from other internet sources... I would like to understand where these files are stored exactly...

Spring: Why do we autowire the interface and not the implemented class?

Example interface IA { public void someFunction(); } @Resource(name="b") class B implements IA { public void someFunction() { //busy code block } public void someBfunc() { //doing b things } } @Resource(name="c") class C imp...

Best way to handle list.index(might-not-exist) in python?

I have code which looks something like this: thing_index = thing_list.index(thing) otherfunction(thing_list, thing_index) ok so that's simplified but you get the idea. Now thing might not actually be in the list, in which case I want to pass -1 as...

How to copy a char array in C?

In C, I have two char arrays: char array1[18] = "abcdefg"; char array2[18]; How to copy the value of array1 to array2 ? Can I just do this: array2 = array1?...

Import Script from a Parent Directory

How do I import a module(python file) that resides in the parent directory? Both directories have a __init__.py file in them but I still cannot import a file from the parent directory? In this folder layout, Script B is attempting to import Script ...

Delete duplicate elements from an array

For example, I have an array like this; var arr = [1, 2, 2, 3, 4, 5, 5, 5, 6, 7, 7, 8, 9, 10, 10] My purpose is to discard repeating elements from array and get final array like this; var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] How can this be ac...

Learning Regular Expressions

I don't really understand regular expressions. Can you explain them to me in an easy-to-follow manner? If there are any online tools or books, could you also link to them?...

How can I disable an <option> in a <select> based on its value in JavaScript?

I have a <select> with a number of <option>s. Each has a unique value. I need to disable an <option> with a given defined value (not innerhtml). Anyone have an idea how?...

How to send push notification to web browser?

I have been reading for past few hours about Push Notification API and Web Notification API. I also discovered that Google & Apple gives push notification service for free via GCM and APNS respectively. I am trying to understand if we can imple...

Received an invalid column length from the bcp client for colid 6

I want to bulk upload csv file data to sql server 2005 from c# code but I am encountering the below error - Received an invalid column length from the bcp client for colid 6. when bulk copy write to database server...

Depend on a branch or tag using a git URL in a package.json?

Say I've forked a node module with a bugfix and I want to use my fixed version, on a feature branch of course, until the bugfix is merged and released. How would I reference my fixed version in the dependencies of my package.json?...

Convert Json String to C# Object List

I want to convert a json string to a Object list. Please help me. it would be more helpful if done by NewtonJson. I tried, but its not working. I dont want all the values of that json. just which are mentioned in the MatrixModel This is a Object p...

How to find which columns contain any NaN value in Pandas dataframe

Given a pandas dataframe containing possible NaN values scattered here and there: Question: How do I determine which columns contain NaN values? In particular, can I get a list of the column names containing NaNs?...

Change background image opacity

I have a div element with text blocks and a parent div in which I have set a background image. Now I want to reduce the opacity of the background image. Please suggest how I can do that. Thanks in advance. EDIT: I am looking to change the way my ...

Java out.println() how is this possible?

I've seen some code such as: out.println("print something"); I tried import java.lang.System; but it's not working. How do you use out.println() ?...

jQuery: how to trigger anchor link's click event

I have a anchor link like <a id="myanchor" href="http://google.com" target="_blank">Google</a> How to open href target in a new tab programatically?...

how to rename an index in a cluster?

I need to rename several indexes in a cluster (their name must be changed, I cannot use aliases). I saw that there are no supported ways to do that, the closest I found is to rename the directory of the index, I tried this in a cluster. The cluster...

Numpy array dimensions

I'm currently trying to learn Numpy and Python. Given the following array: import numpy as np a = np.array([[1,2],[1,2]]) Is there a function that returns the dimensions of a (e.g.a is a 2 by 2 array)? size() returns 4 and that doesn't help very ...

Calling a function in jQuery with click()

In the code below, why does the open function work but the close function does not? $("#closeLink").click("closeIt"); How do you just call a function in click() instead of defining it in the click() method? <script type="text/javascript"> ...

how to remove key+value from hash in javascript

Given var myHash = new Array(); myHash['key1'] = { Name: 'Object 1' }; myHash['key2'] = { Name: 'Object 2' }; myHash['key3'] = { Name: 'Object 3' }; How do I remove key2, and object 2 from the hash, so that it ends up in a state as if I did: var ...

Change background color for selected ListBox item

This is my XAML so far. <ScrollViewer Grid.Column="1" Grid.RowSpan="2"> <ListBox Background="Black" ItemsSource="{Binding Path=ActiveLog}" > <ListBox.ItemTemplate> &...

jQuery - how to write 'if not equal to' (opposite of ==)

I need to reverse of the following code. How can I make the animation run if the width is NOT 500px. $(".image-div").not(this).each(function() { if ($(this).css('width') == '500px') { $(this).animate({ width:...

Jquery open popup on button click for bootstrap

When i click below button <button class="btn btn-primary btn-lg" data-toggle="modal" data-target="#myModal"> Launch demo modal </button> I open below popup(modal) <!-- Modal --> <div class="modal fade" id="myM...

System.Data.OracleClient requires Oracle client software version 8.1.7

I have a web site that I developed on Vista using Vb.net9. It makes a connection to Oracle. for the connection I use System.Data.OracleClient. It works fine on my machine, and our test server, but it does not work on the production server. We ins...

google map API zoom range

I am using google map API version-3 , I was trying with different zoom value, I have randomly done for some numbers started with 1 upto 100 , map gets zoom in for increasing numbers but some level giving same result, I mean I am getting same zoom for...

How to replace an entire line in a text file by line number

I have a situation where I want a bash script to replace an entire line in a file. The line number is always the same, so that can be a hard-coded variable. I'm not trying to replace some sub-string in that line, I just want to replace that line ent...

NumPy ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

I was calculating eigenvectors and eigenvalues of a matrix in NumPy and just wanted to check the results via assert(). This would throw a ValueError that I don't quite understand, since printing those comparisons works just fine. Any tips how I could...

How can I detect if a selector returns null?

What is the best way to detect if a jQuery-selector returns an empty object. If you do: alert($('#notAnElement')); you get [object Object], so the way I do it now is: alert($('#notAnElement').get(0)); which will write "undefined", and so you ca...

How to use http.client in Node.js if there is basic authorization

As per title, how do I do that? Here is my code: var http = require('http'); // to access this url I need to put basic auth. var client = http.createClient(80, 'www.example.com'); var request = client.request('GET', '/', { 'host': 'www.examp...

Merging arrays with the same keys

In a piece of software, I merge two arrays with array_merge function. But I need to add the same array (with the same keys, of course) to an existing array. The problem: $A = array('a' => 1, 'b' => 2, 'c' => 3); $B = array('c' => 4, '...

Python, how to check if a result set is empty?

I have a sql statement that returns no hits. For example, 'select * from TAB where 1 = 2'. I want to check how many rows are returned, cursor.execute(query_sql) rs = cursor.fetchall() Here I get already exception: "(0, 'No result set')" How c...

How do I round to the nearest 0.5?

I have to display ratings and for that i need increments as follows: If the number is 1.0 it should be equal to 1 If the number is 1.1 should be equal to 1 If the number is 1.2 should be equal to 1 If the number is 1.3 should be equal to 1.5 If ...

How to make a vertical line in HTML

How do you make a vertical line using HTML?...

How to compare only date in moment.js

I am new to moment.js. I have a date object and it has some time associated with it. I just want to check if that date is greater than or equal to today's date, excluding the time when comparing. var dateToCompare = 2015-04-06T18:30:00.000Z I jus...

pandas: to_numeric for multiple columns

I'm working with the following df: c.sort_values('2005', ascending=False).head(3) GeoName ComponentName IndustryId IndustryClassification Description 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014...

Find empty or NaN entry in Pandas Dataframe

I am trying to search through a Pandas Dataframe to find where it has a missing entry or a NaN entry. Here is a dataframe that I am working with: cl_id a c d e A1 A2 A3 0 1 ...

How to stick a footer to bottom in css?

I am having the classic problem for the positioning of a Footer on the bottom of the browser. I've tried methods including http://ryanfait.com/resources/footer-stick-to-bottom-of-page/ but to no good result: my footer always keeps appearing in the mi...

Calculate time difference in minutes in SQL Server

I need the time difference between two times in minutes. I am having the start time and end time as shown below: start time | End Time 11:15:00 | 13:15:00 10:45:00 | 18:59:00 I need the output for first row as 45,60,15 which correspond...

How can I pass a reference to a function, with parameters?

Possible Duplicate: How can I pre-set arguments in JavaScript function call? (Partial Function Application) I need to able to pass a reference to a function with a given set of parameters. Here is an example of passing a reference without...

How to make a circle around content using CSS?

Like this With only this code <span>1</span> ...

java.lang.VerifyError: Expecting a stackmap frame at branch target JDK 1.7

After upgrading to JDK 1.7 I am getting below exception: java.lang.VerifyError: Expecting a stackmap frame at branch target 71 in method com.abc.domain.myPackage.MyClass$JaxbAccessorM_getDescription_setDescription_java_lang_String.get(Ljava/lang/Obj...

What is the most efficient way to create HTML elements using jQuery?

Recently I've been doing a lot of modal window pop-ups and what not, for which I used jQuery. The method that I used to create the new elements on the page has overwhelmingly been along the lines of: $("<div></div>"); However, I'm get...

How do I get the directory from a file's full path?

What is the simplest way to get the directory that a file is in? I'm using this to set a working directory. string filename = @"C:\MyDirectory\MyFile.bat"; In this example, I should get "C:\MyDirectory"....

How to resolve "The requested URL was rejected. Please consult with your administrator." error?

I have a ASP application. On click of a particular link, some VB scripts are executed and an ASP page is to be shown, but instead I get a screen that says: Information Not Available. The requested URL was rejected. Please consult with your admi...

What to do on TransactionTooLargeException

I got a TransactionTooLargeException. Not reproducible. In the docs it says The Binder transaction failed because it was too large. During a remote procedure call, the arguments and the return value of the call are transferred as Parcel objects stor...

How to display a Yes/No dialog box on Android?

Yes, I know there's AlertDialog.Builder, but I'm shocked to know how difficult (well, at least not programmer-friendly) to display a dialog in Android. I used to be a .NET developer, and I'm wondering is there any Android-equivalent of the following...

jQuery to retrieve and set selected option value of html select element

I am attempting to retrieve and set the selected value of a select element (drop down list) with jQuery. for retrievel i have tried $("#myId").find(':selected').val(), as well as $("#myId").val() but both return undefined. Any insight into this...

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

When is assembly faster than C?

One of the stated reasons for knowing assembler is that, on occasion, it can be employed to write code that will be more performant than writing that code in a higher-level language, C in particular. However, I've also heard it stated many times tha...

Split string to equal length substrings in Java

How to split the string "Thequickbrownfoxjumps" to substrings of equal size in Java. Eg. "Thequickbrownfoxjumps" of 4 equal size should give the output. ["Theq","uick","brow","nfox","jump","s"] Similar Question: Split string into equal-length sub...

How to Convert date into MM/DD/YY format in C#

In My Asp.net webpage I need to display today's date into one of the textbox , so in my form load I wrote the following code textbox1.text = System.DateTime.Today.ToShortDateString(); this line is giving me date like 1/7/09 but I want date like...

How do I include a path to libraries in g++

I am trying to include the path to extra libraries in my makefile, but I can't figure out how to get the compiler to use that path. so far I have: g++ -g -Wall testing.cpp fileparameters.cpp main.cpp -o test and I want to include the path to /da...

Print string to text file

I'm using Python to open a text document: text_file = open("Output.txt", "w") text_file.write("Purchase Amount: " 'TotalAmount') text_file.close() I want to substitute the value of a string variable TotalAmount into the text document. Can someon...

How to rename a component in Angular CLI?

Is there any shortcut to rename a component with the Angular CLI other than manually editing all the component files such as folder name, .css, .ts, spec.ts and app.module.ts? ...

How to linebreak an svg text within javascript?

So here is what I have: <path class="..." onmousemove="show_tooltip(event,'very long text \\\n I would like to linebreak')" onmouseout="hide_tooltip()" d="..."/> <rect class="tooltip_bg" id="tooltip_bg" ... /> <text class="toolt...

RE error: illegal byte sequence on Mac OS X

I'm trying to replace a string in a Makefile on Mac OS X for cross-compiling to iOS. The string has embedded double quotes. The command is: sed -i "" 's|"iphoneos-cross","llvm-gcc:-O3|"iphoneos-cross","clang:-Os|g' Configure And the error is: sed...

Printing one character at a time from a string, using the while loop

Im reading "Core Python Programming 2nd Edition", They ask me to print a string, one character at a time using a "while" loop. I know how the while loop works, but for some reason i can not come up with an idea how to do this. I've been looking arou...

Difference between long and int data types

Considering that the following statements return 4, what is the difference between the int and long types in C++? sizeof(int) sizeof(long) ...

How to print variables without spaces between values

I would like to know how to remove additional spaces when I print something. Like when I do: print 'Value is "', value, '"' The output will be: Value is " 42 " But I want: Value is "42" Is there any way to do this?...

CSS:Defining Styles for input elements inside a div

I have a div called "divContainer" inside which i have few input elements like textboxes,radio buttons et.. How can i define the style for then in the CSS ? I wanna mention styles for elements inside this purticular div.not for the entire form. Ex:...

What is the best way to implement a "timer"?

What is the best way to implement a timer? A code sample would be great! For this question, "best" is defined as most reliable (least number of misfires) and precise. If I specify an interval of 15 seconds, I want the target method invoked every 15 s...

How to auto-size an iFrame?

Possible Duplicate: Resizing an iframe based on content I'm loading an iFrame and want the parent to automatically change the height based upon the height of the iFrame's content. To simply things, all pages belong to the same domain, so ...

Print to standard printer from Python?

Is there a reasonably standard and cross platform way to print text (or even PS/PDF) to the system defined printer? Assuming CPython here, not something clever like using Jython and the Java printing API....

How can I select from list of values in Oracle

I am referring to this stackoverflow answer: How can I select from list of values in SQL Server How could something similar be done in Oracle? I've seen the other answers on this page that use UNION and although this method technically works, it's no...

Remove empty array elements

Some elements in my array are empty strings based on what the user has submitted. I need to remove those elements. I have this: foreach($linksArray as $link) { if($link == '') { unset($link); } } print_r($linksArray); But it do...

JSON.Parse,'Uncaught SyntaxError: Unexpected token o

I am having trouble with JSON returned from a web service. It looks like the JSON lacks quotes, but when I add quotes to the JSON, I get an error. Here is the error message: 'Uncaught SyntaxError: Unexpected token o. When I log the string to console:...

C# : Out of Memory exception

Today my application threw an OutOfMemoryException. To me this was always almost impossible since I have 4GB RAM and a lot of virtual memory too. The error happened when I tried to add an existing collection to a new list. List<Vehicle> vList =...

How to copy an object by value, not by reference

I want to make a copy of an object, then after some logic, re-assign the original object the value of the copy. example: User userCopy = //make a copy foreach(...) { user.Age = 1; user.ID = -1; UserDao.Update(user) user = userCopy; } ...

Can not deserialize instance of java.util.ArrayList out of START_OBJECT token

I'm trying to POST a List of custom objects. My JSON in request body is this: { "collection": [ { "name": "Test order1", "detail": "ahk ks" }, { "name": "Test order2", "det...

How do I undo a checkout in git?

I just checked out an earlier commit from my local git repo. I haven't made any changes to it, I was just looking at it. Now I want to go back to my latest commit - how do I do that? The exact command I used to check it out: git checkout e5dff6b3c5...

How do I sort a VARCHAR column in SQL server that contains numbers?

I have a VARCHAR column in a SQL Server 2000 database that can contain either letters or numbers. It depends on how the application is configured on the front-end for the customer. When it does contain numbers, I want it to be sorted numerically, e...

How to change column datatype from character to numeric in PostgreSQL 8.4

I am using following query: ALTER TABLE presales ALTER COLUMN code TYPE numeric(10,0); to change the datatype of a column from character(20) to numeric(10,0) but I am getting the error: column "code" cannot be cast to type numeric ...

SQL Server - boolean literal?

How to write literal boolean value in SQL Server? See sample use: select * from SomeTable where PSEUDO_TRUE another sample: if PSEUDO_TRUE begin select 'Hello, SQL!' end Note: The query above has nothing to do with how I'm going to use it. I...

How can I know which radio button is selected via jQuery?

I have two radio buttons and want to post the value of the selected one. How can I get the value with jQuery? I can get all of them like this: $("form :radio") How do I know which one is selected?...

How to inject JPA EntityManager using spring

Is it possible to have Spring inject the JPA entityManager object into my DAO class without extending JpaDaoSupport? If yes, does Spring manage the transaction in this case? I'm trying to keep my Spring configuration as simple as possible: <bean...

HAX kernel module is not installed

I have just downloaded latest android studio from official android site and installed it. But I am getting this error instead of having Intel X 86 Emulator accelerator. What can cause this error emulator: ERROR: x86 emulation currently requires hard...

Using bind variables with dynamic SELECT INTO clause in PL/SQL

I have a question regarding where bind variables can be used in a dynamic SQL statement in PL/SQL. For example, I know that this is valid: CREATE OR REPLACE FUNCTION get_num_of_employees (p_loc VARCHAR2, p_job VARCHAR2) RETURN NUMBER IS v_query_...

Redirecting to a relative URL in JavaScript

I have a problem: I want to redirect via JavaScript to a directory above. My code: location.href = (location.href).substr(0, (location.href).lastIndexOf('folder')); The URL looks like this: example.com/path/folder/index.php?file=abc&test=1...

Using an index to get an item, Python

I have a tuple in python ('A','B','C','D','E'), how do I get which item is under a particular index number? Example: Say it was given 0, it would return A. Given 2, it would return C. Given 4, it would return E....

how to set default main class in java?

I have 2 classes within same package. Both classes have main method in them. Now I want to build a jar file. I want to build 2 jar files which use different main functions as default main. eg class A { public static void main(String args[]) ...

Fixed digits after decimal with f-strings

Is there an easy way with Python f-strings to fix the number of digits after the decimal point? (Specifically f-strings, not other string formatting options like .format or %) For example, let's say I want to display 2 digits after the decimal place...

How to update Ruby to 1.9.x on Mac?

I have created a new user account on my mac and I am trying to update to the current version of ruby on it (1.9.2) from the snow leopard default of 1.8.7. Can somebody point me to tutorial or explain the best method to update Ruby on my mac from 1.8 ...

Remove all files in a directory

Trying to remove all of the files in a certain directory gives me the follwing error: OSError: [Errno 2] No such file or directory: '/home/me/test/*' The code I'm running is: import os test = "/home/me/test/*" os.remove(test) ...

What is 0x10 in decimal?

I have the following code: SN.get_Chars(5) SN is a string so this should give the 5th Char. Ok! Now I have another code but: SN.get_Chars(0x10) I wonder what 0x10 is? Is it a number? If it's so, then what is it in decimal notation?...

How do I grep for all non-ASCII characters?

I have several very large XML files and I'm trying to find the lines that contain non-ASCII characters. I've tried the following: grep -e "[\x{00FF}-\x{FFFF}]" file.xml But this returns every line in the file, regardless of whether the line contai...

Get refresh token google api

I can't get my refresh token with my code. I can only get my access token, token type etc., I have followed some tutorials like putting access_type=offline on my login URL: echo "<a href='https://accounts.google.com/o/oauth2/auth?" . "access...

How to tell if JRE or JDK is installed

I have one computer that I intentionally installed JDK on. I have another computer with JRE, for, among other things, testing. However, when I got a java application working on this computer, and then tried it on another, it complained that JDK was r...

Google Maps API: open url by clicking on marker

I want to open a new window by clicking on a marker using Google Maps API 3. Unfortunately there are not many examples for the Google Maps API and I found out this code: google.maps.event.addListener(marker, 'click', function() { window.locatio...

What is a handle in C++?

I have been told that a handle is sort of a pointer, but not, and that it allows you to keep a reference to an object, rather than the object itself. What is a more elaborate explanation?...

How to get selenium to wait for ajax response?

How can I get selenium to wait for something like a calendar widget to load? Right now I am just doing a Thread.sleep(2500) after exporting the testcase to a junit program....

CGRectMake, CGPointMake, CGSizeMake, CGRectZero, CGPointZero is unavailable in Swift

After converting code to latest swift 3.0 I am shown this error. Also tell me solution for CGSize = CGSizeMake(0,0) static var frameAtStartOfPan: CGRect = CGRectZero static var startPointOfPan: CGPoint = CGPointZero Which is also unavailable....

How do I use a third-party DLL file in Visual Studio C++?

I understand that I need to use LoadLibrary(). But what other steps do I need to take in order to use a third-party DLL file? I simply jumped into C++ and this is the only part that I do not get (as a Java programmer). I am just looking into how I c...

How to get the version of ionic framework?

I wonder how to check the version of ionic. If I do ionic -v I get back 1.4.3 Can that be? Wasn't 1.0.0 just released?...

Controller 'ngModel', required by directive '...', can't be found

What's going on here? Here is my directive: app.directive('submitRequired', function (objSvc) { return { require: 'ngModel', link: function (scope, elm, attrs, ctrl) { // do something } }; }); Here is an...

How do you obtain a Drawable object from a resource id in android package?

I need to get a Drawable object to display on an image button. Is there a way to use the code below (or something like it) to get an object from the android.R.drawable.* package? for example if drawableId was android.R.drawable.ic_delete mContext.g...

MySQL > Table doesn't exist. But it does (or it should)

I changed the datadir of a MySQL installation and all the bases moved correctly except for one. I can connect and USE the database. SHOW TABLES also returns me all the tables correctly, and the files of each table exists on the MySQL data directory....

Determine the number of NA values in a column

I want to count the number of NA values in a data frame column. Say my data frame is called df, and the name of the column I am considering is col. The way I have come up with is following: sapply(df$col, function(x) sum(length(which(is.na(x))))) ...

How do I exit the results of 'git diff' in Git Bash on windows?

I'm using Git Bash on Windows 7. When I run git diff, I see this: However, I'm unable to get back to a regular prompt. Pressing Ctrl+C seems to work, but as soon as I start typing a command, it's covered up with (END) as in that image....

How to change the port number for Asp.Net core app?

I added the following section in project.json. "commands": { "run": "run server.urls=http://localhost:8082", "web": "Microsoft.AspNet.Hosting --server Microsoft.AspNet.Server.Kestrel --server.urls http://localhost:8082", "weblistener":...

Possible reason for NGINX 499 error codes

I'm getting a lot of 499 NGINX error codes. I see that this is a client side issue. It is not a problem with NGINX or my uWSGI stack. I note the correlation in uWSGI logs when a get a 499. address space usage: 383692800 bytes/365MB} {rss usage: ...

How to query first 10 rows and next time query other 10 rows from table

I have more than 500 rows with in my Database Table with particular date. To query the rows with particular date. select * from msgtable where cdate='18/07/2012' This returns 500 rows. How to query these 500 rows by 10 rows step by step. Query...

How to remove the underline for anchors(links)?

Is there anyway (in CSS) to avoid the underline for the text and links introduced in the page .. ?...

how to show calendar on text box click in html

In html i want to show calendar to select date while clicking a text box. then we select a date from that calendar then the selected date will be display in that text box....

HTML colspan in CSS

I'm trying to construct a layout similar to the following: +---+---+---+ | | | | +---+---+---+ | | +-----------+ where the bottom is filling the space of the upper row. If this were an actual table, I could easily accomplish this ...

Full width layout with twitter bootstrap

I'm trying to accomplish a layout similar to this one: http://dribbble.com/shots/829195-Slate/attachments/86422 My project uses Twitter Bootstrap with responsive design. It is possible to implement a full width layout with Bootstrap? The issue is ...

'Missing recommended icon file - The bundle does not contain an app icon for iPhone / iPod Touch of exactly '120x120' pixels, in .png format'

I submitted an app update, but I have received an email telling me this error has occurred: Missing recommended icon file - The bundle does not contain an app icon for iPhone / iPod Touch of exactly '120x120' pixels, in .png format How can I fi...

MySQL Update Inner Join tables query

I have no idea what the problem is. Using MySQL 5.0 I get a compile error when attempting to run the following MySQL update query: UPDATE b SET b.mapx = g.latitude, b.mapy = g.longitude FROM business AS b INNER JOIN business_geocode g ON b.busin...

Cannot uninstall angular-cli

I've tried several times to uninstall my angular-cli in order to update it but even if I follow the instructions provided on github: npm uninstall -g @angular/cli npm cache clean npm install -g @angular/cli@latest When I check using the command n...

Java2D: Increase the line width

I want to increase the Line2D width. I could not find any method to do that. Do I need to actually make a small rectangle for this purpose?...

Is there a way to detach matplotlib plots so that the computation can continue?

After these instructions in the Python interpreter one gets a window with a plot: from matplotlib.pyplot import * plot([1,2,3]) show() # other code Unfortunately, I don't know how to continue to interactively explore the figure created by show() w...

JavaScript dictionary with names

I want to create a dictionary in JavaScript like the following: myMappings = [ { "Name": 10%}, { "Phone": 10%}, { "Address": 50%}, { "Zip": 10%}, { "Comments": 20%} ] I want to po...

Send email from localhost running XAMMP in PHP using GMAIL mail server

I try to send an email from localhost to my yahoo email account using php mail() function, the return says I successfully send the email but I did not get any email. I've been reading and trying many so called 'simple way' to send email but the resul...

Generating a list of pages (not posts) without the index file

I am using Jekyll as a static generator for a website (not a blog), and I want to have an automatically generated list of all pages on my index page. I get that to work with the following code for the sidebar.html file: <ul> {% for page in s...

Remove blank lines with grep

I tried grep -v '^$' in Linux and that didn't work. This file came from a Windows file system....

python-pandas and databases like mysql

The documentation for Pandas has numerous examples of best practices for working with data stored in various formats. However, I am unable to find any good examples for working with databases like MySQL for example. Can anyone point me to links or ...

Select option padding not working in chrome

Select option padding not working in chrome <style> select option { padding:5px 0px; } </style> <select> <option>1</option> <option>2</option> <option>3</option> </select> ...

Disable browser's back button

How to disable browser's BACK Button (across browsers)?...

How to find difference between two Joda-Time DateTimes in minutes

Below is the method I wrote: public List<Map<String, Object>> loadNotYetInEmployee(int shift, Date date, int transitionVal, String type, User user) { DateTime datetime = new DateTime(date); datetime = datetime ...

How can I set / change DNS using the command-prompt at windows 8

How can I set my DNS settings using the command-prompt or bat file at windows 8 I tried this: netsh interface ip set dns name="Local Area Connection" source=static addr=none but not worked....

Multiple file-extensions searchPattern for System.IO.Directory.GetFiles

What is the syntax for setting multiple file-extensions as searchPattern on Directory.GetFiles()? For example filtering out files with .aspx and .ascx extensions. // TODO: Set the string 'searchPattern' to only get files with // the extension '.aspx...

Best XML parser for Java

I need to read smallish (few MB at the most, UTF-8 encoded) XML files, rummage around looking at various elements and attributes, perhaps modify a few and write the XML back out again to disk (preferably with nice, indented formatting). What would b...

window.print() not working in IE

I am doing something like this in javascript to print a section of my page on click of a link function printDiv() { var divToPrint = document.getElementById('printArea'); var newWin = window.open(); newWin.document.write(divToPrint.innerHTML); n...

Proper way to concatenate variable strings

I need to create new variable from contents of other variables. Currently I'm using something like this: - command: echo "{{ var1 }}-{{ var2 }}-{{ var3 }}" register: newvar The problem is: Usage of {{ var1 }}...{{ varN }} brings too long strin...

How to debug Apache mod_rewrite

I have two main problems with mod_rewrite: 1) There is no meaningful error reported when I have an invalid rule 2) To reliably test each modification, I have to erase chrome's cache. This isn't rocket science, but I have to hit Ctrl+Shift+Delete ...

Switching to landscape mode in Android Emulator

This is probably a pretty easy to answer question, but I can't find the solution myself after a couple hours of searching the documentation and Google. I set the orientation of my Android app to landscape in the AndroidManifest.xml file: android:scr...

UITableView - change section header color

How can I change color of a section header in UITableView? EDIT: The answer provided by DJ-S should be considered for iOS 6 and above. The accepted answer is out of date....

Calculating Waiting Time and Turnaround Time in (non-preemptive) FCFS queue

I have 6 processes as follows: -- P0 -- arrival time = 0 burst time = 10 -- P1 -- arrival time = 110 burst time = 210 -- P2 -- arrival time = 130 burst time = 70 -- P3 -- arrival time = 130 burst time = 70 -- P4 -- ar...

FFmpeg on Android

I have got FFmpeg compiled (libffmpeg.so) on Android. Now I have to build either an application like RockPlayer or use existing Android multimedia framework to invoke FFmpeg. Do you have steps / procedures / code / example on integrating FFmpeg on ...

How to prevent buttons from submitting forms

In the following page, with Firefox the remove button submits the form, but the add button does not. How do I prevent the remove button from submitting the form? _x000D_ _x000D_ function addItem() { var v = $('form :hidden:last').attr('name'); va...

How to get current value of RxJS Subject or Observable?

I have an Angular 2 service: import {Storage} from './storage'; import {Injectable} from 'angular2/core'; import {Subject} from 'rxjs/Subject'; @Injectable() export class SessionStorage extends Storage { private _isLoggedInSource = new Subject...

Number of days between past date and current date in Google spreadsheet

I want to calculate the number of days passed between past date and a current date. My past date is in the format dd/mm/yyyy format. I have used below mentioned formulas but giving the proper output. =DAYS360(A2,TODAY()) =MINUS(D2,TODAY()) In the ...

MSBUILD : error MSB1008: Only one project can be specified

Why am I getting the following Build error? C:\WINDOWS\Microsoft.NET\Framework\v3.5\msbuild.exe C:\Code\EduBenesysNET\EduBenesysNET\EduBenesysNET.vbproj /t:publish /p:Configuration=Release /p:Platform=AnyCPU /v:detailed /p:PublishDir="\\BSIIS3\c$\DA...

IIS 7, HttpHandler and HTTP Error 500.21

On IIS 7, I'm trying to use custom HttpHandler for my ASP.NET web application. I use pipeline mode "classic", .NET version is 4.0.30319, my web.config configuration for the handler is: <system.webServer> <handlers> <add name="MyH...

How to specify jackson to only use fields - preferably globally

Default jackon behaviour seems to use both properties (getters and setters) and fields to serialize and deserialize to json. I would like to use the fields as the canonical source of serialization config and thus don't want jackson to look at proper...

Error: The type exists in both directories

In a MVC2 project I moved a file from App_code to Content folder and compiled it. Then move it back again to App_Code and then changed its Build Action to "Compile". Now I get this error and I don't know how to fix this to make my program work again:...

Referring to a Column Alias in a WHERE Clause

SELECT logcount, logUserID, maxlogtm , DATEDIFF(day, maxlogtm, GETDATE()) AS daysdiff FROM statslogsummary WHERE daysdiff > 120 I get "invalid column name daysdiff". Maxlogtm is a datetime field. It's the little stuff that drives me ...

Convert line endings

I have been using d2u to convert line endings. After installing Puppy Linux I noticed that it does not come with d2u, but dos2unix. Then I noticed that Ubuntu is missing both by default. What is another way to convert line endings?...

What is the equivalent of "!=" in Excel VBA?

The problem is that != does not work as a function in excel vba. I want to be able to use If strTest != "" Then instead of If strTest = "" Then Is there another approach to do this besides !=? My function to mimic != is Sub test() Dim intTest...

Changing SQL Server collation to case insensitive from case sensitive?

I've recently installed SQL Server 2008 and I selected collation as case sensitive. I want to make it case insensitive for the entire instance (not for a database in that instance). If I change the collation does it affect any existing databases? if ...

How to encrypt and decrypt String with my passphrase in Java (Pc not mobile platform)?

I want to encrypt a string and then put it on a file. Also want to decrypt it when I want. I don’t need very strong security. I just want to make it harder to get my data others. I tried several ways. Here are these. Md5 Encryption: How to hash...

NSDate get year/month/day

How can I get the year/month/day of a NSDate object, given no other information? I realize that I could probably do this with something similar to this: NSCalendar *cal = [[NSCalendar alloc] init]; NSDateComponents *components = [cal components:0 fr...

Remove multiple objects with rm()

My memory is getting clogged by a bunch of intermediate files (call them temp1, temp2, etc.). and I would like to know if it is possible to remove them from memory without doing repeated rm calls (i.e. rm(temp1), rm(temp2))? I tried rm(list(temp1, te...

Converting HTML files to PDF

I need to automatically generate a PDF file from an exisiting (X)HTML-document. The input files (reports) use a rather simple, table-based layout, so support for really fancy JavaScript/CSS stuff is probably not needed. As I am used to working in Ja...

commandButton/commandLink/ajax action/listener method not invoked or input value not set/updated

Sometimes, when using <h:commandLink>, <h:commandButton> or <f:ajax>, the action, actionListener or listener method associated with the tag are simply not being invoked. Or, the bean properties are not updated with submitted UIInput...

Closing a file after File.Create

I check to see if a file exists with if(!File.Exists(myPath)) { File.Create(myPath); } However, when I go to create a StreamReader with this newly created file, I get an error saying that The process cannot access the file '[my file path ...

GetType used in PowerShell, difference between variables

What is the difference between variables $a and $b? $a = (Get-Date).DayOfWeek $b = Get-Date | Select-Object DayOfWeek I tried to check $a.GetType $b.GetType MemberType : Method OverloadDefinitions : {type GetType()} TypeNameOfValue ...

How to extract this specific substring in SQL Server?

I have a string with a specific pattern: 23;chair,red [$3] i.e., a number followed by a semicolon, then a name followed by a left square bracket. Assuming the semicolon ; always exists and the left square bracket [ always exists in the string, ho...

Scala list concatenation, ::: vs ++

Is there any difference between ::: and ++ for concatenating lists in Scala? scala> List(1,2,3) ++ List(4,5) res0: List[Int] = List(1, 2, 3, 4, 5) scala> List(1,2,3) ::: List(4,5) res1: List[Int] = List(1, 2, 3, 4, 5) scala> res0 == res1 ...

Eloquent ORM laravel 5 Get Array of ids

I'm using Eloquent ORM laravel 5.1, i want to return an array of ids greater than 0, My model called test. I have tried : $test=test::select('id')->where('id' ,'>' ,0)->get()->toarray(); It return : Array ( [0] => Array ( [id] =&g...

how to kill the tty in unix

This is the result of the finger command (Today(Monday) when I (Vidya) logged in) sekic1083 [6:14am] [/home/vidya] -> finger Name Tty Idle Login Time Where Felix pts/0 - Thu 10:06 sekic2594.rnd.ki.sw. john ...

How do I render a Word document (.doc, .docx) in the browser using JavaScript?

I have successfully done code to display a PDF file in the browser instead of the "Open/Save" dialog. Now, I'm stuck trying to display a Word document in the browser. I want to display a Word document in Firefox, IE7+, Chrome etc. Can any one help? ...

Android webview & localStorage

I have a problem with a webview which may access to the localStorage by an HTML5 app. The test.html file informs me that local storage is'nt supported by my browser (ie. the webview). If you have any suggestion.. package com.test.HelloWebView; im...

Printing Mongo query output to a file while in the mongo shell

2 days old with Mongo and I have a SQL background so bear with me. As with mysql, it is very convenient to be in the MySQL command line and output the results of a query to a file on the machine. I am trying to understand how I can do the same with M...

Iterate two Lists or Arrays with one ForEach statement in C#

This just for general knowledge: If I have two, let's say, List, and I want to iterate both with the same foreach loop, can we do that? Edit Just to clarify, I wanted to do this: List<String> listA = new List<string> { "string", "stri...

How to transform currentTimeMillis to a readable date format?

I want to use currentTimeMillis twice so I can calculate a duration but I also want to display Time and Date in user readable format. I'm having trouble as currentTimeMillis is good for the calculation but I can't see a built in function to convert t...

How to convert image to byte array

Can anybody suggest how I can convert an image to a byte array and vice versa? I'm developing a WPF application and using a stream reader....

utf-8 special characters not displaying

I moved my website from my local test server to NameCheap shared hosting and now I'm running into a problem - some of the pages aren't displaying utf-8 special characters properly (showing question marks instead). All pages are utf-8 encoded, as are ...

How to display pandas DataFrame of floats using a format string for columns?

I would like to display a pandas dataframe with a given format using print() and the IPython display(). For example: df = pd.DataFrame([123.4567, 234.5678, 345.6789, 456.7890], index=['foo','bar','baz','quux'], co...

Importing text file into excel sheet

I'm writing a VBA code which supposed to delete the data on a selected excel sheet, open a dialog box for text file selection, and then import the data from that text file to the same exact sheet I've deleted the data from. So far I can only open the...

Spring Boot Configure and Use Two DataSources

How can I configure and use two data sources? For example here is what I have for the first data source: application.properties #first db spring.datasource.url = [url] spring.datasource.username = [username] spring.datasource.password = [password]...

tar: add all files and directories in current directory INCLUDING .svn and so on

I try to tar.gz a directory and use tar -czf workspace.tar.gz * The resulting tar includes .svn directories in subdirs but NOT in the current directory (as * gets expanded to only 'visible' files before it is passed to tar I tried to tar -czf w...

Can attributes be added dynamically in C#?

Is it possible to add attributes at runtime or to change the value of an attribute at runtime?...

Android Color Picker

I am looking for a Color Picker framework which can return color HEX on selection. I have looked at this wondering if there is some other library I can use....

Downloading Java JDK on Linux via wget is shown license page instead

When I try to download Java from Oracle I instead end up downloading a page telling me that I need agree to the OTN license terms. Sorry! In order to download products from Oracle Technology Network you must agree to the OTN license terms. ...

Append a tuple to a list - what's the difference between two ways?

I wrote my first "Hello World" 4 months ago. Since then, I have been following a Coursera Python course provided by Rice University. I recently worked on a mini-project involving tuples and lists. There is something strange about adding a tuple into ...

Get text from DataGridView selected cells

I have a DataGridView with cells from a database file that contains data. Basically, I want to get the text from the selected cells in the DataGridView and display it in a textbox at the click of the button. The code for the button click event is: P...

$(this).val() not working to get text from span using jquery

Giving this html, i want to grab "August" from it when i click on it: <span class="ui-datepicker-month">August</span> i tried $(".ui-datepicker-month").live("click", function () { var monthname = $(this).val(); alert(monthna...

Windows batch file file download from a URL

I am trying to download a file from a website (ex. http://www.example.com/package.zip) using a Windows batch file. I am getting an error code when I write the function below: xcopy /E /Y "http://www.example.com/package.zip" The batch file doesn't...

How to iterate std::set?

I have this code: std::set<unsigned long>::iterator it; for (it = SERVER_IPS.begin(); it != SERVER_IPS.end(); ++it) { u_long f = it; // error here } There is no ->first value. How I can obtain the value?...

How to get datetime in JavaScript?

How to get date time in JavaScript with format 31/12/2010 03:55 AM?...

Create, read, and erase cookies with jQuery

Somebody help me. How to create, read and erase some cookies with jQuery ? ...

ReactJS and images in public folder

Im new in ReactJS and I want to import images in a component. These images are inside of the public folder and I do not know how to access the folder from the react component. Any ideas ? EDIT I want to import an image inside Bottom.js or Header....

Is it possible to output a SELECT statement from a PL/SQL block?

How can I get a PL/SQL block to output the results of a SELECT statement the same way as if I had done a plain SELECT? For example how to do a SELECT like: SELECT foo, bar FROM foobar; Hint : BEGIN SELECT foo, bar FROM foobar; END; doesn't wor...

Get specific line from text file using just shell script

I am trying to get a specific line from a text file. So far, online I have only seen stuff like sed, (I can only use the sh -not bash or sed or anything like that). I need to do this only using a basic shell script. cat file | while read line d...

Shell equality operators (=, ==, -eq)

Can someone please explain the difference between =, == and -eq in shell scripting? Is there any difference between the following? [ $a = $b ] [ $a == $b ] [ $a -eq $b ] Is it simply that = and == are only used when the variables contain numbers?...

jQuery datepicker, onSelect won't work

I can't get onSelect working on my jQuery datepicker. Heres my code: <script type="text/javascript"> $(function() { $('.date-pick').datePicker( { onSelect: function(date) { alert(date) }, selectWeek: tr...

Convert Date format into DD/MMM/YYYY format in SQL Server

I have a query in SQL, I have to get a date in a format of dd/mm/yy Example: 25/jun/2013. How can I convert it for SQL server?...

Undefined reference to main - collect2: ld returned 1 exit status

I'm trying to compile a program (called es3), but, when I write from terminal: gcc es3.c -o es3 it appears this message: /usr/lib/gcc/i686-linux-gnu/4.4.5/../../../../lib/crt1.o: In function `_start': (.text+0x18): undefined reference to `main' co...

setting multiple column using one update

How to set multiple columns of a table using update query in mysql?...

How to disable button in React.js

I have this component: import React from 'react'; export default class AddItem extends React.Component { add() { this.props.onButtonClick(this.input.value); this.input.value = ''; } render() { return ( <div className="add-...

Postgres: INSERT if does not exist already

I'm using Python to write to a postgres database: sql_string = "INSERT INTO hundred (name,name_slug,status) VALUES (" sql_string += hundred + ", '" + hundred_slug + "', " + status + ");" cursor.execute(sql_string) But because some of my rows are i...

jquery: get id from class selector

Is there any way that I can get the id of an element from something like: <a href="#" class="test" id="test_1">Some text</a> <a href="#" class="test" id="test_2">Some text</a> <a href="#" class="test" id="test_3">Some t...

How to increment a pointer address and pointer's value?

Let us assume, int *p; int a = 100; p = &a; What will the following code will do actually and how? p++; ++p; ++*p; ++(*p); ++*(p); *p++; (*p)++; *(p)++; *++p; *(++p); I know, this is kind of messy in terms of coding, but I want to know ...

Converting a date in MySQL from string field

I'm using a system where the dates are stored as strings in the format dd/mm/yyyy. Is it possible to convert this to yyyy-mm-dd in a SELECT query (so that I can use DATE_FORMAT on it)? Does MySQL have a date parsing function? Currently the only meth...

urllib2 and json

can anyone point out a tutorial that shows me how to do a POST request using urllib2 with the data being in JSON format?...

How to pass IEnumerable list to controller in MVC including checkbox state?

I have an mvc application in which I am using a model like this: public class BlockedIPViewModel { public string IP { get; set; } public int ID { get; set; } public bool Checked { get; set; } } Now I have a View to bind a list like ...

Clear Application's Data Programmatically

I want to clear my application's data programmatically. Application's data may contain anything like databases, shared preferences, Internal-External files or any other files created within the application. I know we can clear data in the mobile d...

Add column to dataframe with constant value

I have an existing dataframe which I need to add an additional column to which will contain the same value for every row. Existing df: Date, Open, High, Low, Close 01-01-2015, 565, 600, 400, 450 New df: Name, Date, Open, High, Low, Close abc, 01...

What’s the difference between “{}” and “[]” while declaring a JavaScript array?

What’s the difference between “{}” and “[]” while declaring a JavaScript array? Normally I declare like var a=[]; What is the meaning of declaring the array as var a={}...

Android, How can I Convert String to Date?

I store current time in database each time application starts by user. Calendar c = Calendar.getInstance(); String str = c.getTime().toString(); Log.i("Current time", str); In database side, I store current time as string (as you see in ab...

How to modify memory contents using GDB?

I know that we can use several commands to access and read memory: for example, print, p, x... But how can I change the contents of memory at any specific location (while debugging in GDB)? ...

How to check if all inputs are not empty with jQuery

I need to validate a form with jQuery. I can check all my inputs one by one, but it's not a very practical solution. How can i check if all my inputs are non-empty more efficiently? In my form i can have input elements of different types: text, seve...

Javascript to set hidden form value on drop down change

New to javascript, but I'm sure this is easy. Unfortunately, most of the google results haven't been helpful. Anyway, I want to set the value of a hidden form element through javascript when a drop down selection changes. I can use jQuery, if it m...

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

Variable used in lambda expression should be final or effectively final

Variable used in lambda expression should be final or effectively final When I try to use calTz it is showing this error. private TimeZone extractCalendarTimeZoneComponent(Calendar cal, TimeZone calTz) { try { cal.getComponents().ge...

How to solve WAMP and Skype conflict on Windows 7?

I have Windows 7 (32-bit) installed on laptop. I downloaded WAMP server and installed it with it's default options. However, I noticed that Apache does not work (while MySQL does work!). I tried to install it via Apache ? Service ? Install Servic...

Plotting 4 curves in a single plot, with 3 y-axes

I have 4 sets of values: y1, y2, y3, y4 and one set x. The y values are of different ranges, and I need to plot them as separate curves with separate sets of values on the y-axis. To put it simple, I need 3 y-axes with different values (scales) for ...

Replace multiple characters in a C# string

Is there a better way to replace strings? I am surprised that Replace does not take in a character array or string array. I guess that I could write my own extension but I was curious if there is a better built in way to do the following? Notice t...

Using the Web.Config to set up my SQL database connection string?

Can anyone help me out please? I'm confused. I want to set up my connection string so I can just call it from my Web.Config file. I need a way to call it from my code, please make a little example. :( I also need help on setting up the Web.Config...

handle textview link click in my android app

I'm currently rendering HTML input in a TextView like so: tv.setText(Html.fromHtml("<a href='test'>test</a>")); The HTML being displayed is provided to me via an external resource, so I cannot change things around as I will, but I can,...

Connect Android Studio with SVN

I have an Android project in Eclipse (Windows) synchronized with SVN, I installed Android Studio (Linux) and I need take the same project from SVN....

How to disable and then enable onclick event on <div> with javascript

Following is the code which i am trying document.getElementById("id").disabled = true; ...

Validate that text field is numeric usiung jQuery

I have a simple issue -- I would like to check a field to see if it's an integer if it is not blank. I'm not using any additional plugins, just jQuery. My code is as follows: if($('#Field').val() != "") { if($('#Field').val().match('^(0|[1-9][0-...

What is the difference between precision and scale?

What is the difference between precision and scale in Oracle? In tutorials they usually leave scale empty and set precision to 6 when creating a primary key. What do precision and scale stand for?...

HTML tag <a> want to add both href and onclick working

I'd like to ask about HTML tag <a href="www.mysite.com" onClick="javascript.function();">Item</a> How to make this a tag working with href and onClick? (prefer onClick running first then href)...

Is there any WinSCP equivalent for linux?

I love WinSCP for Windows. What are the best equivalent softwares for linux? I tried to use sshfs to mount the remote file system on my local machine, but it is not as user friendly as simply launching a GUI, plus it seems to require root access on...

Set initial value in datepicker with jquery?

I'm trying to set an initial value in my jquery ui datepicker. I've tried several different ways, but nothing seems to display the date, it's empty. var idag = new Date(); $("#txtFrom").datepicker("setDate", idag - 2); $("#txtTom").datepicker("setDa...

Slide a layout up from bottom of screen

I have a layout hidden from the view. On a button click I want it to slide up from the bottom pushing the entire screen contents upwards, very similar to how whatsapp shows emoticons panel in chat screen. I have seen SlidingDrawer, that dosen't wor...

Using Panel or PlaceHolder

What is the difference between <asp:Panel > and <asp:PlaceHolder > in ASP.NET? When should you use one over the other?...

WebService Client Generation Error with JDK8

I need to consume a web service in my project. I use NetBeans so I right-clicked on my project and tried to add a new "Web Service Client". Last time I checked, this was the way to create a web service client. But it resulted in an AssertionError, sa...

How to check if a .txt file is in ASCII or UTF-8 format in Windows environment?

I have converted a .txt file from ASCII to UTF-8 using UltraEdit. However, I am not sure how to verify if it is in UTF-8 format in Windows environment. Thank you!...

CSS - Syntax to select a class within an id

What is the selector syntax to select a tag within an id via the class name? For example, what do I need to select below in order to make the inner "li" turn red? <html> <head> <style type="text/css"> #navigation li ...

Transparent scrollbar with css

Now use this code (and many variations of this), but scroll track get dark-grey color, something like #222222 or near this. Find many examples, but all of them give same result. Opera, Chrome and Firefox show this bug. How to fix? #style-3::-webkit-...

Is there a macro to conditionally copy rows to another worksheet?

Is there a macro or a way to conditionally copy rows from one worksheet to another in Excel 2003? I'm pulling a list of data from SharePoint via a web query into a blank worksheet in Excel, and then I want to copy the rows for a particular month to ...

Apache is not running from XAMPP Control Panel ( Error: Apache shutdown unexpectedly. This may be due to a blocked port)

I have installed XAMPP (xampp-win32-1.8.2-0-VC9-installer.exe) on Windows 7 successfully. But unfortunately, the following error was found during running Apache from XAMPP Control Panel: 5:38:38 PM [Apache] Error: Apache shutdown unexpectedly. ...

Set encoding and fileencoding to utf-8 in Vim

What is the difference between these two commands? set encoding=utf-8 set fileencoding=utf-8 Do I need to set both when I want to use utf-8? Also, do I need to set fileencoding with set or setglobal?...

Apply function to each element of a list

How do I apply a function to the list of variable inputs? For e.g. the filter function returns true values but not the actual output of the function. from string import upper mylis=['this is test', 'another test'] filter(upper, mylis) ['this is tes...

Write variable to a file in Ansible

I am pulling JSON via the URI module and want to write the received content out to a file. I am able to get the content and output it to the debugger so I know the content has been received, but I do not know the best practice for writing files....

JPG vs. JPEG image formats

I often use JPEG images, and I have noticed that there are two very similar file extensions: .jpg, which my mobile's camera and the Preview application use, and .jpeg, with which Image Capture saves the images from scanning with my Canon MX455 printe...

I want to add a JSONObject to a JSONArray and that JSONArray included in other JSONObject

I need below kind of structure constructed in java and send it as response : var abc = { "action": "Remove", "datatable": [ { "userid": "userid0", "username": "name0" }, ...

Android Studio Emulator and "Process finished with exit code 0"

I've updated android studio from 3.0 to 3.0.1 but when I launch Emulator it didn't get launched and gives message in event log: Emulator: Process finished with exit code 0 ...

Blocks and yields in Ruby

I am trying to understand blocks and yield and how they work in Ruby. How is yield used? Many of the Rails applications I've looked at use yield in a weird way. Can someone explain to me or show me where to go to understand them?...

WordPress: get author info from post id

Or even the author id from the post id. I am trying to return the author meta (author page link and avatar) in the sidebar of a single post page (outside of the post loop). What is the best way to do this? I am using a custom function (see below) to ...

Different names of JSON property during serialization and deserialization

Is it possible: to have one field in class, but different names for it during serialization/deserialization in Jackson library? For example, I have class "Coordiantes". class Coordinates{ int red; } For deserialization from JSON want to have fo...

React prevent event bubbling in nested components on click

Here's a basic component. Both the <ul> and <li> have onClick functions. I want only the onClick on the <li> to fire, not the <ul>. How can I achieve this? I've played around with e.preventDefault(), e.stopPropagation(), to n...

Twitter bootstrap scrollable modal

I'm using twitter bootstrap for a project I am working on. I have a modal window that has a somewhat longer form in it and I didn't like that when the window got too small the modal didn't scroll (if just disappeared off my page which isn't scrolla...

Django Admin - change header 'Django administration' text

How does one change the 'Django administration' text in the django admin header? It doesn't seem to be covered in the "Customizing the admin" documentation....

Nesting await in Parallel.ForEach

In a metro app, I need to execute a number of WCF calls. There are a significant number of calls to be made, so I need to do them in a parallel loop. The problem is that the parallel loop exits before the WCF calls are all complete. How would you r...

How to enable cross-origin resource sharing (CORS) in the express.js framework on node.js

I'm trying to build a web server in node.js that will support cross-domain scripting, while still providing static files from a public directory. I'm using the express.js and am not really sure how to allow cross-domain scripting (Access-Control-Allo...

Check if a string is a date value

What is an easy way to check if a value is a valid date, any known date format allowed. For example I have the values 10-11-2009, 10/11/2009, 2009-11-10T07:00:00+0000 which should all be recognized as date values, and the values 200, 10, 350, which...

Convert java.time.LocalDate into java.util.Date type

I want to convert java.time.LocalDate into java.util.Date type. Because I want to set the date into JDateChooser. Or is there any date chooser that supports java.time dates?...

How to use nanosleep() in C? What are `tim.tv_sec` and `tim.tv_nsec`?

What is the use of tim.tv_sec and tim.tv_nsec in the following? How can I sleep execution for 500000 microseconds? #include <stdio.h> #include <time.h> int main() { struct timespec tim, tim2; tim.tv_sec = 1; tim.tv_nsec = 500;...

Open page in new window without popup blocking

Hope you can help a bit here... I have a form that translate a word in a field, populate the field with the translated term and then do submit action all in one submit button. the submit is being made by jquery. problem is the target page is being b...

Gradients in Internet Explorer 9

Does anyone know the vendor prefix for gradients within IE9 or are we still supposed to still be using their proprietry filters? What I've got for the other browsers is: background-image: -moz-linear-gradient(top, #444444, #999999); /* FF3.6 */ bac...

Node.js: for each … in not working

I wanted to use for each ... in with Node.js (v0.4.11). I use it like this: var conf = { index: { path: { first: "index.html", pattern: "index/{num}.html" }, template: "index.tpl", limit: 8 }, feed...

Using setattr() in python

I am looking for someone to explain the basics of how to use, and not use setattr(). My problem arose trying to use one class method/function to return data that is then put in another method/function. Perhaps a simpler approach would be much better...

append new row to old csv file python

I am trying to add a new row to my old csv file. Basically, it gets updated each time I run the Python script. Right now I am storing the old csv rows values in a list and then deleting the csv file and creating it again with the new list value. W...

Print multiple arguments in Python

This is just a snippet of my code: print("Total score for %s is %s ", name, score) But I want it to print out: "Total score for (name) is (score)" where name is a variable in a list and score is an integer. This is Python 3.3 if that helps ...

Showing which files have changed between two revisions

I want to merge two branches that have been separated for a while and wanted to know which files have been modified. Came across this link: http://linux.yyz.us/git-howto.html which was quite useful. The tools to compare branches I've come across ar...

Typescript react - Could not find a declaration file for module ''react-materialize'. 'path/to/module-name.js' implicitly has an any type

I am trying to import components from react-materialize as - import {Navbar, NavItem} from 'react-materialize'; But when the webpack is compiling my .tsx it throws an error for the above as - ERROR in ./src/common/navbar.tsx (3,31): error TS7016: Co...

How can I get a list of all open named pipes in Windows?

Is there an easy way to test whether your named pipe is working correctly? I want to make sure that the data I'm sending from my app is actually being sent. Is there a quick and easy way to get a list of all the named pipes?...

Difference between timestamps with/without time zone in PostgreSQL

Are timestamp values stored differently in PostgreSQL when the data type is WITH TIME ZONE versus WITHOUT TIME ZONE? Can the differences be illustrated with simple test cases?...

How to set up a cron job to run an executable every hour?

I need to set up a cron job that runs an executable compiled using gcc once every hour. I logged in as root and typed crontab -e Then I entered the following and saved the file. 0 * * * * /path_to_executable However, the cron job does not work....

SQL Transaction Error: The current transaction cannot be committed and cannot support operations that write to the log file

I'm having a similar issue to The current transaction cannot be committed and cannot support operations that write to the log file, but I have a follow-up question. The answer there references Using TRY...CATCH in Transact-SQL, which I'll come back ...

How to update single value inside specific array item in redux

I have an issue where re-rendering of state causes ui issues and was suggested to only update specific value inside my reducer to reduce amount of re-rendering on a page. this is example of my state { name: "some name", subtitle: "some subtitle",...

How to post data in PHP using file_get_contents?

I'm using PHP's function file_get_contents() to fetch contents of a URL and then I process headers through the variable $http_response_header. Now the problem is that some of the URLs need some data to be posted to the URL (for example, login pages)...

Angular 2 ngfor first, last, index loop

I'm trying to set as default the first occurrence in this example: plunkr getting the following error: Unhandled Promise rejection: Template parse errors: TypeError: Cannot read property 'toUpperCase' of undefined ("dButtonToggleGroup&qu...

Convert a timedelta to days, hours and minutes

I've got a timedelta. I want the days, hours and minutes from that - either as a tuple or a dictionary... I'm not fussed. I must have done this a dozen times in a dozen languages over the years but Python usually has a simple answer to everything so...

Sorting dictionary keys in python

I have a dict where each key references an int value. What's the best way to sort the keys into a list depending on the values?...

Laravel Eloquent: Ordering results of all()

I'm stuck on a simple task. I just need to order results coming from this call $results = Project::all(); Where Project is a model. I've tried this $results = Project::all()->orderBy("name"); But it didn't work. Which is the better way to ...