Examples On Programing Languages

Find if listA contains any elements not in listB

I have two lists: List<int> listA List<int> listB How to check using LINQ if in the listA exists an element wchich deosn't exists in the listB ? I can use the foreach loop but I'm wondering if I can do this using LINQ...

onclick go full screen

I'm creating a web-app for the upcoming Chrome Web-store. Is there a way to simulate F11 being pressed? Or simply a command that will make the current window go full screen?...

INSERT IF NOT EXISTS ELSE UPDATE?

I've found a few "would be" solutions for the classic "How do I insert a new record or update one if it already exists" but I cannot get any of them to work in SQLite. I have a table defined as follows: CREATE TABLE Book ID INTEGER PRIMARY KEY...

How to replace a substring of a string

Assuming I have a String string like this: "abcd=0; efgh=1" and I want to replace "abcd" by "dddd". I have tried to do such thing: string.replaceAll("abcd","dddd"); It does not work. Any suggestions? EDIT: To be more specific, I am working in...

vertical-align image in div

i have problem with image vertical-align in div .img_thumb { float: left; height: 120px; margin-bottom: 5px; margin-left: 9px; position: relative; width: 147px; background-color: rgba(0, 0, 0, 0.5); border-radius: 3px...

How to import other Python files?

How do I import other files in Python? How exactly can I import a specific python file like import file.py? How can I import a folder instead of a specific file? I want to load a Python file dynamically at runtime, based on user input. I want to kn...

Failed to load resource: the server responded with a status of 404 (Not Found) error in server

I'm trying to load up image in my Image Folder, but it's not working. Upon debugging, I see this error: Failed to load resource: the server responded with a status of 404 (Not Found) My image coding is in .css file that is, background: url(...

Object comparison in JavaScript

What is the best way to compare objects in JavaScript? Example: var user1 = {name : "nerd", org: "dev"}; var user2 = {name : "nerd", org: "dev"}; var eq = user1 == user2; alert(eq); // gives false I know that two objects are equal if they refer t...

Remove white space above and below large text in an inline-block element

Say I have a single span element defined as an inline-block. It's only contents is plain text. When the font size is very large, you can clearly see how the browser adds a little padding above and below the text. HTML: CSS: _x000D_ _x000D_ span {_...

Is it possible to save HTML page as PDF using JavaScript or jquery?

Is it possible to save HTML page as PDF using JavaScript or jquery? In Detail: I generated one HTML Page which contains a table . It has one button 'save as PDF'. If user clicks that button then that HTML page has to convert as PDF file. Is it pos...

Is there a performance difference between i++ and ++i in C?

Is there a performance difference between i++ and ++i if the resulting value is not used?...

How to get the start time of a long-running Linux process?

Is it possible to get the start time of an old running process? It seems that ps will report the date (not the time) if it wasn't started today, and only the year if it wasn't started this year. Is the precision lost forever for old processes?...

Using cut command to remove multiple columns

given input echo 1,2,3,4,5,6,7,8,9,...100 If I want to cut columns 5 I can do cut -d, -f-4,6- what if I want to cut multiple non consecutive columns like 5, 7,etc is there a one liner?...

hide div tag on mobile view only?

I'm creating a fluid layout for a site. I'm trying to hide the contents of a <div> or the whole <div> itself in the mobile view, but not the tablet and desktop view. Here's what I've got so far... #title_message { clear: both; f...

CMake: How to build external projects and include their targets

I have a Project A that exports a static library as a target: install(TARGETS alib DESTINATION lib EXPORT project_a-targets) install(EXPORT project_a-targets DESTINATION lib/alib) Now I want to use Project A as an external project from Project B a...

How can I plot separate Pandas DataFrames as subplots?

I have a few Pandas DataFrames sharing the same value scale, but having different columns and indices. When invoking df.plot(), I get separate plot images. what I really want is to have them all in the same plot as subplots, but I'm unfortunately fai...

How to make rounded percentages add up to 100%

Consider the four percentages below, represented as float numbers: 13.626332% 47.989636% 9.596008% 28.788024% ----------- 100.000000% I need to represent these percentages as whole numbers. If I simply use Math.round(), I en...

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 detect Windows 64-bit platform with .NET?

In a .NET 2.0 C# application I use the following code to detect the operating system platform: string os_platform = System.Environment.OSVersion.Platform.ToString(); This returns "Win32NT". The problem is that it returns "Win32NT" even when runnin...

Convert Dictionary<string,string> to semicolon separated string in c#

Simple one to start the day, given a Dictionary<string, string> as follows: var myDict = new Dictionary<string, string>(); myDict["A"] = "1"; myDict["B"] = "2"; myDict["C"] = "3"; myDict["D"] = "4"; I wish to create a string: "A=1;B=2;...

How to do while loops with multiple conditions

I have a while loop in python condition1=False condition1=False val = -1 while condition1==False and condition2==False and val==-1: val,something1,something2 = getstuff() if something1==10: condition1 = True if something2==20:...

Retrofit and GET using parameters

I am trying to send a request to the Google GeoCode API using Retrofit. The service interface looks like this: public interface FooService { @GET("/maps/api/geocode/json?address={zipcode}&sensor=false") void getPositionByZip(@Path("...

Countdown timer in React

I have seen lots of countdown timers in JavaScript and wanted to get one working in React. I have borrowed this function I found online: secondsToTime(secs){ let hours = Math.floor(secs / (60 * 60)); let divisor_for_minutes = secs % (60 * ...

How to add google-play-services.jar project dependency so my project will run and present map

I have following problem: I try to use SupportMapFragment from com.google.android.gms.maps.SupportMapFragment which is part of Google Maps Android API v2. My first approach was to add project to Eclipse from android-sdk\extras\google\google_play_ser...

json.net has key method?

If my response has key "error" I need to process error and show warning box. Is there "haskey" method exists in json.net? Like: var x= JObject.Parse(string_my); if(x.HasKey["error_msg"]) MessageBox.Show("Error!") ...

What is the bit size of long on 64-bit Windows?

Not to long ago, someone told me that long are not 64 bits on 64 bit machines and I should always use int. This did not make sense to me. I have seen docs (such as the one on Apple's official site) say that long are indeed 64 bits when compiling for ...

Arithmetic overflow error converting numeric to data type numeric

I keep getting this error message everytime I run this query: Msg 8115, Level 16, State 8, Line 33 Arithmetic overflow error converting numeric to data type numeric. The statement has been terminated. But if I change the create table to (7,0), I d...

String concatenation with Groovy

What is the best (idiomatic) way to concatenate Strings in Groovy? Option 1: calculateAccountNumber(bank, branch, checkDigit, account) { bank + branch + checkDigit + account } Option 2: calculateAccountNumber(bank, branch, checkDigit, accoun...

Override browser form-filling and input highlighting with HTML/CSS

I have 2 basic forms -- sign in and sign up, both on the same page. Now, I have no problem with the sign in form auto-filling, but the sign up form auto fills as well, and I don't like it. Also, the form styles get a yellow background which I can't ...

In MVC, how do I return a string result?

In my AJAX call, I want to return a string value back to the calling page. Should I use ActionResult or just return a string? ...

How do I Merge two Arrays in VBA?

Given Dim arr1 As Variant Dim arr2 As Variant Dim arr3 As Variant arr1 = Array("A", 1, "B", 2) arr2 = Array("C", 3, "D", 4) What kind of operations can I do on arr1 and arr2 and store result in arr3 such that: arr3 = ("A", "C", 1, 3, "B", "D"...

Android Whatsapp/Chat Examples

Does anybody have an example or a tutorial for a Android application like WhatsApp? I want to understand how WhatsApp works and how it is programmed. I want to see an example that uses a message-chat-system with "online"-status and "read the message...

How to go from Blob to ArrayBuffer

I was studying Blobs, and I noticed that when you have an ArrayBuffer, you can easily convert this to a Blob as follows: var dataView = new DataView(arrayBuffer); var blob = new Blob([dataView], { type: mimeString }); The question I have now is, i...

How to stop EditText from gaining focus at Activity startup in Android

I have an Activity in Android, with two elements: EditText ListView When my Activity starts, the EditText immediately has input focus (flashing cursor). I don't want any control to have input focus at startup. I tried: EditText.setSelected(fals...

How to delete a selected DataGridViewRow and update a connected database table?

I have a DataGridView control on a Windows Forms application (written with C#). What I need is: when a user selects a DataGridViewRow, and then clicks on a 'Delete' button, the row should be deleted and next, the database needs to be updated using...

Checking if a key exists in a JavaScript object?

How do I check if a particular key exists in a JavaScript object or array? If a key doesn't exist, and I try to access it, will it return false? Or throw an error?...

How do I get the current time only in JavaScript

How can I get the current time in JavaScript and use it in a timepicker? I tried var x = Date() and got: Tue May 15 2012 05:45:40 GMT-0500 But I need only current time, for example, 05:45 How can I assign this to a variable?...

How can I generate an HTML report for Junit results?

Is there a way to (easily) generate a HTML report that contains the tests results ? I am currently using JUnit in addition to Selenium for testing web apps UI. PS: Given the project structure I am not supposed to use Ant :(...

Detecting the onload event of a window opened with window.open

window.popup = window.open($(this).attr('href'), 'Ad', 'left=20,top=20,width=500,height=500,toolbar=1,resizable=0'); $(window.popup).onload = function() { alert("Popup has loaded a page"); }; This doesn't work in a...

PATH issue with pytest 'ImportError: No module named YadaYadaYada'

I used easy_install to install pytest on a mac and started writing tests for a project with a file structure likes so: repo/ repo/app.py repo/settings.py repo/models.py repo/tests/ repo/tests/test_app.py run py.test while in the repo directory, ev...

Android: Use a SWITCH statement with setOnClickListener/onClick for more than 1 button?

Let's say I have a few buttons in a LinearLayout, 2 of them are: mycards_button = ((Button)this.findViewById(R.id.Button_MyCards)); exit_button = ((Button)this.findViewById(R.id.Button_Exit)); I register setOnClickListener() on both of them: myca...

Get all photos from Instagram which have a specific hashtag with PHP

I need to get some pictures which have a specific hashtag using PHP ? Any help will be awesome, or hint ?...

iOS for VirtualBox

Is there anyway to install Apple iOS in VirtualBox? i have installed Android on VirtualBox with live Android and i have installed Snow leopard on VirtualBox but i don't know whether i could do the same with iOS if there is a way please let me know.(i...

How can I clear the NuGet package cache using the command line?

I can clear my development computer's NuGet package cache using Visual Studio menu Tools → Options → NuGet Package Manager → General: Clear Package Cache button. I would like to do this on the command line. Unfortunately, I can n...

What does upstream mean in nginx?

upstream app_front_static { server 192.168.206.105:80; } Never seen it before, anyone knows, what it means?...

Use VBA to Clear Immediate Window?

Does anyone know how to clear the immediate window using VBA? While I can always clear it myself manually, I am curious if there is a way to do this programmatically....

How do you get current active/default Environment profile programmatically in Spring?

I need to code different logic based on different current Environment profile. How can you get the currently active and default profiles from Spring?...

How do you tell if caps lock is on using JavaScript?

How do you tell if caps lock is on using JavaScript? One caveat though: I did google it and the best solution I could find was to attach an onkeypress event to every input, then check each time if the letter pressed was uppercase, and if it was, the...

Share variables between files in Node.js?

Here are 2 files: // main.js require('./modules'); console.log(name); // prints "foobar" // module.js name = "foobar"; When I don't have "var" it works. But when I have: // module.js var name = "foobar"; name will be undefined in main.js. I h...

Graphviz's executables are not found (Python 3.4)

I am running Python3.4 on Windows 7. I am trying to use the Python interface for graphviz. This is a script I intend to run: from graphviz import Digraph import pydotplus dot = Digraph(comment='The Round Table') dot.node('A', 'King Arthur') dot.no...

How do I configure IIS for URL Rewriting an AngularJS application in HTML5 mode?

I have the AngularJS seed project and I've added $locationProvider.html5Mode(true).hashPrefix('!'); to the app.js file. I want to configure IIS 7 to route all requests to http://localhost/app/index.html so that this works for me. How do I...

How do I explicitly specify a Model's table-name mapping in Rails?

I have a Model class called Countries and I want it to map to a DB table called 'cc'. How is that done in Rails?...

Delete all rows with timestamp older than x days

I want to delete all the rows with timestamp older than 180 days from a specific table in my database. I've tried the this: DELETE FROM on_search WHERE search_date < DATE_SUB(NOW(), INTERVAL 180 DAY); But that deleted all the rows and not only...

filter: progid:DXImageTransform.Microsoft.gradient is not working in ie7

I want to apply a gradient background color to my div. For IE I have used the property: filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#fad59f', endColorstr='#fa9907') It's working in IE9 and IE8. But not working in IE7. What...

How to load a model from an HDF5 file in Keras?

How to load a model from an HDF5 file in Keras? What I tried: model = Sequential() model.add(Dense(64, input_dim=14, init='uniform')) model.add(LeakyReLU(alpha=0.3)) model.add(BatchNormalization(epsilon=1e-06, mode=0, momentum=0.9, weights=None)) ...

Try/catch does not seem to have an effect

I am new to powershell, and I am trying to add error handling via try/catch statements, but they don't seem to actually be catching the error. This is powershell v2 CP3. $objComputer = $objResult.Properties; $strComputerName = $objComputer.name writ...

Laravel - Session store not set on request

I recently created a new Laravel project and was following along the guide on Authentication. When I visit either my login or register route, I get the following error: ErrorException in Request.php line 775: Session store not set on request. (View:...

SQL query to get most recent row for each instance of a given key

I'm trying to get the ip, user, and most recent timestamp from a table which may contain both the current ip for a user and one or more prior ips. I'd like one row for each user containing the most recent ip and the associated timestamp. So if a tabl...

Android ListView with Checkbox and all clickable

Possible Duplicate: Android: Binding data from a database to a CheckBox in a ListView? i want to use a ListView with the items having following layout ------------------------- [CB] TV TV ------------------------- CB is ...

instantiate a class from a variable in PHP?

I know this question sounds rather vague so I will make it more clear with an example: $var = 'bar'; $bar = new {$var}Class('var for __construct()'); //$bar = new barClass('var for __construct()'); This is what I want to do. How would you do it? I...

Capturing a single image from my webcam in Java or Python

I want to capture a single image from my webcam and save it to disk. I want to do this in Java or Python (preferably Java). I want something that will work on both 64-bit Win7 and 32-bit Linux. EDIT: I use Python 3.x, not 2.x Because everywhere e...

Remove quotes from String in Python

I have a python Code that will recognize speech using the Google STT engine and give me back the results but I get the results in strings with "quotes". I don't want that quotes in my code as I will use it to run many commands and it doesn't work. I ...

Understanding PIVOT function in T-SQL

I am very new to SQL. I have a table like this: ID | TeamID | UserID | ElementID | PhaseID | Effort ----------------------------------------------------- 1 | 1 | 1 | 3 | 5 | 6.74 2 | 1 | 1 | 3 | 6 ...

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 do I find the parent directory in C#?

I use this code for finding the debug directory public string str_directory = Environment.CurrentDirectory.ToString(); "C:\\Users\\Masoud\\Documents\\Visual Studio 2008\\Projects\\MyProj\\MyProj\\bin\\Debug" How can I find the parent folder as sh...

The request was rejected because no multipart boundary was found in springboot

As I am trying this with spring boot and webservices with postman chrome add-ons. In postman content-type="multipart/form-data" and I am getting the below exception. HTTP Status 500 - Request processing failed; nested exception is org.springframew...

How to add a second css class with a conditional value in razor MVC 4

While Microsoft has created some automagic rendering of html attributes in razor MVC4, it took me quite some time to find out how to render a second css class on an element, based on a conditional razor expression. I would like to share it with you. ...

$lookup on ObjectId's in an array

What's the syntax for doing a $lookup on a field that is an array of ObjectIds rather than just a single ObjectId? Example Order Document: { _id: ObjectId("..."), products: [ ObjectId("..<Car ObjectId>.."), ObjectId("..<Bike Ob...

jQuery get content between <div> tags

This'll probably be easy for someone: var x = '<p>blah</p><div><a href="http://bs.serving-sys.com/BurstingPipe/adServer.bs?cn=brd&FlightID=2997227&Page=&PluID=0&Pos=9088" target="_blank"><img src="http://bs...

import an array in python

How can I import an array to python (numpy.arry) from a file and that way the file must be written if it doesn't already exist. For example, save out a matrix to a file then load it back....

nuget 'packages' element is not declared warning

not a showstopper but when using nuget in a project, it creates a packages.config file with this shape <?xml version="1.0" encoding="utf-8"?> <packages> ... your packages </packages> this gives a warning in VS The 'packages...

Making view resize to its parent when added with addSubview

I'm having a problem when using addSubview. Example code: ParentView *myParentView = [[ParentView alloc] initWithNibName:@"ParentView " bundle:nil]; ChildeView *myChildeView = [[ChildeView alloc] initWithNibName:@"ChildeView" bundle:nil]; //... p...

Using jquery to get element's position relative to viewport

What's the proper way to get the position of an element on the page relative to the viewport (rather than the document). jQuery.offset function seemed promising: Get the current coordinates of the first element, or set the coordinates of every ...

How do I replace multiple spaces with a single space in C#?

How can I replace multiple spaces in a string with only one space in C#? Example: 1 2 3 4 5 would be: 1 2 3 4 5 ...

Oracle JDBC ojdbc6 Jar as a Maven Dependency

I cannot seem to get Maven to bundle the ojdbc6.jar file into my project's war file. I have it working within the POM file when specifying a dependency directly for Hibernate tools. But it won't get bundled with the project's war file, and therefor...

How to call function of one php file from another php file and pass parameters to it?

I want to call a function in one PHP file from a second PHP file and also pass two parameters to that function. How can I do this? I am very new to PHP. So please tell me, should I include the first PHP file into the second? Please show me an examp...

How to see an HTML page on Github as a normal rendered HTML page to see preview in browser, without downloading?

On http://github.com developer keep the HTML, CSS, JavaScript and images files of the project. How can I see the HTML output in browser? For example this: https://github.com/necolas/css3-social-signin-buttons/blob/master/index.html When I open this...

Session timeout in ASP.NET

I am running an ASP.NET 2.0 application in IIS 6.0. I want session timeout to be 60 minutes rather than the default 20 minutes. I have done the following Set <sessionState timeout="60"></sessionState> in web.config. Set session timeout ...

Python URLLib / URLLib2 POST

I'm trying to create a super-simplistic Virtual In / Out Board using wx/Python. I've got the following code in place for one of my requests to the server where I'll be storing the data: data = urllib.urlencode({'q': 'Status'}) u = urllib2.urlopen('...

CSS to make HTML page footer stay at bottom of the page with a minimum height, but not overlap the page

I have the following page (deadlink: http://www.workingstorage.com/Sample.htm ) that has a footer which I can't make sit at the bottom of the page. I want the footer to stick to the window bottom when the page is short and the screen is not filled, ...

What's the difference between '$(this)' and 'this'?

I am currently working through this tutorial: Getting Started with jQuery For the two examples below: $("#orderedlist").find("li").each(function (i) { $(this).append(" BAM! " + i); }); $("#reset").click(function () { $("form").each(function...

How to stop a function

For example: def main(): if something == True: player() elif something_else == True: computer() def player(): # do something here check_winner() # check something computer() # let the computer do something def...

android View not attached to window manager

I am having some of the following exceptions: java.lang.IllegalArgumentException: View not attached to window manager at android.view.WindowManagerImpl.findViewLocked(WindowManagerImpl.java:355) at android.view.WindowManagerImpl.updateViewLayout(Win...

Does 'position: absolute' conflict with Flexbox?

I want to make a div stick on the top of the screen without any influence to other elements, and its child element in the center. _x000D_ _x000D_ .parent {_x000D_ display: flex;_x000D_ justify-content: center;_x000D_ position: absolute;_x0...

How to get document height and width without using jquery

How to get document height and width in pure javascript i.e without using jquery. I know about $(document).height() and $(document).width(), but I want to do this in javascript. I meant page's height and width....

Android - SPAN_EXCLUSIVE_EXCLUSIVE spans cannot have a zero length

I have the following layout (virtually empty): <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/set_layout" android:layout_width="fill_parent" andro...

Why does an onclick property set with setAttribute fail to work in IE?

Ran into this problem today, posting in case someone else has the same issue. var execBtn = document.createElement('input'); execBtn.setAttribute("type", "button"); execBtn.setAttribute("id", "execBtn"); execBtn.setAttribute("value", "Execute"); exe...

Fixed height and width for bootstrap carousel

I am using the bootstrap carousel but I want a fixed width and height so that all my images will auto fit to the defined height and width. Can someone please help me on achieving this. <div class="row"> <div class="span8"> &l...

apache server reached MaxClients setting, consider raising the MaxClients setting

I am running centos 5.5 with 768mb ram. i keep getting server reached MaxClients setting, consider raising the MaxClients setting in the logs also apache runs really slow. when i look at cacti graphs it shows the server is not even using all the reso...

Is it possible to use if...else... statement in React render function?

Basically, I have a react component, its render() function body is as below: (It is my ideal one, which means it currently does not work) render(){ return ( <div> <Element1/> <Element2/> ...

Convert ascii char[] to hexadecimal char[] in C

I am trying to convert a char[] in ASCII to char[] in hexadecimal. Something like this: hello --> 68656C6C6F I want to read by keyboard the string. It has to be 16 characters long. This is my code now. I don't know how to do that operation. I rea...

How to configure socket connect timeout

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

Testing the type of a DOM element in JavaScript

Is there a way to test the type of an element in JavaScript? The answer may or may not require the prototype library, however the following setup does make use of the library. function(event) { var element = event.element(); // if the element ...

Convert Year/Month/Day to Day of Year in Python

I'm using the datetime module, i.e.: >>> import datetime >>> today = datetime.datetime.now() >>> print(today) 2009-03-06 13:24:58.857946 and I would like to compute the day of year that takes leap years into account. e.g. ...

How to see full query from SHOW PROCESSLIST

When I issue SHOW PROCESSLIST query, only first 100 characters of the running SQL query are returned in the info column. Is it possible to change Mysql config or issue a different kind of request to see complete query (the queries I'm looking at are...

Oracle query to identify columns having special characters

I'm trying to write a SQL query to return rows which has anything other than alphabets, numbers, spaces and following chars '.', '{','[','}',']' Column has alphabets like Ÿ, ¿ eg:- There's a table TEST with 2 columns - EmpNo and SampleText EmpNo ...

Sending E-mail using C#

I need to send email via my C# app. I come from a VB 6 background and had a lot of bad experiences with the MAPI control. First of all, MAPI did not support HTML emails and second, all the emails were sent to my default mail outbox. So I still neede...

Check if decimal value is null

I would like to check if the decimal number is NULL or it has some value, since the value is assigned from database in class object: public decimal myDecimal{ get; set; } and then I have myDecimal = Convert.ToDecimal(rdrSelect[23].ToString()); ...

ActivityCompat.requestPermissions not showing dialog box

if (ContextCompat.checkSelfPermission(RegisterActivity.this, Manifest.permission.READ_PHONE_STATE) == PackageManager.PERMISSION_DENIED){ ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.REA...

Logical operators ("and", "or") in DOS batch

How would you implement logical operators in DOS Batch files?...

How to override the [] operator in Python?

What is the name of the method to override the [] operator (subscript notation) for a class in Python?...

RecyclerView vs. ListView

From android developer (Creating Lists and Cards): The RecyclerView widget is a more advanced and flexible version of ListView. Okay, it sounds cool, but when I saw this example picture, I got really confused about the difference between thes...

Get the generated SQL statement from a SqlCommand object?

I have the following code: Using cmd As SqlCommand = Connection.CreateCommand cmd.CommandText = "UPDATE someTable SET Value = @Value" cmd.CommandText &= " WHERE Id = @Id" cmd.Parameters.AddWithValue("@Id", 1234) cmd.Parameters.Ad...

Convert DateTime to TimeSpan

I want to convert a DateTime instance into a TimeSpan instance, is it possible? I've looked around but I couldn't find what I want, I only find time difference. More specifically, I want to convert a DateTime instance into milliseconds, to then sav...

delete all from table

what's faster? DELETE FROM table_name; or DELETE FROM table_name where 1=1; why? does truncate table work in access?...

How to remove margin space around body or clear default css styles

I am admittedly a beginner, but I also did a fair amount of searching before posting this. There seems to be extra space around my div element. I also would like to point out that I tried many combinations of border: 0, padding:0, etc. and nothing se...

setOnItemClickListener on custom ListView

I have a custom ListView. This ListView contains 1 Image and 6 TextViews. To retrieve the value I have created a setOnItemClickListener(...). Whenever I click on the ListView how could I actually retrieve all the data from the 6 TextViews?...

How to split string using delimiter char using T-SQL?

I have this long string in one of the columns of the table. I want to get only specific information:- My Table structure:- Col1 = '123' Col2 = 'AAAAA' Col3 = 'Clent ID = 4356hy|Client Name = B B BOB|Client Phone = 667-444-2626|Client Fax = 666-666-0...

How to create a circle icon button in Flutter?

How can I create something similar to a FloatingActionButton?...

Return list from async/await method

I want to make a webservice request asynchron. I call it here: List<Item> list = GetListAsync(); Here is the declaration of my function, which should return a list: private async Task<List<Item>> GetListAsync(){ List<Item...

How do I list one filename per output line in Linux?

I'm using ls -a command to get the file names in a directory, but the output is in a single line. Like this: . .. .bash_history .ssh updater_error_log.txt I need a built-in alternative to get filenames, each on a new line, like this: . .....

JavaScript open in a new window, not tab

I have a select box that calls window.open(url) when an item is selected. Firefox will open the page in a new tab by default. However, I would like the page to open in a new window, not a new tab. How can I accomplish this?...

How to use code to open a modal in Angular 2?

Usually we use data-target="#myModal" in the <button> to open a modal. Right now I need use codes to control when to open the modal. If I use [hidden] or *ngIf to show it, I need remove class="modal fade", otherwise, the modal will never show....

How to make a jquery function call after "X" seconds

I have a jquery function and I need to call it after opening the website in an Iframe. I am trying to open a weblink in an Iframe and after opening it I need to call the below function. So how do I do that? Here is my function: <script type="te...

How can I capture the result of var_dump to a string?

I'd like to capture the output of var_dump to a string. The PHP documentation says; As with anything that outputs its result directly to the browser, the output-control functions can be used to capture the output of this function, and save it in...

Deleting all files from a folder using PHP?

For example I had a folder called `Temp' and I wanted to delete or flush all files from this folder using PHP. Could I do this?...

How to make a Div appear on top of everything else on the screen?

Edit to reopen: It seems to be difficult to position elements over a google map. Using z-index does not solve the problem which is described below: Google Maps will stay on top of some other elements even when using high z-indexes. The question is: I...

Sending credentials with cross-domain posts?

According to Requests with credentials, Firefox will only send credentials along with cross-domain posts if invocation.withCredentials = "true"; is set… But it doesn't seem like jQuery's Ajax API provides any mechanism for this. Is there somet...

Serializing a list to JSON

I have an object model that looks like this: public MyObjectInJson { public long ObjectID {get;set;} public string ObjectInJson {get;set;} } The property ObjectInJson is an already serialized version an object that contains nested lists. For t...

Understanding Python super() with __init__() methods

I'm trying to understand the use of super(). From the looks of it, both child classes can be created, just fine. I'm curious to know about the actual difference between the following 2 child classes. class Base(object): def __init__(self): ...

HTTP Status 500 - Error instantiating servlet class pkg.coreServlet

I am creating simple servlet and deploying it in tomcat server but I am getting the following error: HTTP Status 500 - Error instantiating servlet class pkg.coreServlet File Structure on the tomcat server: webapps | - aarya | - WEB-I...

Cron and virtualenv

I am trying to run a Django management command from cron. I am using virtualenv to keep my project sandboxed. I have seen examples here and elsewhere that show running management commands from within virtualenv's like: 0 3 * * * source /home/user/p...

How to ignore deprecation warnings in Python

I keep getting this : DeprecationWarning: integer argument expected, got float How do I make this message go away? Is there a way to avoid warnings in Python?...

Disable clipboard prompt in Excel VBA on workbook close

I have an Excel workbook, which using VBA code that opens another workbook, copies some data into the original, then closes the second workbook. When I close the second workbook (using Application.Close), I get a prompt for: Do you want to save ...

Read from database and fill DataTable

I'm getting a set of data by a DataReader and assigning to a string. Now I need to fill the DataTable columns with the query fields. The DataTable is connected to a grid to display the filled data. query is : strSQL = "SELECT EmpCode,EmpID,EmpName...

Delete cookie by name?

How can I delete a specific cookie with the name roundcube_sessauth? Shouldn't the following: function del_cookie(name) { document.cookie = 'roundcube_sessauth' + '=; expires=Thu, 01-Jan-70 00:00:01 GMT;'; } And then: <a href="javas...

How to convert a string to character array in c (or) how to extract a single char form string?

I need to convert a string to a char array in C; how can I do this? Or at least, how can I extract single chars from a string incrementally?...

Elegant way to report missing values in a data.frame

Here's a little piece of code I wrote to report variables with missing values from a data frame. I'm trying to think of a more elegant way to do this, one that perhaps returns a data.frame, but I'm stuck: for (Var in names(airquality)) { missin...

Dump a NumPy array into a csv file

Is there a way to dump a NumPy array into a CSV file? I have a 2D NumPy array and need to dump it in human-readable format....

How to specify the private SSH-key to use when executing shell command on Git?

A rather unusual situation perhaps, but I want to specify a private SSH-key to use when executing a shell (git) command from the local computer. Basically like this: git clone [email protected]:TheUser/TheProject.git -key "/home/christoffer/ssh_key...

Split Div Into 2 Columns Using CSS

I have been attempting to split a div into two columns using CSS, but I have not managed to get it working yet. My basic structure is as follows: <div id="content"> <div id="left"> <div id="object1"></div> <di...

Shuffling a list of objects

I have a list of objects and I want to shuffle them. I thought I could use the random.shuffle method, but this seems to fail when the list is of objects. Is there a method for shuffling objects or another way around this? import random class A: ...

What is the difference between HAVING and WHERE in SQL?

What is the difference between HAVING and WHERE in an SQL SELECT statement? EDIT: I have marked Steven's answer as the correct one as it contained the key bit of information on the link: When GROUP BY is not used, HAVING behaves like a WHERE clause ...

Cannot load properties file from resources directory

I imported a project from a Git repository and added Maven nature to it in Eclipse. In the resources folder, I added a configuration file called myconf.properties. Now, whenever I try to open this file from my Java code, I get FileNotFoundException. ...

Using success/error/finally/catch with Promises in AngularJS

I'm using $http in AngularJs, and I'm not sure on how to use the returned promise and to handle errors. I have this code: $http .get(url) .success(function(data) { // Handle data }) .error(function(data, status) { /...

How is using "<%=request.getContextPath()%>" better than "../"

I have worked on number of J2EE projects where the view layer is JSP. In most projects, I have seen that we reference external resources i.e. images, javascript, jsp's, css etc. using the contextPath in the scriptlet. The code is as follows, <%@...

jQuery form validation on button click

I have a simple page with a form and a button outside the form. I am trying to validate the form on the button click. I have added the rules for validation of the form on the document.onready function. However the form is not getting validated. HT...

Remove duplicated rows using dplyr

I have a data.frame like this - set.seed(123) df = data.frame(x=sample(0:1,10,replace=T),y=sample(0:1,10,replace=T),z=1:10) > df x y z 1 0 1 1 2 1 0 2 3 0 1 3 4 1 1 4 5 1 0 5 6 0 1 6 7 1 0 7 8 1 0 8 9 1 0 9 10 0 1 10 I wo...

How to get a password from a shell script without echoing

I have a script that automates a process that needs access to a password protected system. The system is accessed via a command-line program that accepts the user password as an argument. I would like to prompt the user to type in their password, as...

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

PHP Redirect to another page after form submit

I have read all your posts about inserting headers into a php form file in order to redirect the user to another URL AFTER the form is submitted - but I can't figure out how to do it. Below is my code. Can you show me where to put the header/redire...

Open application after clicking on Notification

I have a notification in my app with the following code: //Notification Start notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); int icon = R.drawable.n1; CharSequence tickerText = "Call Blocker";...

What is "with (nolock)" in SQL Server?

Can someone explain the implications of using with (nolock) on queries, when you should/shouldn't use it? For example, if you have a banking application with high transaction rates and a lot of data in certain tables, in what types of queries would ...

Read XLSX file in Java

I need to read an Excel 2007 XLSX file in a Java application. Does anyone know of a good API to accomplish this task?...

How do I install cygwin components from the command line?

Is there a tool in the Cygwin package similar to apt-get on Debian or yum on redhat that allows me to install components from the command line?...

How do I get the full url of the page I am on in C#

I need to be able to get at the full URL of the page I am on from a user control. Is it just a matter of concatenating a bunch of Request variables together? If so which ones? Or is there a more simpiler way?...

Trying to merge 2 dataframes but get ValueError

These are my two dataframes saved in two variables: > print(df.head()) > club_name tr_jan tr_dec year 0 ADO Den Haag 1368 1422 2010 1 ADO Den Haag 1455 1477 2011 2 ADO Den Haag 1461 1443 2012 ...

React onClick and preventDefault() link refresh/redirect?

I'm rendering a link with react: render: -> `<a className="upvotes" onClick={this.upvote}>upvote</a>` Then, above I have the upvote function: upvote: -> // do stuff (ajax) Before link I had span in that place but I need to...

React Hook Warnings for async function in useEffect: useEffect function must return a cleanup function or nothing

I was trying the useEffect example something like below: useEffect(async () => { try { const response = await fetch(`https://www.reddit.com/r/${subreddit}.json`); const json = await response.json(); setPosts(json.data.c...

Using Postman to access OAuth 2.0 Google APIs

I am trying to access Proximity Google API using Postman chrome app. I have followed tutorials on postman and google dev website but I'm still getting 401 error message. What am I doing? Step 1 - Enable Proximity API: In order to use Proximity ...

Showing/Hiding Table Rows with Javascript - can do with ID - how to do with Class?

I have a table which lists merchandise in a Guitar Store - each row contains one piece of merchandise. Each row (and each piece of merchandise) is either New, Used or on Consignment. I'd like for a user to be able to click a link in a sidebar UL (cli...

How to compile c# in Microsoft's new Visual Studio Code?

I have installed the preview version of Microsoft's new code editor "Visual Studio Code". It seems quite a nice tool! The introduction mentions you can program c# with it, but the setup document does not mention how to actually compile c# files. ...

Display curl output in readable JSON format in Unix shell script

In my Unix shell script, when I execute a curl command, the result will be displayed as below which I am redirecting to file: {"type":"Show","id":"123","title":"name","description":"Funny","channelTitle":"ifood.tv","lastUpdateTimestamp":"2014-04-20T...

When should I use mmap for file access?

POSIX environments provide at least two ways of accessing files. There's the standard system calls open(), read(), write(), and friends, but there's also the option of using mmap() to map the file into virtual memory. When is it preferable to use o...

Play/pause HTML 5 video using JQuery

I am trying to control HTML5 videos using JQuery. I have two clips in a tabbed interface, there are six tabs in total, the others just have images. I am trying to make the video clips play when their tab is clicked and then stop when any of the other...

How to select Multiple images from UIImagePickerController

In my application, I have to select more images ie; up to 3 images from library or capture of images....

How to add comments into a Xaml file in WPF?

I used this syntax as I found online but it throws an error: xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" <!-- Cool comment --> xmlns:System="clr-namespace:System;assembly=mscorlib" 'Name cannot begin with the '<' character, ...

Why is there no multiple inheritance in Java, but implementing multiple interfaces is allowed?

Java doesn't allow multiple inheritance, but it allows implementing multiple interfaces. Why?...

Best way to split string into lines

How do you split multi-line string into lines? I know this way var result = input.Split("\n\r".ToCharArray(), StringSplitOptions.RemoveEmptyEntries); looks a bit ugly and loses empty lines. Is there a better solution?...

How do I change db schema to dbo

I imported a bunch of tables from an old sql server (2000) to my 2008 database. All the imported tables are prefixed with my username, for example: jonathan.MovieData. In the table properties it lists jonathan as the db schema. When I write stored...

Set Date in a single line

According to the Java API, the constructor Date(year, month, day) is deprecated. I know that I can replace it with the following code: Calendar myCal = Calendar.getInstance(); myCal.set(Calendar.YEAR, theYear); myCal.set(Calendar.MONTH, theMonth); m...

Animate change of view background color on Android

How do you animate the change of background color of a view on Android? For example: I have a view with a red background color. The background color of the view changes to blue. How can I do a smooth transition between colors? If this can't be d...

Vuejs: v-model array in multiple input

I have an input text field with a v-model attached, and every time someone hits the "Add" button, another input text get added to the DOM with the same v-model attached. I thought I'd then get an array of the v-model values, but it only gets the valu...

Why should we typedef a struct so often in C?

I have seen many programs consisting of structures like the one below typedef struct { int i; char k; } elem; elem user; Why is it needed so often? Any specific reason or applicable area?...

Get file name from a file location in Java

I have a String that provides an absolute path to a file (including the file name). I want to get just the file's name. What is the easiest way to do this? It needs to be as general as possible as I cannot know in advance what the URL will be. I can...

Import JavaScript file and call functions using webpack, ES6, ReactJS

Trying to do something I would think would be very simple. I would like to import an existing JavaScript library and then call it's functions. So for example I would like to import blah.js and then call blah(). import React from 'react'; import {b...

How do I obtain a list of all schemas in a Sql Server database

I want to retrieve a list of all schemas in a given Sql Server database. Using the ADO.NET schema retrieval API I get a list of all collections but there is no collection for 'Schemas'. I could traverse the 'Tables', 'Procedures' collections (and oth...

How to navigate back to the last cursor position in Visual Studio Code?

What is the keyboard shortcut navigate back to the last cursor position in Visual Studio Code?...

How to wait in bash for several subprocesses to finish and return exit code !=0 when any subprocess ends with code !=0?

How to wait in a bash script for several subprocesses spawned from that script to finish and return exit code !=0 when any of the subprocesses ends with code !=0 ? Simple script: #!/bin/bash for i in `seq 0 9`; do doCalculations $i & done wai...

Adding an img element to a div with javascript

I am trying to add an img to the placehere div using JavaScript, however I am having no luck. Can anyone give me a hand with my code? <html> <script type="text/javascript"> var elem = document.createElement("img"); elem.setAttribute("src...

How to send value attribute from radio button in PHP

I am struggling with sending the value of a radiobutton to an email. I have coded 2 radiobuttons, where I have set the first on to be default checked. The form and values work, however the radio button value is not submitted. Any wise words?...

What is the difference between user variables and system variables?

What is the difference between user variables such as PATH, TMP, etc. and system variables? I accidentally deleted the user variable PATH. What am I supposed to do?...

How to call same method for a list of objects?

Suppose code like this: class Base: def start(self): pass def stop(self) pass class A(Base): def start(self): ... do something for A def stop(self) .... do something for A class B(Base): def star...

When should I use curly braces for ES6 import?

It seems to be obvious, but I found myself a bit confused about when to use curly braces for importing a single module in ES6. For example, in the React-Native project I am working on, I have the following file and its content: File initialState.js v...

CodeIgniter: How to use WHERE clause and OR clause

I am using the following code to select from a MySQL database with a Code Igniter webapp: $query = $this->db->get_where('mytable',array('id'=>10)); This works great! But I want to write the following MySQL statement using the CI library? ...

How do I import a .dmp file into Oracle?

I have a .dmp file that I would like to import into Oracle 9i. How do I do that?...

Simulate Keypress With jQuery

Using jQuery, how can I simulate (trigger?) a KeyPress when a link is clicked? For example, when a user clicks the following link: <a id="clickforspace" href="#">Click Here</a> Then, by clicking the link, it would be as if they presse...

I want to exception handle 'list index out of range.'

I am using BeautifulSoup and parsing some HTMLs. I'm getting a certain data from each HTML (using for loop) and adding that data to a certain list. The problem is, some of the HTMLs have different format (and they don't have the data that I want in...

Android SDK manager won't open

So I installed the android sdk for Windows: http://developer.android.com/sdk/index.html (the installation link) And ran into the path variable problem. So I fixed that by changing "PATH" in enviroment variables to include where my java.exe file ...

Execution order of events when pressing PrimeFaces p:commandButton

I am trying to execute a JSF2 bean method and show a dialog box after completion of the method on click of PrimeFaces <p:commandButton>. <p:commandButton id="viewButton" value="View" actionlistener="#{userBean.setResultsForSelectedRow}"...

IDEA: javac: source release 1.7 requires target release 1.7

When running a JUnit test, using IntelliJ IDEA, I get How can I correct this? Using SDK 1.7 Module language level is 1.7 Maven build works fine. (That's why I believe this in IDEA configuration issue)...

Remove android default action bar

Possible Duplicate: How to hide the title bar for an Activity in XML with existing custom theme i remove the action bar by requestWindowFeature(Window.FEATURE_NO_TITLE); however, when the app starts, the action bar appears in a ver...

Use JSTL forEach loop's varStatus as an ID

I want to use the count from the JSTL forEach loop, but my code doesnt seem to work. <c:forEach items="${loopableObject}" var="theObject" varStatus="theCount"> <div id="divIDNo${theCount}"> </div> </c:forEach> produ...

Uncaught TypeError: undefined is not a function on loading jquery-min.js

I'm building a normal webpage which requires me to load about five CSS files and ten Javascript files. When loading them separately in the HTML page, my webpage loads fine. Now for production, I concatenated all the Javascript into a single file, i...

Number to String in a formula field

I am using a formula field to concatonate 2 decimal values separated by a dash. However, I want the result to trim all unneccesary trailing zeros and decimal points for both values. For example, I want values 10 and 8.5 to be "10 - 8.5". Now it show...

Javascript: Load an Image from url and display

I want to preface this with the fact that I am very very new to JavaScript. I appreciate your patience with me. I'm trying to create a script that allows a user to input a name into a text-area, press submit and an image is displayed based on that n...

getting file size in javascript

given a path of a file like: C:\file.jpg how can i get the size of the file in javascript?...

Is the MIME type 'image/jpg' the same as 'image/jpeg'?

Pretty simple question but can't seem to find it anywhere online. I'm trying to make a program that depending on the file type will give me the extension....

Simpler way to check if variable is not equal to multiple string values?

Current Codes: <?php // See the AND operator; How do I simplify/shorten this line? if( $some_variable !== 'uk' && $some_variable !== 'in' ) { // Do something } ?> And: <?php // See the OR operator; How do I simpl...

Room persistance library. Delete all

How can I delete all entries on specific table using Room Persistence Library? I need to drop table, but I cannot to find any information how to do this. Only when database is migrating or to load all entries and delete them :)...

Subtract two dates in Java

Possible Duplicate: Calculating the Difference Between Two Java Date Instances I know this might be a duplicate thread. But I am trying to figure out a way to compute the difference between two dates. From jquery the date string is in the ...

Adding Permissions in AndroidManifest.xml in Android Studio?

In Eclipse we were able to add permissions in AndroidManifest.xml by going to AndroidManifest.xml->Permission-> Adding permissions. How to add permissions in Android Studio? How can we get a list of all the permissions that we can add to an Activit...

Hide password with "•••••••" in a textField

In my app there is a textField where the user have to put is password in and i want that when he enter a character it change it to '•' how can i do this?...

Thread pooling in C++11

Relevant questions: About C++11: C++11: std::thread pooled? Will async(launch::async) in C++11 make thread pools obsolete for avoiding expensive thread creation? About Boost: C++ boost thread reusing threads boost::thread and creating a pool o...

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

Android studio: emulator is running but not showing up in Run App "choose a running device"

I have launched my emulator via the AVD manager and once it's running I have clicked on run app. I have waited a couple of minutes for my running device to show up in choose a running device but the window always stays blank. ...

Using Cygwin to Compile a C program; Execution error

I'm enrolled in a masters computer science course. The course is using C and the instructor wants us to use Cygwin to compile programs if we are using windows. I've downloaded and installed Cygwin and I've ensured that I've installed the GCC compil...

Adding class to element using Angular JS

I know how to add a class on click of a button in 'jQuery' $('#button1').click(function(){ $('#div1').addClass('alpha'); }); I want to achieve same thing by angular js. I have a controller - myController1. Can someone help me do it eazily?...

LINQ to read XML

I got this XML file: <root> <level1 name="A"> <level2 name="A1" /> <level2 name="A2" /> </level1> <level1 name="B"> <level2 name="B1" /> <level2 name="B2" />...

'if' in prolog?

Is there a way to do an if in prolog, e.g. if a variable is 0, then to do some actions (write text to the terminal). An else isn't even needed, but I can't find any documentation of if....

What is the maximum characters for the NVARCHAR(MAX)?

I have declared a column of type NVARCHAR(MAX) in SQL Server 2008, what would be its exact maximum characters having the MAX as the length?...

Removing underline with href attribute

Possible Duplicate: How to remove the underline for anchors(links)? In the following code below, the link gets underlined when I use the href attribute. <html> <body> <a href="xxx.html">goto this link</a> </body...

Launching an application (.EXE) from C#?

How can I launch an application using C#? Requirements: Must work on Windows XP and Windows Vista. I have seen a sample from DinnerNow.net sampler that only works in Windows Vista....

Sending emails with Javascript

This is a little confusing to explain, so bear with me here... I want to set up a system where a user can send templated emails via my website, except it's not actually sent using my server - it instead just opens up their own local mail client with...

Maximum value for long integer

How can I assign the maximum value for a long integer to a variable, similar, for example, to C++'s LONG_MAX....

Get most recent row for given ID

In the table below, how do I get just the most recent row with id=1 based on the signin column, and not all 3 rows? +----+---------------------+---------+ | id | signin | signout | +----+---------------------+---------+ | 1 | 2011-12-12...

PHP ternary operator vs null coalescing operator

Can someone explain the differences between ternary operator shorthand (?:) and null coalescing operator (??) in PHP? When do they behave differently and when in the same way (if that even happens)? $a ?: $b VS. $a ?? $b ...

Spring + Web MVC: dispatcher-servlet.xml vs. applicationContext.xml (plus shared security)

What is the correct way to use the two contexts: dispatcher-servlet.xml and applicationContext.xml? What goes where? I want to write a fairly typical app deployed in a servlet container. It has some controllers with JSP views. It also has some nontr...

ALTER table - adding AUTOINCREMENT in MySQL

I created a table in MySQL with on column itemID. After creating the table, now I want to change this column to AUTOINCREMENT. How can this be done using ALTER statements? Table definition: ALLITEMS (itemid int(10) unsigned, itemname varchar(50)) I a...

How to use Greek symbols in ggplot2?

My categories need to be named with Greek letters. I am using ggplot2, and it works beautifully with the data. Unfortunately I cannot figure out how to put those greek symbols on the x axis (at the tick marks) and also make them appear in the legen...

How do you create an asynchronous method in C#?

Every blog post I've read tells you how to consume an asynchronous method in C#, but for some odd reason never explain how to build your own asynchronous methods to consume. So I have this code right now that consumes my method: private async void b...

How do I use raw_input in Python 3

import sys print(sys.platform) print(2**100) raw_input() I am using Python 3.1 and can't get the raw_input to "freeze" the dos pop-up. The book I'm reading is for Python 2.5 and I'm using Python 3.1 What should I do to fix this?...

Laravel 4: Redirect to a given url

Is there a method in Redirect class of laravel where the parameter is a complete url? We all know parameters to these methods are just route name,action, slash,..etc but what I want now is like return Redirect::foo('https://bla.com/?yken=KuQxIVTNRc...

How to delete row based on cell value

I have a worksheet, I need to delete rows based on cell value .. Cells to check are in Column A .. If cell contains "-" .. Delete Row I can't find a way to do this .. I open a workbook, copy all contents to another workbook, then delete entire row...

Make child visible outside an overflow:hidden parent

In CSS the overflow:hidden is set on parent containers in order to allow it to expand with the height of their floating children. But it also has another interesting feature when combined with margin: auto... If PREVIOUS sibling is a floating ele...

Access the css ":after" selector with jQuery

I have the following css: .pageMenu .active::after { content: ''; margin-top: -6px; display: inline-block; width: 0px; height: 0px; border-top: 14px solid white; border-left: 14px solid transparent; border-bottom: 14p...

How to change maven java home

I want to change maven java home which is open jdk with sun jdk. How can I do it ? root@ak-EasyNote-TM98:~# mvn -version Apache Maven 3.0.4 Maven home: /usr/share/maven Java version: 1.6.0_24, vendor: Sun Microsystems Inc. Java home: /usr/lib/jvm/ja...

Conditionally Remove Dataframe Rows with R

Using R, how can I write the following logic into the dataframe: IF column A = B and Column E = 0, delete row...

How to make an HTML back link?

What is the simplest way to create an <a> tag that links to the previous web page? Basically a simulated back button, but an actual hyperlink. Client-side technologies only, please. Edit Looking for solutions that have the benefit of showing t...

sql query distinct with Row_Number

I am fighting with the distinct keyword in sql. I just want to display all row numbers of unique (distinct) values in a column & so I tried: SELECT distinct id, ROW_NUMBER() OVER (ORDER BY id) AS RowNum FROM table ...

How to reverse an animation on mouse out after hover

So, it is possible to have reverse animation on mouse out such as: .class{ transform: rotate(0deg); } .class:hover{ transform: rotate(360deg); } but, when using @keyframes animation, I couldn't get it to work, e.g: .class{ animation-nam...

Remove Elements from a HashSet while Iterating

So, if I try to remove elements from a Java HashSet while iterating, I get a ConcurrentModificationException. What is the best way to remove a subset of the elements from a HashSet as in the following example? Set<Integer> set = new HashSet&l...

How to downgrade the installed version of 'pip' on windows?

On a windows 7 machine I have pip version 1.5.6 installed: pip 1.5.6 from C:\Users\dietz\PNC\tas\ENV\lib\site-packages (python 2.7) In order to find the reason for an error I want to install a different version of pip, which worked fine for me. So...

Margin while printing html page

I am using a separate style-sheet for printing. Is it possible to set right and left margin in the style-sheet which set the print margin (i.e. margin on paper). Thanks. ...

Creating a List of Lists in C#

I seem to be having some trouble wrapping my head around the idea of a Generic List of Generic Lists in C#. I think the problem stems form the use of the <T> argument, which I have no prior experience playing with. Could someone provide a short...

How do I skip a header from CSV files in Spark?

Suppose I give three files paths to a Spark context to read and each file has a schema in the first row. How can we skip schema lines from headers? val rdd=sc.textFile("file1,file2,file3") Now, how can we skip header lines from this rdd?...

Cannot get a text value from a numeric cell “Poi”

I'm trying to consume data from a spreadsheet in Excel, but always of this error, already tried formatting the worksheet to text and number and still the error persists. I saw a person using it resolved cell.setCellType ( Cell.CELL_TYPE_STRING ) ; b...

Unexpected 'else' in "else" error

I get this error: Error: unexpected 'else' in " else" From this if, else statement: if (dsnt<0.05) { wilcox.test(distance[result=='nt'],distance[result=='t'],alternative=c("two.sided"),paired=TRUE) } else { if (dst<0.05) { wil...

script to map network drive

I want to be able to connect to a (wifi) network hard drive from my laptop, but only occasionally. If I use the "Map a network drive" command in WinXP explorer, I have to put in the drive's IP address and name, then the router name and its password. ...

Generate PDF from Swagger API documentation

I have used the Swagger UI to display my REST webservices and hosted it on a server. However this service of Swagger can only be accessed on a particular server. If I want to work offline, does anybody know how I can create a static PDF using the Sw...

How can I load storyboard programmatically from class?

My problem is that I was looking for way to use both storyboard and xib. But I can't find proper way to load and show storyboard programmatically. Project was started developing with xib, and now it's very hard to nest all xib files in storyboard. So...

How to Code Double Quotes via HTML Codes

In HTML, What is the preferred way to specify html codes like ", and what is the major differences? For example: &quot; <!-- friendly code --> &#34; <!-- numerical code --> &#x22; <!-- hex code --> Which one...

How to check heap usage of a running JVM from the command line?

Can I check heap usage of a running JVM from the commandline, I mean the actual usage rather than the max amount allocated with Xmx. I need it to be commandline because I don't have access to a windowing environment, and I want script based on the v...

Error :The remote server returned an error: (401) Unauthorized

I want get picture of internet and insert into word . I use this code . MainDocumentPart mainPart = wordprocessingDocument.MainDocumentPart; System.Net.WebRequest request = System.Net.HttpWebRequest.Create("http://spsdev2:1009"); System.Net.W...

How to Save Console.WriteLine Output to Text File

I have a program which outputs various results onto a command line console. How do I save the output to a text file using a StreamReader or other techniques? System.Collections.Generic.IEnumerable<String> lines = File.ReadAllLines(@"C:\Test\n...

'Conda' is not recognized as internal or external command

I installed Anaconda3 4.4.0 (32 bit) on my Windows 7 Professional machine and imported NumPy and Pandas on Jupyter notebook so I assume Python was installed correctly. But when I type conda list and conda --version in command prompt, it says conda is...

How to drop rows of Pandas DataFrame whose value in a certain column is NaN

I have this DataFrame and want only the records whose EPS column is not NaN: >>> df STK_ID EPS cash STK_ID RPT_Date 601166 20111231 601166 NaN NaN 600036 20111231 600036 NaN 12 600016 20111231 ...

How to empty the message in a text area with jquery?

--UPDATED-- I want to empty message in a textarea in callback. Can anyone tell me how to empty it please? I tried $("#message").empty(), but it does not empty it. Thanks in advance. <form method="post" id="form" action="index.php/admin/messa...

How to create and write to a txt file using VBA

I have a file which is manually added or modified based on the inputs. Since most of the contents are repetitive in that file, only the hex values are changing, I want to make it a tool generated file. I want to write the c codes which are going to ...

Change color when hover a font awesome icon?

Base in the Font Awesome documentation I create this icon: <span class="fa-stack fa-5x"> <i class="fa fa-circle fa-stack-2x"></i> <i class="fa fa-flag fa-stack-1x fa-inverse"></i> </span> This code create th...

Spring Boot @autowired does not work, classes in different package

I have a Spring boot application. I get the following error org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'birthdayController': Injection of autowired dependencies failed; nested exception is org....

How to get numeric position of alphabets in java?

How to get numeric position of alphabets in java ? Suppose through command prompt i have entered abc then as a output i need to get 123 how can i get the numeric position of alphabets in java? Thanks in advance....

PostgreSQL query to list all table names?

Is there any query available to list all tables in my Postgres DB. I tried out one query like: SELECT table_name FROM information_schema.tables WHERE table_schema='public' But this query returns views also. How can i get o...

How to read multiple text files into a single RDD?

I want to read a bunch of text files from a hdfs location and perform mapping on it in an iteration using spark. JavaRDD<String> records = ctx.textFile(args[1], 1); is capable of reading only one file at a time. I want to read more than one f...

What is the difference between substr and substring?

What is the difference between alert("abc".substr(0,2)); and alert("abc".substring(0,2)); They both seem to output “ab”....

css absolute position won't work with margin-left:auto margin-right: auto

Say you have the following css applied to a div tag .divtagABS { position: absolute; margin-left: auto; margin-right:auto; } the margin-left and margin-right does not take effect but if you have relative, it works fine i.e. ,divt...

How to check 'undefined' value in jQuery

Possible Duplicate: Detecting an undefined object property in JavaScript javascript undefined compare How we can add a check for an undefined variable, like: function A(val) { if (val == undefined) // do this else // do thi...

Why am I getting a " Traceback (most recent call last):" error?

I'm sorry for asking, but I can't find why I'm getting this errors, especially after the program is running. The erros to be exact are: >>> Welcome! This program will convert measures for you. Select operation. 1.Miles to Kilometers 2.Fah...

How to use Comparator in Java to sort

I learned how to use the comparable but I'm having difficulty with the Comparator. I am having a error in my code: Exception in thread "main" java.lang.ClassCastException: New.People cannot be cast to java.lang.Comparable at java.util.Arrays.merge...

Jquery: How to check if the element has certain css class/style

I have a div: <div class="test" id="someElement" style="position: absolute"></div> Is there any way to check if the certain element: $("#someElement") has a particular class (in my case, "test"). Alternately, is there a way to che...

Python sys.argv lists and indexes

In the below code I understand that sys.argv uses lists, however I am not clear on how the index's are used here. def main(): if len(sys.argv) >= 2: name = sys.argv[1] else: name = 'World' print 'Hello', name if __name__ == '__mai...

Recreate the default website in IIS

I've accidentally deleted the default website in IIS; It no longer shows up in the tree of IIS manager and browsing "localhost" returns a 404 error. I've re-installed IIS, but the default website still doesn't exist... Is it possible to recreate the...

Is there an arraylist in Javascript?

I have a bunch of things I want to add into an array, and I don't know what the size of the array will be beforehand. Can I do something similar to the c# arraylist in javascript, and do myArray.Add(object); repeatedly on it?...

How to kill a child process after a given timeout in Bash?

I have a bash script that launches a child process that crashes (actually, hangs) from time to time and with no apparent reason (closed source, so there isn't much I can do about it). As a result, I would like to be able to launch this process for a ...

How to correctly use the ASP.NET FileUpload control

I'm trying to use the FileUpload control in ASP.NET Here's my current namespace setup: using System; using System.IO; using System.Collections.Generic; using System.Linq; using System.Text; using System.Web; using System.Web.UI; using System.Web.U...

This table does not contain a unique column. Grid edit, checkbox, Edit, Copy and Delete features are not available

The error generated in phpMyAdmin is: This table does not contain a unique column. Grid edit, checkbox, Edit, Copy and Delete features are not available. What does this error message mean and how can I fix it?...

How to add extension methods to Enums

I have this Enum code: enum Duration { Day, Week, Month }; Can I add a extension methods for this Enum?...

Mongodb: Failed to connect to 127.0.0.1:27017, reason: errno:10061

Here is my mongod.cfg file: bind_ip = 127.0.0.1 dbpath = C:\mongodb\data\db logpath = C:\mongodb\log\mongo-server.log verbose=v Here is my mongod service command: mongod -f c:\mongodb\mongod.cfg --install I have installed MongoDB about a week a...

How do I set environment variables from Java?

How do I set environment variables from Java? I see that I can do this for subprocesses using ProcessBuilder. I have several subprocesses to start, though, so I'd rather modify the current process's environment and let the subprocesses inherit it. ...

How to return the output of stored procedure into a variable in sql server

I want to execute a stored procedure in SQL Server and assign the output to a variable (it returns a single value) ?...

python request with authentication (access_token)

I am trying to get an API query into python. The command line curl --header "Authorization:access_token myToken" https://website.com/id gives some json output. myToken is a hexadecimal variable that remains constant throughout. I would like to mak...

Update Git branches from master

I'm new to Git, and now I'm in this situation: I have four branches (master, b1, b2, and b3). After I worked on b1-b3, I realized I have something to change on branch master that should be in all other branches. I changed what I needed in master an...

How do you change the value inside of a textfield flutter?

I have a TextEditingController where if a user clicks a button it fills in with information. I can't seem to figure out how to change the text inside of a Textfield or TextFormField. Is there a solution?...

how to convert JSONArray to List of Object using camel-jackson

Am having the String of json array as follow {"Compemployes":[ { "id":1001, "name":"jhon" }, { "id":1002, "name":"jhon" } ]} i want to convert this this jsonarray to List<Empol...

printing all contents of array in C#

I am trying to print out the contents of an array after invoking some methods which alter it, in Java I use: System.out.print(Arrays.toString(alg.id)); how do I do this in c#?...

How to capitalize first letter of each word, like a 2-word city?

My JS woks well when the city has one word: cHIcaGO ==> Chicago But when it's san diego ==> San diego How do I make it become San Diego? function convert_case() { document.profile_form.city.value = document.profile_form.city.valu...

Creating a BLOB from a Base64 string in JavaScript

I have Base64-encoded binary data in a string: const contentType = 'image/png'; const b64Data = 'iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg=='; I would like to create a blob: ...

Get method arguments using Spring AOP?

I am using Spring AOP and have below aspect: @Aspect public class LoggingAspect { @Before("execution(* com.mkyong.customer.bo.CustomerBo.addCustomer(..))") public void logBefore(JoinPoint joinPoint) { System.out.println("logBefore(...

Program to find largest and smallest among 5 numbers without using array

Yesterday I went for an interview where I have been asked to create a program to find largest and smallest among 5 numbers without using array. I know how to create the program using array. int largestNumber; int smallestNumber; int numbers[n]; l...

Try-catch-finally-return clarification

By reading all the questions already asked in this forum related to the topic above (see title), I thoroughly understand that finally gets always called. (except from System.exit and infinite loops). However, I would like to know if a return is call...

How to use the new Material Design Icon themes: Outlined, Rounded, Two-Tone and Sharp?

Google has revamped its Material Design Icons with 4 new preset themes: Outlined, Rounded, Two-Tone and Sharp, in addition to the regular Filled/Baseline theme: But, unfortunately, it doesn't say anywhere how to use the new themes. I've been using ...

Warning: mysqli_query() expects at least 2 parameters, 1 given. What?

I made a PHP page that is supposed to select two names from a database and displays them. It just says: Warning: mysqli_query() expects at least 2 parameters, 1 given in /home/tdoylex1/public_html/dorkhub/index.php on line 4 Warning: mysqli_query() ...

Java String to JSON conversion

i am getting data from restful api in String variable now i want to convert to JSON object but i am having problem while conversion it throws exception .Here is my code : URL url = new URL("SOME URL"); HttpURLConnection conn = (HttpURLConnection) u...

Android getActivity() is undefined

I have errors in my class MainActivity. The error: The method getActivity() is undefined for the type MainActivity public class MainActivity extends SherlockFragmentActivity{ PlaceSlidesFragmentAdapter mAdapter; ViewPager mPager; PageIn...

Getting the last argument passed to a shell script

$1 is the first argument. $@ is all of them. How can I find the last argument passed to a shell script?...

is python capable of running on multiple cores?

Question: Because of python's use of "GIL" is python capable running its separate threads simultaneously? Info: After reading this I came away rather uncertain on whether or not python is capable of taking advantage of a multi-core processor. As ...

How do I exclude Weekend days in a SQL Server query?

How do I exclude values in a DateTime column that are Saturdays or Sundays? For example, given the following data: date_created '2009-11-26 09:00:00' -- Thursday '2009-11-27 09:00:00' -- Friday '2009-11-28 09:00:00' -- Saturday '2009-11-29 09:00...

POST Content-Length exceeds the limit

I get similar errors in my error_log in php when users are uploading their files PHP Warning: POST Content-Length of 11933650 bytes exceeds the limit of 8388608 bytes in Unknown on line 0 In my php.ini (created custom ini file in public_html)...

Side-by-side list items as icons within a div (css)

I am looking for a way to create a <ul> of items that I can put within a <div> and have them show up side-by-side and wrap to the next line as the browser window is resized. For example, if we have 10 items in the list that currently s...

How to connect wireless network adapter to VMWare workstation?

How can I connect wireless network adapter to wmvare workstation ?(My Host OS is Win Seven Ultimate, my Guest OS is Fedora 13 & my VMWare version is 6.5.0) I'm running win seven on my Dell Vostro A860 laptop & my wireless network adapter is A...

How to see which flags -march=native will activate?

I'm compiling my C++ app using GCC 4.3. Instead of manually selecting the optimization flags I'm using -march=native, which in theory should add all optimization flags applicable to the hardware I'm compiling on. But how can I check which flags is it...

Accessing variables from other functions without using global variables

I've heard from a variety of places that global variables are inherently nasty and evil, but when doing some non-object oriented Javascript, I can't see how to avoid them. Say I have a function which generates a number using a complex algorithm using...

Oracle Differences between NVL and Coalesce

Are there non obvious differences between NVL and Coalesce in Oracle? The obvious differences are that coalesce will return the first non null item in its parameter list whereas nvl only takes two parameters and returns the first if it is not null, ...

How to set Java environment path in Ubuntu

I just installed JDK in Ubuntu with sudo apt-get install openjdk-6-jdk command, after the installation where's the Java bin directory located? And how can I set the environment path for that directory? I have little experience with Ubuntu, can anyone...

Send email with PHPMailer - embed image in body

I'm trying to send HTML mail, with PHPMailer, with images. The body is loaded from a html file, that contains all the info. When sending the mail, the image does not appear in the body, although I even send the image also as an attachment. HTML <...

Disable a textbox using CSS

How to disable a textbox in CSS? Currently we are having a textbox in our view which can be enabled/disabled depending on a property in the model. We are having asp.net MVC view; depending on the value of the Model property we need to either render a...

How to set the size of button in HTML

I have some buttons on my pure HTML/JS page. When the page is opened in browser, the button size is normal. But on refresh/reloading page, the button size is reduced. In fact, I have not set the button text value. The button's text is blank. How shou...

SQL-Server: Is there a SQL script that I can use to determine the progress of a SQL Server backup or restore process?

When I backup or restore a database using MS SQL Server Management Studio, I get a visual indication of how far the process has progressed, and thus how much longer I still need to wait for it to finish. If I kick off the backup or restore with a scr...

Programmatically saving image to Django ImageField

Ok, I've tried about near everything and I cannot get this to work. I have a Django model with an ImageField on it I have code that downloads an image via HTTP (tested and works) The image is saved directly into the 'upload_to' folder (the upload_t...

How to activate "Share" button in android app?

i want to add "Share" button to my android app. Like that I added "Share" button, but button is not active. I click, but nothing happens. My code in MainActivity.java: private ShareActionProvider mShareActionProvider; @Override public boolean...

100% width Twitter Bootstrap 3 template

I am a bootstrap newbie and I have a 100% wide template that I want to code with bootstrap. The first column begins at the left corner and I have a Google map the stretches to the rightmost. I thought I could do this with container-fluid class, but t...

Reliable way to convert a file to a byte[]

I found the following code on the web: private byte [] StreamFile(string filename) { FileStream fs = new FileStream(filename, FileMode.Open,FileAccess.Read); // Create a byte array of file stream length byte[] ImageData = new byte[fs.Lengt...

How do I best silence a warning about unused variables?

I have a cross platform application and in a few of my functions not all the values passed to functions are utilised. Hence I get a warning from GCC telling me that there are unused variables. What would be the best way of coding around the warning...

What is the best way to prevent session hijacking?

Specifically this is regarding when using a client session cookie to identify a session on the server. Is the best answer to use SSL/HTTPS encryption for the entire web site, and you have the best guarantee that no man in the middle attacks will be ...

Difference between "char" and "String" in Java

I am reading a book for Java that I am trying to learn, and I have a question. I can't understand what is the difference between the variable type char and String. For example, there is a difference between int and short, the bytes at the memory and ...

How to change the sender's name or e-mail address in mutt?

How can I change the sender's name or e-mail address (From: header) used by mutt?...

Convert Unix timestamp to a date string

Is there a quick, one-liner way to convert a Unix timestamp to a date from the Unix command line? date might work, except it's rather awkward to specify each element (month, day, year, hour, etc.), and I can't figure out how to get it to work properl...

How to get the query string by javascript?

How to extract the query string from the URL in javascript? Thank you!...

How to change the color of a button?

I'm new to android programming. How do I change the color of a button? <Button android:id="@+id/btn" android:layout_width="55dp" android:layout_height="50dp" android:layout_gravity="center" android:text="Button Text" andro...

How do I get a TextBox to only accept numeric input in WPF?

I'm looking to accept digits and the decimal point, but no sign. I've looked at samples using the NumericUpDown control for Windows Forms, and this sample of a NumericUpDown custom control from Microsoft. But so far it seems like NumericUpDown (supp...

Use of #pragma in C

What are some uses of #pragma in C, with examples?...

Search text in stored procedure in SQL Server

I want to search a text from all my database stored procedures. I use the below SQL: SELECT DISTINCT o.name AS Object_Name, o.type_desc FROM sys.sql_modules m INNER JOIN sys.objects o ON m.object_id = o.object_...

What is the Java equivalent of PHP var_dump?

PHP has a var_dump() function which outputs the internal contents of an object, showing an object's type and content. For example: class Person { private $firstName; private $lastName; public function __construct($firstName, $lastName) { ...

Compiling C++11 with g++

I'm trying to update my C++ compiler to C++11. I have searched a bit and I have come to the conclusion that I have to use the flag -std=c++0x or -std=gnu++0x, but I don't know many things about flags. Can anyone help me? (I'm using Ubuntu 12.04.) He...

git add only modified changes and ignore untracked files

I ran "git status" and listed below are some files that were modified/or under the heading "changes not staged for commit". It also listed some untracked files that I want to ignore (I have a ".gitignore" file in these directories). I want to put th...

Mockito, JUnit and Spring

I started to learn about Mockito only today. I wrote some simple test (with JUnit, see below), but I can't figure out how can I use mock object inside Spring's managed beans. What is best practices for working with Spring. How should I inject mocked ...

Just disable scroll not hide it?

I'm trying to disable the html/body scrollbar of the parent while I'm using a lightbox. The main word here is disable. I do not want to hide it with overflow: hidden;. The reason for this is that overflow: hidden makes the site jump and take up the ...

How do I make an Event in the Usercontrol and have it handled in the Main Form?

I have a custom usercontrol and I want to do something relatively simple. When ever a numeric up down in that usercontrol's value changes, have the main form update a display window. This is not a problem if the NUD was not in a usercontrol but I c...

UIView background color in Swift

Is there a way to set the UIView background color with Swift? I know that in Objective-C, you would use self.view.backgroundColor = [UIColor redColor];, but that does not work the same way in Swift. I have looked around and because Swift is only abo...

Pandas dataframe fillna() only some columns in place

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

ASP.NET MVC Ajax Error handling

How do I handle exceptions thrown in a controller when jquery ajax calls an action? For example, I would like a global javascript code that gets executed on any kind of server exception during an ajax call which displays the exception message if in ...

Cannot import XSSF in Apache POI

I am referencing the version 3.7 of the Apache POI and I am getting a "cannot be resolved" error when I do: import org.apache.poi.xssf.usermodel.XSSFWorkbook; Other import statements that reference POI DO NOT give me errors, such as: import org.a...

Convert INT to FLOAT in SQL

I have this Query : SELECT sl.sms_prefix, sum( sl.parts ) , cp.country_name, CAST(SUM(sl.parts) AS NUMERIC(10,4)) * CAST(cp.price AS NUMERIC(10,4)) FROM sms_log sl, sms_transaction st, country_prefix cp WHERE st.customer_id =1 AND st.sendtime >...

Function to calculate distance between two coordinates

I'm currently using the function below and it doesn't work properly. According to Google Maps, the distance between these coordinates (from 59.3293371,13.4877472 to 59.3225525,13.4619422) are 2.2 kilometres while the function returns 1.6 kilometres. ...

Import .bak file to a database in SQL server

I have a file with .bak extension. How can I import this date to a database in SQL Server?...

Change date format in a Java string

I've a String representing a date. String date_s = "2011-01-18 00:00:00.0"; I'd like to convert it to a Date and output it in YYYY-MM-DD format. 2011-01-18 How can I achieve this? Okay, based on the answers I retrieved below, here's somet...

Maven artifact and groupId naming

I'm currently in the process of moving some project from Ant to Maven. Conformist as I am, I want to use well-established conventions for finding groupId and artifactId, but I can't find any detailed conventions (there are some, but they don't cover ...

How can I find script's directory?

Consider the following Python code: import os print os.getcwd() I use os.getcwd() to get the script file's directory location. When I run the script from the command line it gives me the correct path whereas when I run it from a script run by code...

Find and replace entire mysql database

i would like to do a find and replace inside an entire database not just a table. How can i alter the script below to work? update [table_name] set [field_name] = replace([field_name],'[string_to_find]','[string_to_replace]'); Do i just use an a...

How to speed up insertion performance in PostgreSQL

I am testing Postgres insertion performance. I have a table with one column with number as its data type. There is an index on it as well. I filled the database up using this query: insert into aNumber (id) values (564),(43536),(34560) ... I inser...

HTTP URL Address Encoding in Java

My Java standalone application gets a URL (which points to a file) from the user and I need to hit it and download it. The problem I am facing is that I am not able to encode the HTTP URL address properly... Example: URL: http://search.barnesandn...

How do I measure the execution time of JavaScript code with callbacks?

I have a piece of JavaScript code that I am executing using the node.js interpreter. for(var i = 1; i < LIMIT; i++) { var user = { id: i, name: "MongoUser [" + i + "]" }; db.users.save(user, function(err, saved) { if(err || !sav...

Change route params without reloading in Angular 2

I'm making a real estate website using Angular 2, Google Maps, etc. and when a user changes the center of the map I perform a search to the API indicating the current position of the map as well as the radius. The thing is, I want to reflect those va...

disable viewport zooming iOS 10+ safari?

I've update my iPhone 6 plus to iOS 10 beta version and just found that in mobile safari, you can zoom any webpages by double tapping or pinching IGNORE the user-scalable=no code in the meta tag. I don't know whether it's a bug or feature. If it's co...

Excel 2007 - Compare 2 columns, find matching values

I have two colums. Column A and Column B which have email addresses. Column A has about 3000 rows, Column B has about 1800. Is there anyway to compare the two columns, and find any fields that match... And if so, how to either highlight or flag the...

count number of characters in nvarchar column

Does anyone know a good way to count characters in a text (nvarchar) column in Sql Server? The values there can be text, symbols and/or numbers. So far I used sum(datalength(column))/2 but this only works for text. (it's a method based on datalength...

What is the most efficient way to loop through dataframes with pandas?

I want to perform my own complex operations on financial data in dataframes in a sequential manner. For example I am using the following MSFT CSV file taken from Yahoo Finance: Date,Open,High,Low,Close,Volume,Adj Close 2011-10-19,27.37,27.47,27.01,...

Run JavaScript when an element loses focus

I have a standard HTML input that I want to run JavaScript code when it loses focus. Sadly my Google searches did not reveal how to do this. To make it clear, I'm looking for a way to do this: <input type="text" name="name" value="value" onlosef...

Setting up Eclipse with JRE Path

I have downloaded and extracted Eclipse. I have Eclipse in the following directory: C:\Applications\eclipse. When I try and run the executable , I get the following message : I currently have the following folder: C:\Program Files (x86)\Java\jre7...

How to put a delay on AngularJS instant search?

I have a performance issue that I can't seem to address. I have an instant search but it's somewhat laggy, since it starts searching on each keyup(). JS: var App = angular.module('App', []); App.controller('DisplayController', function($scope, $ht...

How to delete an element from an array in C#

Lets say I have this array, int[] numbers = {1, 3, 4, 9, 2}; How can I delete an element by "name"? , lets say number 4? Even ArrayList didn't help to delete? string strNumbers = " 1, 3, 4, 9, 2"; ArrayList numbers = new ArrayList(strNumbers.Spl...

static and extern global variables in C and C++

I made 2 projects, the first one in C and the second one in C++, both work with same behavior. C project: header.h int varGlobal=7; main.c #include <stdio.h> #include <stdlib.h> #include "header.h" void function(int i) { static...

UITextField text change event

How can I detect any text changes in a textField? The delegate method shouldChangeCharactersInRange works for something, but it did not fulfill my need exactly. Since until it returns YES, the textField texts are not available to other observer metho...

Create a new workspace in Eclipse

I don't see any menu item I can use to create a new workspace. What should I use to create a new workspace and move some of the projects from existing default workspace to a new workspace? I am using Windows with Eclipse 3.7....

Given a class, see if instance has method (Ruby)

I know in Ruby that I can use respond_to? to check if an object has a certain method. But, given the class, how can I check if the instance has a certain method? i.e, something like Foo.new.respond_to?(:bar) But I feel like there's gotta be a be...

Unable to allocate array with shape and data type

I'm facing an issue with allocating huge arrays in numpy on Ubuntu 18 while not facing the same issue on MacOS. I am trying to allocate memory for a numpy array with shape (156816, 36, 53806) with np.zeros((156816, 36, 53806), dtype='uint8') and...

AngularJS error: 'argument 'FirstCtrl' is not a function, got undefined'

I noticed the same question was asked a few times here, I tried so solve it but nothing helps. I'm following this tutorial with the egghead videos. But when I get at the section of Controllers and Sharing data between controllers, I can't get it t...

How to get hostname from IP (Linux)?

I'd like to get remote machine/hostname through IP Address. I found lots of answer such as nslookup, host, resloveip, etc.. but I still can't get hostname from my target machine(cent OS, ubuntu etc...) It seems need to register to DNS server? I hav...

Array definition in XML?

In XML, how do I declare array of integers? I can declare it as the following: <numbers type="array"> <value>3</value> <value>2</value> <value>1</value> </numbers> but may be there's sim...

How to get correct timestamp in C#

I would like to get valid timestamp in my application so I wrote: public static String GetTimestamp(DateTime value) { return value.ToString("yyyyMMddHHmmssffff"); } // ...later on in the code String timeStamp = GetTimestamp(new DateTime()); Con...

Parse JSON in TSQL

Is it possible to parse JSON in TSQL? I don't mean to create a JSON string; rather, I want to parse a JSON string passed in as a parameter. ...

Curl error 60, SSL certificate issue: self signed certificate in certificate chain

I try to send curl request with my correct APP_ID, APP_SECRET etc. to the https://oauth.vk.com/access_token?client_id=APP_ID&client_secret=APP_SECRET&code=7a6fa4dff77a228eeda56603b8f53806c883f011c40b72630bb50df056f6479e52a&redirect_uri...

One line if statement not working

<%if @item.rigged %>Yes<%else%>No<%end%> I was thinking of something like this? if @item.rigged ? "Yes" : "No" But it doesn't work. Ruby has the ||= but I"m not even sure how to use that thing. ...

ActionBar text color

how can I change the text color of the ActionBar? I've inherited the Holo Light Theme, I'm able to change the background of the ActionBar but I don't find out what is the attribute to tweak to change the text color. Ok, I'm able to change the text...

How can I declare dynamic String array in Java

I am using String Array declare as zoom z[]=new String[422];. But this array stores value from 0 to 32, so I got null pointer exception after looping value 32. How to solve this problem in java? How can I declare a dynamic array in java ?...

How to convert string to binary?

I am in need of a way to get the binary representation of a string in python. e.g. st = "hello world" toBinary(st) Is there a module of some neat way of doing this?...

Detect if PHP session exists

Facebook now offer subscriptions to users so you can get realtime updates on changes. If my app receives an update, I plan to store it in the database. I would also like to detect if their session exists. If it does then I could update the data in th...

Save bitmap to file function

I'm trying to save a bitmap to file and a specific directly using a function I've created. It's not working. It crashes after bitmap.compress part (before here3). File dir = new File(filepath); if(!dir.exists())dir.mkdirs(); File file ...

Preferred way of getting the selected item of a JComboBox

HI, Which is the correct way to get the value from a JComboBox as a String and why is it the correct way. Thanks. String x = JComboBox.getSelectedItem().toString(); or String x = (String)JComboBox.getSelectedItem(); ...

INSERT VALUES WHERE NOT EXISTS

OK so I'm trying to improve my asp data entry page to ensure that the entry going into my data table is unique. So in this table I have SoftwareName and SoftwareType. I'm trying to get it so if the entry page sends an insert query with parameters th...

How to Convert a Text File into a List in Python

I'm having trouble trying to convert a text file into a list of lists split by commas. Basically, I want: DATE OF OCCURRENCE,WARD,LONGITUDE,LATITUDE 06/04/2011,3,-87.61619704286184,41.82254380664193 06/04/2011,20,-87.62391924557963,41.7936753177009...

LINQ to Entities does not recognize the method

I'm getting the following error when trying to do a linq query: LINQ to Entities does not recognize the method 'Boolean IsCharityMatching(System.String, System.String)' method, and this method cannot be translated into a store expression. I...

How to load data from a text file in a PostgreSQL database?

I have a file like (CSV file): value1|value2|value2.... value1|value2|value2.... value1|value2|value2.... value1|value2|value2.... and would like to load these data into a postgresql table....

how to convert binary string to decimal?

I want to convert binary string in to digit E.g var binary = "1101000" // code for 104 var digit = binary.toString(10); // Convert String or Digit (But it does not work !) console.log(digit); How is it possible? Thanks...

switch case statement error: case expressions must be constant expression

My switch-case statement works perfectly fine yesterday. But when I run the code earlier this morning eclipse gave me an error underlining the case statements in color red and says: case expressions must be constant expression, it is constant I don't...

How to store image in SQLite database

In my application I am uploading an image from gallery and I want to store this image in the SQLite database. How do I store a bitmap in the database? I am converting bitmap to a string and saving it in the database. While retrieving it from the data...

How do I print a double value with full precision using cout?

In my earlier question I was printing a double using cout that got rounded when I wasn't expecting it. How can I make cout print a double using full precision?...

Will the IE9 WebBrowser Control Support all of IE9's features, including SVG?

I recently upgraded to IE9-beta. Now, In my .Net (3.5) WinForm application I want to use WebBrowser control. So my question is, whether the WebBrowser control will exhibit all properties and functions of IE9? My concern is, I want to render some ...

Android Gradle Could not reserve enough space for object heap

I've installed Android Studio 1.1.0. I haven't done anything yet like start new Android application or import anything. Somehow it is trying to build something and it throws sync error. Error:Unable to start the daemon process. This problem mig...

Is there a limit to the length of a GET request?

Is there a limit to the length of a GET request?...

Best practices for Storyboard login screen, handling clearing of data upon logout

I'm building an iOS app using a Storyboard. The root view controller is a Tab Bar Controller. I'm creating the login/logout process, and it's mostly working fine, but I've got a few issues. I need to know the BEST way to set all this up. I want to a...

Download and save PDF file with Python requests module

I am trying to download a PDF file from a website and save it to disk. My attempts either fail with encoding errors or result in blank PDFs. In [1]: import requests In [2]: url = 'http://www.hrecos.org//images/Data/forweb/HRTVBSH.Metadata.pdf' In ...

The CodeDom provider type "Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider" could not be located

It's a WebApi project using VS2015. Step to reproduce: Create an empty WebApi project Change Build output path from "bin\" to "bin\Debug\" Run Everything is working perfectly until I changed Build Output path from "bin\" to "bin\Debug\" In f...

Bootstrap 4, How do I center-align a button?

<div class="container"> <div class="row"> <div class="col-xs-12 col-sm-12 col-md-8"> <div v-for="job in job"> <div class="text-center"> <h1>{{ job.job_title }}</h1> <...

How can I display an RTSP video stream in a web page?

I have an ip camera which provides a live RTSP video stream. I can use VLC media player to view the feed by providing it with the URL: rtsp://cameraipaddress But I need to display the feed on a web page. The camera provider supplied an ActiveX con...

Get input value from TextField in iOS alert in Swift

I'm trying to make an alert message with input, and then get the value from the input. I've found many good tutorials how to make the input text field. but I can't get the value from the alert....

std::wstring VS std::string

I am not able to understand the differences between std::string and std::wstring. I know wstring supports wide characters such as Unicode characters. I have got the following questions: When should I use std::wstring over std::string? Can std::stri...

What is the standard exception to throw in Java for not supported/implemented operations?

In particular, is there a standard Exception subclass used in these circumstances?...

PHP Email sending BCC

I know there are a few similar questions to this but I just can't get it working. Ok, I have a list of emails grabbed from my database in a variable called $emailList. I can get my code to send an email from a form if I put the variable in the $to ...

How to develop or migrate apps for iPhone 5 screen resolution?

The new iPhone 5 display has a new aspect ratio and a new resolution (640 x 1136 pixels). What is required to develop new or transition already existing applications to the new screen size? What should we keep in mind to make applications "universa...

Event when window.location.href changes

I'm writing a Greasemonkey script for a site which at some point modifies location.href. How can I get an event (via window.addEventListener or something similar) when window.location.href changes on a page? I also need access to the DOM of the docu...

Java: How To Call Non Static Method From Main Method?

I'm learning java and now i've the following problem: I have the main method declared as public static void main(String[] args) { ..... } Inside my main method, because it is static I can call ONLY other static method!!! Why ? For example: I hav...

'Class' does not contain a definition for 'Method'

In class Employee I've got some methods, which work fine. Now I wanted to add new method, for example public void ExampleMethod() { } Then I call it Employee employee = new Employee(); employee.ExampleMethod(); ExampleMethod is present...

Find and replace words/lines in a file

I have a file (more specifically, a log4j configuration file) and I want to be able to read in the file and pick out certain lines in the code and replace them. For example, within the file there is a string of text that indicates the directory it is...

Guzzle 6: no more json() method for responses

Previously in Guzzle 5.3: $response = $client->get('http://httpbin.org/get'); $array = $response->json(); // Yoohoo var_dump($array[0]['origin']); I could easily get a PHP array from a JSON response. Now In Guzzle 6, I don't know how to do. ...

AngularJS ng-repeat handle empty list case

I thought this would be a very common thing, but I couldn't find how to handle it in AngularJS. Let's say I have a list of events and want to output them with AngularJS, then that's pretty easy: <ul> <li ng-repeat="event in events">{...

Connection attempt failed with "ECONNREFUSED - Connection refused by server"

I am trying to connect to a networked machine's FileZilla server but my FileZilla Client is giving the following error while connecting. The error is: "Connection attempt failed with ECONNREFUSED - Connection refused by server" Windows Firewall...

Multiple ping script in Python

I'm unable to find any good easy to learn documentation on python and networking. In this instance, I'm just trying to make a easy script which I can ping a number of remote machines. for ping in range(1,10): ip="127.0.0."+str(ping) os.system...

String.equals versus ==

This code separates a string into tokens and stores them in an array of strings, and then compares a variable with the first home ... why isn't it working? public static void main(String...aArguments) throws IOException { String usuario = "Jorm...

android - save image into gallery

i have an app with a gallery of images and i want that the user can save it into his own gallery. I've created an option menu with a single voice "save" to allow that but the problem is...how can i save the image into the gallery? this is my code: ...

How to make MySQL handle UTF-8 properly

One of the responses to a question I asked yesterday suggested that I should make sure my database can handle UTF-8 characters correctly. How I can do this with MySQL?...

Linux find and grep command together

I am trying to find a command or create a Linux script that can do this two comands and list the otuput find . -name '*bills*' -print this prints all the files ./may/batch_bills_123.log ./april/batch_bills_456.log .. from this result I want to ...

How to create a toggle button in Bootstrap

I originally created a web app in HTML, CSS and JavaScript, then was asked to create it again in Bootstrap too. I've done it all fine, but I had toggle buttons in the web app that have changed back to radio (originally checkbox) buttons instead of th...

How to display a readable array - Laravel

After I write: Route::get('/', function() { dd(User::all()); }); And after I refresh the browser I get an unreadable array. Is there a way to get that array in a readable format?...

Update query with PDO and MySQL

Im trying to write an update query with PDO only I cant get my code to execute? try { $conn = new PDO("mysql:host=$hostdb; dbname=$namedb", $userdb, $passdb); $conn->exec("SET CHARACTER SET utf8"); // Sets encoding UTF-8 $conn->setAttrib...

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

I am trying to write a program that will download mp3's off of a website then join them together but whenever I try to download the files I get this error: Traceback (most recent call last): File "/home/tesla/PycharmProjects/OldSpice/Voicemail.py", ...

Accessing a Shared File (UNC) From a Remote, Non-Trusted Domain With Credentials

We've run into an interesting situation that needs solving, and my searches have turned up nill. I therefore appeal to the SO community for help. The issue is this: we have a need to programmatically access a shared file that is not in our domain, a...

Preprocessor check if multiple defines are not defined

I have a selection of #defines in a header that are user editable and so I subsequently wish to check that the defines exist in case a user deletes them altogether, e.g. #if defined MANUF && defined SERIAL && defined MODEL // All...

CSS root directory

I have a style sheet where I include background images. background: url(../Images/myImage.png); problem is, pages from different directories use this css! My CSS files are in a CSS folder, images in an Image folder, and my html pages are in many ...

Get unique values from arraylist in java

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

Access to file download dialog in Firefox

Is there any kind of API that can allow me to manipulate a file download dialog in Firefox? (I want to access the one that appears when user does something, not initiate one myself). What I want to do is to access this dialog from Selenium (and whet...

Generate a range of dates using SQL

I have a SQL query that takes a date parameter (if I were to throw it into a function) and I need to run it on every day of the last year. How to generate a list of the last 365 days, so I can use straight-up SQL to do this? Obviously generating a ...

How do I hide the bullets on my list for the sidebar?

This is a WordPress site, the classes/ID's are generated, I can't just go in and add a class. Yes, I have firebug... but I'm so twisted around and confused as to whether this is coming from BuddyPress or.... that I'm just asking for help on finding ...

Converting a char to uppercase

String lower = Name.toLowerCase(); int a = Name.indexOf(" ",0); String first = lower.substring(0, a); String last = lower.substring(a+1); char f = first.charAt(0); char l = last.charAt(0); System.out.println(l); how would i get the F and L variable...

Can't open and lock privilege tables: Table 'mysql.user' doesn't exist

I installed MySQL community server 5.7.10 using binary zip. I extracted the zip in c:\mysql and created the data folder in c:\mysql\data. I created the config file as my.ini and placed it in c:\mysql (root folder of extracted zip). Below is the conte...

What does -> mean in Python function definitions?

I've recently noticed something interesting when looking at Python 3.3 grammar specification: funcdef: 'def' NAME parameters ['->' test] ':' suite The optional 'arrow' block was absent in Python 2 and I couldn't find any information regarding i...

How to get the URL without any parameters in JavaScript?

If I use: alert(window.location.href); I get everything including query strings. Is there a way to just get the main url part, for example: http://mysite.com/somedir/somefile/ instead of http://mysite.com/somedir/somefile/?foo=bar&loo=goo...

Prevent form redirect OR refresh on submit?

I've searched through a bunch of pages, but can't find my problem, so I had to make a post. I have a form that has a submit button, and when submitted I want it to NOT refresh OR redirect. I just want jQuery to perform a function. Here's the form: ...

Is there an equivalent of 'which' on the Windows command line?

As I sometimes have path problems, where one of my own cmd scripts is hidden (shadowed) by another program (earlier on the path), I would like to be able to find the full path to a program on the Windows command line, given just its name. Is there a...

Generating a unique machine id

I need to write a function that generates an id that is unique for a given machine running a Windows OS. Currently, I'm using WMI to query various hardware parameters and concatenate them together and hash them to derive the unique id. My question i...

What is the best data type to use for money in C#?

What is the best data type to use for money in C#?...

Zooming MKMapView to fit annotation pins?

I am using MKMapView and have added a number of annotation pins to the map about a 5-10 kilometre area. When I run the application my map starts zoomed out to show the whole world, what is the best way to zoom the map so the pins fit the view? EDIT:...

Random integer in VB.NET

I need to generate a random integer between 1 and n (where n is a positive whole number) to use for a unit test. I don't need something overly complicated to ensure true randomness - just an old-fashioned random number. How would I do that?...

Extending an Object in Javascript

I am currently transforming from Java to Javascript, and it's a bit hard for me to figure out how to extend objects the way I want it to do. I've seen several people on the internet use a method called extend on object. The code will look like this:...

Bulk insert with SQLAlchemy ORM

Is there any way to get SQLAlchemy to do a bulk insert rather than inserting each individual object. i.e., doing: INSERT INTO `foo` (`bar`) VALUES (1), (2), (3) rather than: INSERT INTO `foo` (`bar`) VALUES (1) INSERT INTO `foo` (`bar`) VALUES (...

How to move child element from one parent to another using jQuery

I am using the jQuery DataTables plugin. I would like to move the search box (.dataTables_filter) and number of records to display dropdown (.dataTables_length) from their parent element (.dataTables_wrapper) to another div on my page without losing ...

How to retrieve a module's path?

I want to detect whether module has changed. Now, using inotify is simple, you just need to know the directory you want to get notifications from. How do I retrieve a module's path in python?...

How do I rewrite URLs in a proxy response in NGINX

I'm used to using Apache with mod_proxy_html, and am trying to achieve something similar with NGINX. The specific use case is that I have an admin UI running in Tomcat on port 8080 on a server at the root context: http://localhost:8080/ I need to...

What is the role of the package-lock.json?

npm@5 has been published, it has a new feature package-lock.json file (after npm install) which confuses me. I want to know, what is the effect of this file?...

ToggleClass animate jQuery?

I have a section on my website that when a user clicks I would like it to expand, I'm using the jQuery's toggleClass for this... expandable: function(e) { e.preventDefault(); $(this).closest('article').toggleClass('expanded', 1000); } This...

Entity Framework Core: A second operation started on this context before a previous operation completed

I'm working on a ASP.Net Core 2.0 project using Entity Framework Core <PackageReference Include="Microsoft.EntityFrameworkCore" Version="2.0.1" /> <PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="2.0.0" PrivateAss...

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

SHOW PROCESSLIST in MySQL command: sleep

When I run SHOW PROCESSLIST in MySQL database, I get this output: mysql> show full processlist; +--------+------+-----------+--------+---------+-------+-------+-----------------------+ | Id | User | Host | db | Command | Time | Sta...

How to obtain values of request variables using Python and Flask

I'm wondering how to go about obtaining the value of a POST/GET request variable using Python with Flask. With Ruby, I'd do something like this: variable_name = params["FormFieldValue"] How would I do this with Flask?...

Preg_match backtrack error

When I use the regex (.*)*[0] everything works well: preg_match('/(.*)*[0]/', 'this is a test string'); var_dump(preg_last_error()); // no code's returned But when I add another character to char class, it will throw out error: preg_match('/(.*)*...

What is the purpose of using WHERE 1=1 in SQL statements?

Possible Duplicates: Why would a sql query have “where 1 = 1” Why would someone use WHERE 1=1 AND <conditions> in a SQL clause? I've seen that a lot in different query examples and it goes to probably all SQL engines. If...

Error:(9, 5) error: resource android:attr/dialogCornerRadius not found

So I installed android studio 3.0.1 and as soon as it opened the gradle built and showed the following errors. I tried adding dependencies such as design and support but in vain. Could someone help me? Thank you in advance. It shows that some att...

Regex Until But Not Including

For regex what is the syntax for search until but not including? Kinda like: Haystack: The quick red fox jumped over the lazy brown dog Expression: .*?quick -> and then everything until it hits the letter "z" but do not include z ...

c# - approach for saving user settings in a WPF application?

What approach do you recommend for persisting user settings in a WPF windows (desktop) application? Note that the idea is that the user can change their settings at run time, and then can close down the application, then when starting up the applic...

What are the most widely used C++ vector/matrix math/linear algebra libraries, and their cost and benefit tradeoffs?

It seems that many projects slowly come upon a need to do matrix math, and fall into the trap of first building some vector classes and slowly adding in functionality until they get caught building a half-assed custom linear algebra library, and depe...

Javascript Confirm popup Yes, No button instead of OK and Cancel

Javascript Confirm popup, I want to show Yes, No button instead of OK and Cancel. I have used this vbscript code: <script language="javascript"> function window.confirm(str) { execScript('n = msgbox("' + str + '","4132")', "vbscri...

How to count instances of character in SQL Column

I have an sql column that is a string of 100 'Y' or 'N' characters. For example: YYNYNYYNNNYYNY... What is the easiest way to get the count of all 'Y' symbols in each row....

Failed to Connect to MySQL at localhost:3306 with user root

I use Mysql Workbench to connect my database,[ Hostname Port and Username are as shown in figure ,and password is right.When I click Test Connection ,it show as above.But if i use 3307 in place of 3306 as port,it connect sucessfully. What matter lea...

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

Does anyone know how I can copy a SQL Azure database to my development machine? I'd like to stop paying to have a development database in the cloud, but it's the best way to get production data. I copy my production database to a new development data...

Open a PDF using VBA in Excel

I'm trying to open all appropriate PDFs found in the same directory as my Excel workbook using VBA. I've added the Adobe Acrobat xx.x Type Library reference to the project. But when I try to create the .App object I get a "Run-time error '429':" er...

How can I print literal curly-brace characters in a string and also use .format on it?

x = " \{ Hello \} {0} " print(x.format(42)) gives me : Key Error: Hello\\ I want to print the output: {Hello} 42...

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

what exactly is device pixel ratio?

this is mentioned every article about mobile web, but nowhere I can found an explanation of what exactly does this attribute measure. Can anyone please elaborate what does queries like this check? @media only screen and (-webkit-min-device-pixel-rat...

How to create websockets server in PHP

I am looking for a simple code to create a WebSocket server. I found phpwebsockets but it is outdated now and doesn't support the newest protocol. I tried updating it myself but it doesn't seem to work. #!/php -q <?php /* >php -q server.php ...

How do I raise an exception in Rails so it behaves like other Rails exceptions?

I would like to raise an exception so that it does the same thing a normal Rails exception does. Specially, show the exception and stack trace in development mode and show "We're sorry, but something went wrong" page in production mode. I tried the...

How to install Android SDK on Ubuntu?

For my Ubuntu machine, I downloaded the latest version of Android SDK from this page. After extracting the downloaded .tgz file, I was trying to search for installation instructions and found: To get started on Linux: Unpack the .zip file you've dow...

How do malloc() and free() work?

I want to know how malloc and free work. int main() { unsigned char *p = (unsigned char*)malloc(4*sizeof(unsigned char)); memset(p,0,4); strcpy((char*)p,"abcdabcd"); // **deliberately storing 8bytes** cout << p; free(p); //...

How to calculate UILabel width based on text length?

I want to display an image next to a UILabel, however UILabel has variable text length, so I don't know where to place the image. How can I accomplish this?...

How different is Objective-C from C++?

What are the main differences between Objective-C and C++ in terms of the syntax, features, paradigms, frameworks and libraries? *Important: My goal is not to start a performance war between the two languages. I only want real hard facts. In fact, m...

Encoding conversion in java

Is there any free java library which I can use to convert string in one encoding to other encoding, something like iconv? I'm using Java version 1.3....

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

I am having a tough time overcoming this error, I have searched everywhere for that error message and nothing seems relevant to my situation: "failed to execute script new-app" new-app is my python GUI program. When I run pyinstaller using this c...

git: can't push (unpacker error) related to permission issues

I have this problem when i try to push in git: error: insufficient permission for adding an object to repository database ./objects fatal: failed to write object error: unpack failed: unpack-objects abnormal exit To ssh://<repo url>/<repo ...

Create the perfect JPA entity

I've been working with JPA (implementation Hibernate) for some time now and each time I need to create entities I find myself struggling with issues as AccessType, immutable properties, equals/hashCode, ... . So I decided to try and find out the gene...

Change / Add syntax highlighting for a language in Sublime 2/3

I want to change / add syntax highlighting for a language in Sublime 2/3. For example I want the keyword this colored in JavaScript. How can I do that? I know that there is a preference JavaScript File in C:\Program Files\Sublime Text 3\Packages, ...

Difference between Arrays.asList(array) and new ArrayList<Integer>(Arrays.asList(array))

What is the difference between 1.List<Integer> list1 = new ArrayList<Integer>(Arrays.asList(ia)); //copy 2.List<Integer> list2 = Arrays.asList(ia); where ia is array of integers. I came to know that some operations are not all...

How to amend a commit without changing commit message (reusing the previous one)?

Is there a way to amend a commit without vi (or your $EDITOR) popping up with the option to modify your commit message, but simply reusing the previous message?...

insert multiple rows into DB2 database

I want to insert multiple rows into a DB2 table. I have a query that looks like this insert into tableName (col1, col2, col3, col4, col5) values (val1, val2, val3, val4, val5), (val1, val2, val3, val4, val5), (val1, val2, val3, val4, val5), (val1...

Shortcut to create properties in Visual Studio?

I have seen some people creating properties in C# really fast, but how did they do it? What shortcuts are available in Visual Studio (currently using Visual Studio 2010) to create properties? I am using C#. For example, public string my...

phpMyAdmin + CentOS 6.0 - Forbidden

I always get this message when I would like access my phpMyAdmin. w3m localhost/phpmyadmin Forbidden You don't have permission to access /phpmyadmin/ on this server. Apache/2.2.15 (CentOS) Server at localhost Port 80 Install steps: rpm --impor...

How do you automatically set text box to Uppercase?

I am using the following style attribute to set the user input to uppercase so that when the user starts typing in the text box for example railway, then it should be altered to capital letters like RAILWAY without the user having to press the Caps...

Lists in ConfigParser

The typical ConfigParser generated file looks like: [Section] bar=foo [Section 2] bar2= baz Now, is there a way to index lists like, for instance: [Section 3] barList={ item1, item2 } Related question: Python’s ConfigParser unique key...

SELECT query with CASE condition and SUM()

I'm currently using these sql statements. My table has the field CPaymentType which contains "Cash" or "Check". I can sum up the amount of payments by executing 2 SQL statements as shown below. In this case, the user won't even notice the speed diffe...

jQuery event to trigger action when a div is made visible

I'm using jQuery in my site and I would like to trigger certain actions when a certain div is made visible. Is it possible to attach some sort of "isvisible" event handler to arbitrary divs and have certain code run when they the div is made visible...

Resolving javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed Error?

Edit :- Tried to format the question and accepted answer in more presentable way at mine Blog Here is the original issue. I am getting this error: detailed message sun.security.validator.ValidatorException: PKIX path building failed: sun.s...

How do I hide the PHP explode delimiter from submitted form results?

I have created a form which utilizes a .txt file to pull the names of the EMPLOYEES from and breaks them up in the SELECT form option using the PHP explode function. <select name="FakeName" id="Fake-ID" aria-required="true" required> <opti...

How to use java.Set

I'm trying to make it working for quite some time,but just can't seem to get it. I have object Tower built of Block's. I've already made it working using arrays, but I wanted to learn Set's. I'd like to get similar functionality to this: public clas...

127 Return code from $?

What is the meaning of return value 127 from $? in UNIX....

How can I convert string date to NSDate?

I want to convert "2014-07-15 06:55:14.198000+00:00" this string date to NSDate in Swift....

What's the difference between an Angular component and module

I've been watching videos and reading articles but this specific article make me so confused, at the start of the article it says The applications in Angular follow modular structure. The Angular apps will contain many modules, each dedicated to the...

How to pip or easy_install tkinter on Windows

My Idle is throwing errors that and says tkinter can't be imported. Is there a simple way to install tkinter via pip or easy_install? There seem to be a lot of package names flying around for this... This and other assorted variations with tkinter-py...

Windows Forms - Enter keypress activates submit button?

How can I capture enter keypresses anywhere on my form and force it to fire the submit button event?...

String replacement in batch file

We can replace strings in a batch file using the following command set str="jump over the chair" set str=%str:chair=table% These lines work fine and change the string "jump over the chair" to "jump over the table". Now I want to replace the word "...

What is the difference between encrypting and signing in asymmetric encryption?

What is the difference between encrypting some data vs signing some data (using RSA)? Does it simply reverse the role of the public-private keys? For example, I want to use my private key to generate messages so only I can possibly be the sende...

Combining paste() and expression() functions in plot labels

Consider this simple example: labNames <- c('xLab','yLabl') plot(c(1:10),xlab=expression(paste(labName[1], x^2)),ylab=expression(paste(labName[2], y^2))) What I want is for the character entry defined by the variable 'labName, 'xLab' or 'yLab...

SQL Query to find the last day of the month

I need to find the last day of a month in the following format: "2013-05-31 00:00:00:000" Anybody please help out....

Change windows hostname from command line

Is it possible to change the hostname in Windows 2003 from the command line with out-of-the-box tools?...

React / JSX Dynamic Component Name

I am trying to dynamically render components based on their type. For example: var type = "Example"; var ComponentName = type + "Component"; return <ComponentName />; // Returns <examplecomponent /> instead of <ExampleCompon...

Freeze the top row for an html table only (Fixed Table Header Scrolling)

I want to make an html table with the top row frozen (so when you scroll down vertically you can always see it). Is there a clever way to make this happen without javascript? Note that I do NOT need the left column frozen. ...

What is the HTML tabindex attribute?

What is the tabindex attribute used for in HTML?...

JavaScript string with new line - but not using \n

I have a string that has new lines in. I am wanting to convert these to HTML <br>s, but I'm having a hard time detecting them. Imagine a JavaScript string set like this: var foo = "Bob is cool"; They are the kind of new lines that I need to...

How to create a function in SQL Server

Please help me, how to filter words in SQL using a function? I'm having a hard time if I explain it so I'm giving example: ID | WebsiteName | ----------------------------------- 1 | www.yahoo.com | 2 | ...

How do I create sql query for searching partial matches?

I have a set of items in db .Each item has a name and a description.I need to implement a search facility which takes a number of keywords and returns distinct items which have at least one of the keywords matching a word in the name or description. ...

javascript, for loop defines a dynamic variable name

Folks, Not sure if eval() or window() is the answer, but I am trying to loop through an array, and create variables for each item in that array dynamically. My myArray looks like: ['foo','bar','baz'] code: for (var i = myArray.length - 1; i &g...

How do you clear a slice in Go?

What is the appropriate way to clear a slice in Go? Here's what I've found in the go forums: // test.go package main import ( "fmt" ) func main() { letters := []string{"a", "b", "c", "d"} fmt.Println(cap(letters)) fmt.Println(len(...

Html.BeginForm and adding properties

How would I go about adding enctype="multipart/form-data" to a form that is generated by using <% Html.BeginForm(); %>?...

Is an anchor tag without the href attribute safe?

Is it okay to use an anchor tag without including the href attribute, and instead using a JavaScript click event handler? So I would omit the href completely, not even have it empty (href="")....

Hash function that produces short hashes?

Is there a way of encryption that can take a string of any length and produce a sub-10-character hash? I want to produce reasonably unique ID's but based on message contents, rather than randomly. I can live with constraining the messages to intege...

What is the main difference between Collection and Collections in Java?

What is the main difference between Collection and Collections in Java?...

How to support UTF-8 encoding in Eclipse

How can I add UTF-8 support in eclipse? I want to add for example Russian language but eclipse won't support it. What should I do? Please guide me....

How to view the committed files you have not pushed yet?

For example I commit some files, the next day some more files, and so on. After some days I want to view all my committed files and view their difference with the remote repo. Note that I have not pushed anything. I just want to verify that if I push...

Hadoop: «ERROR : JAVA_HOME is not set»

I'm trying to install Hadoop on Ubuntu 11.10. I set the JAVA_HOME variable in the file conf/hadoop-env.sh to: # export JAVA_HOME=/usr/lib/jvm/java-1.6.0-openjdk and then I execute these commands (Standalone Operation): $ mkdir input $ cp conf/*...

How to repeat last command in python interpreter shell?

How do I repeat the last command? The usual keys: Up, Ctrl+Up, Alt-p don't work. They produce nonsensical characters. (ve)[kakarukeys@localhost ve]$ python Python 2.6.6 (r266:84292, Nov 15 2010, 21:48:32) [GCC 4.4.4 20100630 (Red Hat 4.4.4-10)] on ...

CORS with spring-boot and angularjs not working

I am trying to call REST endpoints on one application (spring-boot application) from another (angularjs). The applications are running on the following hosts and ports. REST application, using spring boot, http://localhost:8080 HTML application, us...

Attaching a Sass/SCSS to HTML docs

Hello I am new to web design. I would like to learn how to attach an SCSS file to an HTML file in the head tag : <link href="example" rel="stylesheet/scss" type="text/css"> I tried this but did not see the result....

MVC Form not able to post List of objects

so I have an MVC Asp.net app that is having issues. Essentially, I have a View that contains a form, and its contents are bound to a list of objects. Within this loop, it loads PartialView's with the items being looped over. Now everything works up t...

Sorting table rows according to table header column using javascript or jquery

I have something like this <table> <thead> <tr> <th>S.L.</th> <th>name</th> </tr> </thead> <tbody> <tr> <td&...

pgadmin4 : postgresql application server could not be contacted.

I have installed PostgreSQL 9.6.2 on my Windows 8.1. But the pgadmin4 is not able to contact the local server. I have tried several solutions suggested here in stackoverflow, tried to uninstall and reinstall PostgreSQL 9.6.2 , tried to modify the con...

Having both a Created and Last Updated timestamp columns in MySQL 4.0

I have the following table schema; CREATE TABLE `db1`.`sms_queue` ( `Id` INTEGER UNSIGNED NOT NULL AUTO_INCREMENT, `Message` VARCHAR(160) NOT NULL DEFAULT 'Unknown Message Error', `CurrentState` VARCHAR(10) NOT NULL DEFAULT 'None', `Phone` V...

Mod in Java produces negative numbers

When I calculate int i = -1 % 2 I get -1 in Java. In Python, I get 1 as the result of -1 % 2. What do I have to do to get the same behavior in Java with the modulo function?...

WooCommerce return product object by id

I am creating a custom theme for woocommerce and I need to be able to create a mini product display. I am having problems finding documentation on the woocommerce api. I have a comma delimited list of product IDs that I need to iterate through and di...

How do you send a Firebase Notification to all devices via CURL?

I'm attempting to send out a notification to all app users (on Android), essentially duplicating what happens when a notification is sent via the Firebase admin console. Here is the CURL command I begin with: curl --insecure --header "Authorization:...

How do I change TextView Value inside Java Code?

I am working on a android program. A user clicks on a button I do some math and I would like to change the values that I have on my view in some TextView objects. Can someone please tell me how to do it in my code?...

Convert varchar into datetime in SQL Server

How do I convert a string of format mmddyyyy into datetime in SQL Server 2008? My target column is in DateTime I have tried with Convert and most of the Date style values however I get an error message: 'The conversion of a varchar data type to...

Insert data to MySql DB and display if insertion is success or failure

I am inserting data to a MySQL DB, In case if the insertion fails i need to give an appropriate error message indicating so. According to my code below i will be Echo-ing the message Inserted if the insertion was success or failure. What i want to d...

Is there a way to get element by XPath using JavaScript in Selenium WebDriver?

I am looking for something like: getElementByXpath(//html[1]/body[1]/div[1]).innerHTML I need to get the innerHTML of elements using JS (to use that in Selenium WebDriver/Java, since WebDriver can't find it itself), but how? I could use ID attrib...

How to get exception message in Python properly

What is the best way to get exceptions' messages from components of standard library in Python? I noticed that in some cases you can get it via message field like this: try: pass except Exception as ex: print(ex.message) but in some cases (fo...

Best way to convert list to comma separated string in java

I have Set<String> result & would like to convert it to comma separated string. My approach would be as shown below, but looking for other opinion as well. List<String> slist = new ArrayList<String> (result); StringBuilder rStr...

Generate a heatmap in MatPlotLib using a scatter data set

I have a set of X,Y data points (about 10k) that are easy to plot as a scatter plot but that I would like to represent as a heatmap. I looked through the examples in MatPlotLib and they all seem to already start with heatmap cell values to generate ...

How to call a REST web service API from JavaScript?

I have an HTML page with a button on it. When I click on that button, I need to call a REST Web Service API. I tried searching online everywhere. No clue whatsoever. Can someone give me a lead/Headstart on this? Very much appreciated....

Reading RFID with Android phones

I did enough research on reading RFID tags using Android phones(smart phones). My understanding of this is that for NFC-enabled smart phones (Nexus S) it is possible to read RFID tags, but there are restrictions. For non-NFC-enabled Androids we ne...

rsync error: failed to set times on "/foo/bar": Operation not permitted

I'm getting a confusing error from rsync and the initial things I'm finding from web searches (as well as all the usual chmod'ing) are not solving it: rsync: failed to set times on "/foo/bar": Operation not permitted (1) rsync error: some files coul...

How to define servlet filter order of execution using annotations in WAR

If we define webapp specific servlet filters in WAR's own web.xml, then the order of execution of the filters will be the same as the order in which they are defined in the web.xml. But, if we define those filters using @WebFilter annotation, what i...

Convert UTF-8 encoded NSData to NSString

I have UTF-8 encoded NSData from windows server and I want to convert it to NSString for iPhone. Since data contains characters (like a degree symbol) which have different values on both platforms, how do I convert data to string?...

Use jquery click to handle anchor onClick()

I have a set of dynamically generated anchor tags in a for loop as follows: <div id = "solTitle"> <a href = "#" id = "' + tagId + '" onClick = "openSolution();"> ' + solTitle + '</a></div> <br>'; Once this code is ex...

How can I get javascript to read from a .json file?

My script currently looks like this: <script type="text/javascript"> function updateMe(){ var x = 0; var jsonstr = '{"date":"July 4th", "event":"Independence Day"}'; var activity=JSON.parse(jsonstr); while(x<10){ date ...