Questions Tagged with #List comprehension

A syntactic construct which provides a concise way to create lists in a style similar to the mathematical set-builder notation. Use this tag in conjunction with the tag of the programming language you are using for questions about building new lists with list comprehensions.

Why is there no tuple comprehension in Python?

As we all know, there's list comprehension, like [i for i in [1, 2, 3, 4]] and there is dictionary comprehension, like {i:j for i, j in {1: 'a', 2: 'b'}.items()} but (i for i in (1, 2, 3)) wi..

List comprehension on a nested list?

I have this nested list: l = [['40', '20', '10', '30'], ['20', '20', '20', '20', '20', '30', '20'], ['30', '20', '30', '50', '10', '30', '20', '20', '20'], ['100', '100'], ['100', '100', '100', '100'..

Create list of single item repeated N times

I want to create a series of lists, all of varying lengths. Each list will contain the same element e, repeated n times (where n = length of the list). How do I create the lists, without using a list..

Pythonic way to print list items

I would like to know if there is a better way to print all objects in a Python list than this : myList = [Person("Foo"), Person("Bar")] print("\n".join(map(str, myList))) Foo Bar I read this way is..

Transpose a matrix in Python

I'm trying to create a matrix transpose function in Python. A matrix is a two dimensional array, represented as a list of lists of integers. For example, the following is a 2X3 matrix (meaning the hei..

Is it possible to use 'else' in a list comprehension?

Here is the code I was trying to turn into a list comprehension: table = '' for index in xrange(256): if index in ords_to_keep: table += chr(index) else: table += replace_with..

List comprehension with if statement

I want to compare 2 iterables and print the items which appear in both iterables. >>> a = ('q', 'r') >>> b = ('q') # Iterate over a. If y not in b, print y. # I want to see ['r'] ..

remove None value from a list without removing the 0 value

This was my source I started with. My List L = [0, 23, 234, 89, None, 0, 35, 9] When I run this : L = filter(None, L) I get this results [23, 234, 89, 35, 9] But this is not what I need, w..

if else in a list comprehension

I have a list l: l = [22, 13, 45, 50, 98, 69, 43, 44, 1] For numbers above 45 inclusive, I would like to add 1; and for numbers less than it, 5. I tried [x+1 for x in l if x >= 45 else x+5] ..

Are list-comprehensions and functional functions faster than "for loops"?

In terms of performance in Python, is a list-comprehension, or functions like map(), filter() and reduce() faster than a for loop? Why, technically, they run in a C speed, while the for loop runs in t..

Python: For each list element apply a function across the list

Given [1,2,3,4,5], how can I do something like 1/1, 1/2, 1/3,1/4,1/5, ...., 3/1,3/2,3/3,3/4,3/5,.... 5/1,5/2,5/3,5/4,5/5 I would like to store all the results, find the minimum, and return the two..

Python's most efficient way to choose longest string in list?

I have a list of variable length and am trying to find a way to test if the list item currently being evaluated is the longest string contained in the list. And I am using Python 2.6.1 For example: ..

Create a dictionary with list comprehension

I like the Python list comprehension syntax. Can it be used to create dictionaries too? For example, by iterating over pairs of keys and values: mydict = {(k,v) for (k,v) in blah blah blah} # doesn..

Python Dictionary Comprehension

Is it possible to create a dictionary comprehension in Python (for the keys)? Without list comprehensions, you can use something like this: l = [] for n in range(1, 11): l.append(n) We can sho..

List comprehension vs map

Is there a reason to prefer using map() over list comprehension or vice versa? Is either of them generally more efficient or considered generally more pythonic than the other?..

Fastest way to convert an iterator to a list

Having an iterator object, is there something faster, better or more correct than a list comprehension to get a list of the objects returned by the iterator? user_list = [user for user in user_iterat..

One-line list comprehension: if-else variants

It's more about python list comprehension syntax. I've got a list comprehension that produces list of odd numbers of a given range: [x for x in range(1, 10) if x % 2] This makes a filter - I've got..

Double Iteration in List Comprehension

In Python you can have multiple iterators in a list comprehension, like [(x,y) for x in a for y in b] for some suitable sequences a and b. I'm aware of the nested loop semantics of Python's list co..

Inline for loop

I'm trying to learn neat pythonic ways of doing things, and was wondering why my for loop cannot be refactored this way: q = [1, 2, 3, 4, 1, 2, 5, 1, 2, 3, 4, 5] vm = [-1, -1, -1, -1] for v in vm: ..

Generator expressions vs. list comprehensions

When should you use generator expressions and when should you use list comprehensions in Python? # Generator expression (x*2 for x in range(256)) # List comprehension [x*2 for x in range(256)] ..

Flattening a shallow list in Python

Is there a simple way to flatten a list of iterables with a list comprehension, or failing that, what would you all consider to be the best way to flatten a shallow list like this, balancing performan..

Python using enumerate inside list comprehension

Lets suppose I have a list like this: mylist = ["a","b","c","d"] To get the values printed along with their index I can use Python's enumerate function like this >>> for i,j in enumerate(..

Python for and if on one line

I have a issue with python. I make a simple list: >>> my_list = ["one","two","three"] I want create a "single line code" for find a string. for example, I have this code: >>> [..

How to frame two for loops in list comprehension python

I have two lists as below tags = [u'man', u'you', u'are', u'awesome'] entries = [[u'man', u'thats'],[ u'right',u'awesome']] I want to extract entries from entries when they are in tags: result = [..

How to unzip a list of tuples into individual lists?

Possible Duplicate: A Transpose/Unzip Function in Python I have a list of tuples, where I want to unzip this list into two independent lists. I'm looking for some standardized operation in ..

Add a summary row with totals

I know this sounds crazy and probably should not be done this way but I need something like this - I have a records from SELECT [Type], [Total Sales] From Before I want to add an extra row at the end..

What issues should be considered when overriding equals and hashCode in Java?

What issues / pitfalls must be considered when overriding equals and hashCode?..

Fixing a systemd service 203/EXEC failure (no such file or directory)

I'm trying to set up a simple systemd timer to run a bash script every day at midnight. systemctl --user status backup.service fails and logs the following: backup.service: Failed at step EXEC spawn..

Multiple linear regression in Python

I can't seem to find any python libraries that do multiple regression. The only things I find only do simple regression. I need to regress my dependent variable (y) against several independent variabl..

javascript : sending custom parameters with window.open() but its not working

<html> <head> <script> function open_win() { window.open("http://localhost:8080/login","mywindow") } </script> </head> <body> <input type="button" value="Op..

Maven in Eclipse: step by step installation

I have spent been on the Maven site reading the 5- and 30-minute tutorials, and trialing Maven out for the first time. I want to install a Maven plugin and use it to start building Maven projects fro..

Substring in excel

I have a set of data that shown below on excel. R/V(208,0,32) YR/V(255,156,0) Y/V(255,217,0) R/S(184,28,16) YR/S(216,128,0) Y/S(209,171,0) R/B(255,88,80) YR/B(255,168,40) Y/B(2..

Improving bulk insert performance in Entity framework

I want to insert 20000 records in a table by entity framework and it takes about 2 min. Is there any way other than using SP to improve its performance. This is my code: foreach (Employees item in ..

How to add onload event to a div element

How do you add an onload event to an element? Can I use: <div onload="oQuickReply.swap();" ></div> for this?..

Where do you include the jQuery library from? Google JSAPI? CDN?

There are a few ways to include jQuery and jQuery UI and I'm wondering what people are using? Google JSAPI jQuery's site your own site/server another CDN I have recently been using Google JSAPI, b..

Multi-dimensional arrays in Bash

I am planning a script to manage some pieces of my Linux systems and am at the point of deciding if I want to use bash or python. I would prefer to do this as a Bash script simply because the command..

Selecting non-blank cells in Excel with VBA

I'm just beginning to dive into VBA and I've hit a bit of a roadblock. I have a sheet with 50+ columns, 900+ rows of data. I need to reformat about 10 of those columns and stick them in a new workboo..

Why does Java's hashCode() in String use 31 as a multiplier?

Per the Java documentation, the hash code for a String object is computed as: s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1] using int arithmetic, where s[i] is the ith character of the strin..

How do I revert to a previous package in Anaconda?

If I do conda info pandas I can see all of the packages available. I updated my pandas to the latest this morning, but I need to revert to a prior version now. I tried conda update pandas 0.13.1..

Add Bean Programmatically to Spring Web App Context

Because of a plug-in architecture, I'm trying to add a bean programmatically to my webapp. I have a Spring bean created through the @Component annotation, and i am implementing the ApplicationContext..

Getting binary (base64) data from HTML5 Canvas (readAsBinaryString)

Is there any way of reading the contents of a HTML Canvas as binary data? At the moment I've got the following HTML to show an input file and the canvas below it: <p><button id="myButton" t..

How to specify jdk path in eclipse.ini on windows 8 when path contains space

This doesn't work -vm %JAVA_HOME%/bin/javaw.exe How can I replace %JAVA_HOME% with full path on Windows 8 when path contains space ("Program Files" directory)..

JQuery: if div is visible

I'm using JS as a way of changing the content of an SPA I'm creating. When I press a button to change the content the HTML changes from this: <div id="selectDiv" style="display: none;"> to th..

How to call a PHP function on the click of a button

I have created a page called functioncalling.php that contains two buttons, Submit and Insert. I want to test which function is executed when a button gets clicked. I want the output to appear on the ..

Insert content into iFrame

I am trying to insert some content into a 'blank' iFrame, however nothing is being inserted. HTML: <iframe id="iframe"></iframe> JS: $("#iframe").ready(function() { var $doc = $("..

How to create a temporary directory/folder in Java?

Is there a standard and reliable way of creating a temporary directory inside a Java application? There's an entry in Java's issue database, which has a bit of code in the comments, but I wonder if th..

Remove "whitespace" between div element

This is my HTML code <div id="div1"> <div></div><div></div><div></div><br/><div></div><div></div><div></d..

CronJob not running

I have set up a cronjob for root user in ubuntu environment as follows by typing crontab -e 34 11 * * * sh /srv/www/live/CronJobs/daily.sh 0 08 * * 2 sh /srv/www/live/CronJobs/weekly.sh 0 08 1 *..

How to check for an active Internet connection on iOS or macOS?

I would like to check to see if I have an Internet connection on iOS using the Cocoa Touch libraries or on macOS using the Cocoa libraries. I came up with a way to do this using an NSURL. The way I d..

Twitter Bootstrap Modal Form Submit

I've recently been fiddling around with twitter bootstrap, using java/jboss, and i've been attempting to submit a form from a Modal interface, the form contains just a hidden field and nothing else so..

How to clear text area with a button in html using javascript?

I have button in html <input type="button" value="Clear"> <textarea id='output' rows=20 cols=90></textarea> If I have an external javascript (.js) function, what should I write?..

Printf width specifier to maintain precision of floating-point value

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

Java SecurityException: signer information does not match

I recompiled my classes as usual, and suddenly got the following error message. Why? How can I fix it? java.lang.SecurityException: class "Chinese_English_Dictionary"'s signer information does not ma..

Catch a thread's exception in the caller thread in Python

I'm very new to Python and multithreaded programming in general. Basically, I have a script that will copy files to another location. I would like this to be placed in another thread so I can output..

How do I redirect in expressjs while passing some context?

I am using express to make a web app in node.js. This is a simplification of what I have: var express = require('express'); var jade = require('jade'); var http = require("http"); var app = express..

Java get String CompareTo as a comparator object

I would like to sort and binary search a static array of strings via the String.CompareTo comparator. The problem is that both sorting, and binary searching requires that a Comparator object be passe..

Dealing with "java.lang.OutOfMemoryError: PermGen space" error

Recently I ran into this error in my web application: java.lang.OutOfMemoryError: PermGen space It's a typical Hibernate/JPA + IceFaces/JSF application running on Tomcat 6 and JDK 1.6. Apparentl..

How to remove the last element added into the List?

I have a List in c# in which i am adding list fields.Now while adding i have to check condition,if the condition satisfies then i need to remove the last row added from the list. Here is my sample cod..

Install php-mcrypt on CentOS 6

I have been trying to install php-mcrypt for a while now. Everytime I get the "No package php-mcrypt available." returned to me. Here's what I've tried: root@ip-********** [~]# yum install php-mcrypt..

How do I send a JSON string in a POST request in Go

I tried working with Apiary and made a universal template to send JSON to mock server and have this code: package main import ( "encoding/json" "fmt" "github.com/jmcvetta/napping" "l..

how to convert current date to YYYY-MM-DD format with angular 2

i use this line to get the current date public current_date=new Date(); and i have got this result: Wed Apr 26 2017 10:38:12 GMT+0100 (Afr. centrale Ouest) how can i transform that to this form..

What's in an Eclipse .classpath/.project file?

We recently had an issue with an Eclipse project for one of our team members. Tomcat was not deploying JARs of the application. We eventually noticed the .classpath Eclipse file was not the same as ..

Resize image proportionally with MaxHeight and MaxWidth constraints

Using System.Drawing.Image. If an image width or height exceed the maximum, it need to be resized proportionally . After resized it need to make sure that neither width or height still exceed the lim..

Is it possible to focus on a <div> using JavaScript focus() function?

Is it possible to focus on a <div> using JavaScript focus() function? I have a <div> tag <div id="tries">You have 3 tries left</div> I am trying to focus on the above <d..

Countdown timer using Moment js

I am making a countdown timer for an event page, i used moment js for this. Here is fiddle for this. I am calculating date difference between event date and current date (timestamp), then using "..

mysql.h file can't be found

i'm trying to install connection between c++ and mysql in ubuntu 12.04. i've installed mysql-client, mysql-server, libmysqlclient15-dev, libmysql++-dev. but when i try to compile the code i got the er..

Symbol for any number of any characters in regex?

I'm wondering is there a symbol for any number (including zero) of any characters..

How to get controls in WPF to fill available space?

Some WPF controls (like the Button) seem to happily consume all the available space in its' container if you don't specify the height it is to have. And some, like the ones I need to use right now, t..

arranging div one below the other

I have two inner divs which are nested inside a wrapper div. I want the two inner div's to get arranged one below the other. But as of now they are getting arranged on the same line. _x000D_ _x000D_..

Javascript how to parse JSON array

I'm using Sencha Touch (ExtJS) to get a JSON message from the server. The message I receive is this one : { "success": true, "counters": [ { "counter_name": "dsd", "counter_type":..

How do you clear your Visual Studio cache on Windows Vista?

I have a problem where my ASP.NET controls are not able to be referenced from the code behind files. I found a solution in Stack Overflow question ASP.NET controls cannot be referenced in code-..

A cycle was detected in the build path of project xxx - Build Path Problem

I'm in the process of converting my projects to OSGI bundles using maven and eclipse. Maven builds the stuff just fine, only I get the above error now within Eclipse. How can I find out which project ..

invalid operands of types int and double to binary 'operator%'

After compiling the program I am getting below error invalid operands of types int and double to binary 'operator%' at line "newnum1 = two % (double)10.0;" Why is it so? #include<iostream> ..

Rails: How can I set default values in ActiveRecord?

How can I set default value in ActiveRecord? I see a post from Pratik that describes an ugly, complicated chunk of code: http://m.onkey.org/2007/7/24/how-to-set-default-values-in-your-model class It..

Is there a bash command which counts files?

Is there a bash command which counts the number of files that match a pattern? For example, I want to get the count of all files in a directory which match this pattern: log*..

How to use the PI constant in C++

I want to use the PI constant and trigonometric functions in some C++ program. I get the trigonometric functions with include <math.h>. However, there doesn't seem to be a definition for PI in t..

What's the pythonic way to use getters and setters?

I'm doing it like: def set_property(property,value): def get_property(property): or object.property = value value = object.property I'm new to Python, so i'm still exploring the syntax, a..

global variable for all controller and views

In Laravel I have a table settings and i have fetched complete data from the table in the BaseController, as following public function __construct() { // Fetch the Site Settings object $sit..

CSS background opacity with rgba not working in IE 8

I am using this CSS for background opacity of a <div>: background: rgba(255, 255, 255, 0.3); It’s working fine in Firefox, but not in IE 8. How do I make it work?..

How to stretch a table over multiple pages

I have a Table (multiple rows, multiple columns, see below ) that is longer than one page. How can I tell LaTeX to continue on the next page. Adding a \newpage didn't work Manually 'ending' and 'r..

how to Call super constructor in Lombok

I have a class @Value @NonFinal public class A { int x; int y; } I have another class B @Value public class B extends A { int z; } lombok is throwing error saying it cant find A() c..

Why is my asynchronous function returning Promise { <pending> } instead of a value?

My code: let AuthUser = data => { return google.login(data.username, data.password).then(token => { return token } ) } And when i try to run something like this: let userToken = AuthUser(d..

Node.js connect only works on localhost

I've written a small Node.js app, using connect, that serves up a web page, then sends it regular updates. It also accepts and logs user observations to a disk file. It works fine as long as I am on ..

How to install Android app on LG smart TV?

I have android app apk on my USB, I inserted it in my LG smart tv, it shows me USB device, but apk is not visible... Any ideas what's the issue with it?..

SQLPLUS error:ORA-12504: TNS:listener was not given the SERVICE_NAME in CONNECT_DATA

I downloaded SQLPLUS from Oracle: http://www.oracle.com/technetwork/topics/winx64soft-089540.html Basic Lite and SQL*Plus I then fired up SQL*Plus: c:\Program Files\Oracle\instantclient_12_1>sq..

How is returning the output of a function different from printing it?

In my previous question, Andrew Jaffe writes: In addition to all of the other hints and tips, I think you're missing something crucial: your functions actually need to return something. When yo..

Resize image proportionally with CSS?

Is there a way to resize (scale down) images proportionally using ONLY CSS? I'm doing the JavaScript way, but just trying to see if this is possible with CSS...

Undefined variable: $_SESSION

I'm getting E_NOTICE errors in a core CakePHP file when it tries to reference a never-set or unset session (cake/libs/cake_session.php line 372): function read($name = null) { if (is_null($name))..

Android Closing Activity Programmatically

What is the equivalent operation within an activity to navigating away from the screen. Like when you press the back button, the activity goes out of view. How can this be called from inside an activ..

Maximum Length of Command Line String

In Windows, what is the maximum length of a command line string? Meaning if I specify a program which takes arguments on the command line such as abc.exe -name=abc A simple console application I wro..

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

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

Checking whether a string starts with XXXX

I would like to know how to check whether a string starts with "hello" in Python. In Bash I usually do: if [[ "$string" =~ ^hello ]]; then do something here fi How do I achieve the same in Python..

Adding local .aar files to Gradle build using "flatDirs" is not working

I'm aware of this question: Adding local .aar files to my gradle build but the solution does not work for me. I tried adding this statement to the top level of my build.gradle file: repositories { ..

Downloading video from YouTube

I wish to download a video from YouTube and then extract its audio. Can anyone point me to some C# code to download a video? For clarification purposes, I already know how to extract audio from a ..

What's the best way to get the last element of an array without deleting it?

Ok, I know all about array_pop(), but that deletes the last element. What's the best way to get the last element of an array without deleting it? EDIT: Here's a bonus: $array = array('a' => 'a'..

How to make google spreadsheet refresh itself every 1 minute?

My google spreadsheet is using GOOGLEFINANCE('symbol','price) function to retrieve stock prices of my portfolio. Unfortunately, I have to refresh manually now. How can I make the spreadsheet refresh i..

Insert into a MySQL table or update if exists

I want to add a row to a database table, but if a row exists with the same unique key I want to update the row. For example: INSERT INTO table_name (ID, NAME, AGE) VALUES(1, "A", 19); Let�..

How to zip a whole folder using PHP

I have found here at stackoveflow some codes on how to ZIP a specific file, but how about a specific folder? Folder/ index.html picture.jpg important.txt inside in My Folder, there are files. a..

Redirect Windows cmd stdout and stderr to a single file

I'm trying to redirect all output (stdout + stderr) of a DOS command to a single file: C:\>dir 1> a.txt 2> a.txt The process cannot access the file because it is being used by another proces..

How to automatically close cmd window after batch file execution?

I'm running a batch file that has these two lines: start C:\Users\Yiwei\Downloads\putty.exe -load "MathCS-labMachine1" "C:\Program Files (x86)\Xming\Xming.exe" :0 -clipboard -multiwindow This batc..

With block equivalent in C#?

I know VB.Net and am trying to brush up on my C#. Is there a With block equivalent in C#? Thanks..

Check an integer value is Null in c#

I have got an integer value and i need to check if it is NULL or not. I got it using a null-coalescing operator C#: public int? Age; if ((Age ?? 0)==0) { // do somethig } Now i have to check i..

What is the difference between the remap, noremap, nnoremap and vnoremap mapping commands in Vim?

What is the difference between the remap, noremap, nnoremap and vnoremap mapping commands in Vim?..

How to view the SQL queries issued by JPA?

When my code issues a call like this: entityManager.find(Customer.class, customerID); How can I see the SQL query for this call? Assuming I don't have access to database server to profile/monitor ..

Return the characters after Nth character in a string

I need help! Can someone please let me know how to return the characters after the nth character? For example, the strings I have is "001 baseball" and "002 golf", I want my code to return baseball a..

How to change maven logging level to display only warning and errors?

I want to prevent maven from displaying INFO messages, I want to see only WARNINGS and ERRORS (if any). How can I achieve this, preferably by changing the command line that calls maven?..

what is Array.any? for javascript

I'm looking for a method for javascript returns true or false when it's empty.. something like Ruby any? or empty? [].any? #=> false [].empty? #=> true ..

How do I extract the contents of an rpm?

I have an rpm and I want to treat it like a tarball. I want to extract the contents into a directory so I can inspect the contents. I am familiar with the querying commands of an uninstalled package. ..

Include CSS,javascript file in Yii Framework

How to include a Javascript or CSS file in Yii Framework? I want to create a page on my site that has a little Javascript application running, so I want to include .js and .css files in a specific vi..

Thymeleaf: how to use conditionals to dynamically add/remove a CSS class

By using Thymeleaf as template engine, is it possible to add/remove dynamically a CSS class to/from a simple div with the th:if clause? Normally, I could use the conditional clause as follows: <a..

Execute Immediate within a stored procedure keeps giving insufficient priviliges error

Here is the definition of the stored procedure: CREATE OR REPLACE PROCEDURE usp_dropTable(schema VARCHAR, tblToDrop VARCHAR) IS BEGIN DECLARE v_cnt NUMBER; BEGIN SELECT COUNT(*) INTO v..

Use Excel VBA to click on a button in Internet Explorer, when the button has no "name" associated

I'm trying to use excel to automate the value entering in a time sheet. The time sheet is on a web page. Right now I'm able to load the page, enter my username and password and then entering the time..

How to apply multiple transforms in CSS?

Using CSS, how can I apply more than one transform? Example: In the following, only the translation is applied, not the rotation. li:nth-child(2) { transform: rotate(15deg); transform: trans..

Move to next item using Java 8 foreach loop in stream

I have a problem with the stream of Java 8 foreach attempting to move on next item in loop. I cannot set the command like continue;, only return; works but you will exit from the loop in this case. I ..

Best way to make WPF ListView/GridView sort on column-header clicking?

There are lots of solutions on the internet attempting to fill this seemingly very-basic omission from WPF. I'm really confused as to what would be the "best" way. For example... I want there to be li..

Split string with PowerShell and do something with each token

I want to split each line of a pipe on spaces, and then print each token on its own line. I realise that I can get this result using: (cat someFileInsteadOfAPipe).split(" ") But I want more flexib..

How to change symbol for decimal point in double.ToString()?

I would like to change decimal point to another character in C#. I have a double variable value double value; and when I use the command: Console.WriteLine(value.ToString()); // output is 1,25 I..

Map.Entry: How to use it?

I'm working on creating a calculator. I put my buttons in a HashMap collection and when I want to add them to my class, which extends JPanel, I don't know how can I get the buttons from my collection...

How to change font in ipython notebook

I am fairly new to python and have no html experience. The question has been asked and either not answered at all or not answered in enough detail for me to set the default font within iPython (not ch..

Can we update primary key values of a table?

Can we update primary key values of a table?..

How do I replace part of a string in PHP?

I am trying to get the first 10 characters of a string and want to replace space with '_'. I have $text = substr($text, 0, 10); $text = strtolower($text); But I am not sure what to do next. I..

Using colors with printf

When written like this, it outputs text in blue: printf "\e[1;34mThis is a blue text.\e[0m" But I want to have format defined in printf: printf '%-6s' "This is text" Now I have tried several opt..

Can HTML be embedded inside PHP "if" statement?

I would like to embed HTML inside a PHP if statement, if it's even possible, because I'm thinking the HTML would appear before the PHP if statement is executed. I'm trying to access a table in a dat..

What is the difference between WCF and WPF?

I am a naive developer and I am building up my concepts, I was asked to create a sample application in wcf, and so I am asking a bit subjective question here. I want to know the diffrence and function..

Regex to match URL end-of-line or "/" character

I have a URL, and I'm trying to match it to a regular expression to pull out some groups. The problem I'm having is that the URL can either end or continue with a "/" and more URL text. I'd like to ma..

Fastest way to write huge data in text file Java

I have to write huge data in text[csv] file. I used BufferedWriter to write the data and it took around 40 secs to write 174 mb of data. Is this the fastest speed java can offer? bufferedWriter = new..

Convert a secure string to plain text

I'm working in PowerShell and I have code that successfully converts a user entered password into plain text: $SecurePassword = Read-Host -AsSecureString "Enter password" | convertfrom-securestring ..

YAML: Do I need quotes for strings in YAML?

I am trying to write a YAML dictionary for internationalisation of a Rails project. I am a little confused though, as in some files I see strings in double-quotes and in some without. A few points to ..

error MSB6006: "cmd.exe" exited with code 1

When I'm trying to build my VC++ code using 2010 I'm getting the error message > C:\Program Files\MSBuild\Microsoft.Cpp\v4.0\Microsoft.CppCommon.targets(151,5): error MSB6006: "cmd.exe" exited wit..

How can I select the row with the highest ID in MySQL?

How can I select the row with the highest ID in MySQL? This is my current code: SELECT * FROM permlog WHERE max(id) Errors come up, can someone help me?..

Twitter Bootstrap - how to center elements horizontally or vertically

is there any way to center html elements vertically or horizontally inside the main parents?..

Adding attributes to an XML node

How can I create an xml file dynamically, with the following structure? <Login> <id userName="Tushar" passWord="Tushar"> <Name>Tushar</Name> <Age>24</Ag..

Jquery Open in new Tab (_blank)

I've setup some Jquery based off other StackOverflow questions/answers. The purpose of this script is that it makes an entire div a link based on any a href tag that is inside that div. This works fi..

SQL Server equivalent to MySQL enum data type?

Does SQL Server 2008 have a a data-type like MySQL's enum?..

Activate a virtualenv with a Python script

I want to activate a virtualenv instance from a Python script. I know it's quite easy to do, but all the examples I've seen use it to run commands within the env and then close the subprocess. I sim..

Jenkins could not run git

I've installed Jenkins on my mac (osx lion). But I couldn't get it work. This is the stacktrace I've got: Started by user anonymous Checkout:workspace / /Users/Shared/Jenkins/Home/jobs/test/workspac..

Can I have multiple background images using CSS?

Is it possible to have two background images? For instance, I'd like to have one image repeat across the top (repeat-x), and another repeat across the entire page (repeat), where the one across the e..

How to install easy_install in Python 2.7.1 on Windows 7

I have installed Python 2.7.1 on Windows 7, but I am unable to install easy_install. Please help me...

Naming Classes - How to avoid calling everything a "<WhatEver>Manager"?

A long time ago I have read an article (I believe a blog entry) which put me on the "right" track on naming objects: Be very very scrupulous about naming things in your program. For example if my app..

SVN - Checksum mismatch while updating

When I try to update some files from Subversion, I get the error: org.tigris.subversion.javahl.ClientException: Checksum mismatch while updating 'D:\WWW\Project\\.svn\text-base\import.php.svn-base';..

Using variables inside strings

In PHP I can do the following: $name = 'John'; $var = "Hello {$name}"; // => Hello John Is there a similar language construct in C#? I know there is String.Format(); but I want to know if it..

What are the differences between virtual memory and physical memory?

I am often confused with the concept of virtualization in operating systems. Considering RAM as the physical memory, why do we need the virtual memory for executing a process? Where does this virtual..

CAST DECIMAL to INT

I'm trying to do this: SELECT CAST(columnName AS INT), moreColumns, etc FROM myTable WHERE ... I've looked at the help FAQs here: http://dev.mysql.com/doc/refman/5.0/en/cast-functions.html , it say..

Import and insert sql.gz file into database with putty

I want to insert a sql.gz file into my database with SSH. What should I do? For example I have a database from telephone numbers that name is numbers.sql.gz, what is this type of file and how can I i..

cc1plus: error: unrecognized command line option "-std=c++11" with g++

I'm trying to compile using g++ and either the -std=c++11 or c++0x flags. However, I get this error cc1plus: error: unrecognized command line option "-std=c++11" g++ --version g++ (GCC) 4.1.2 20..

Setting top and left CSS attributes

For some reason I'm unable to set the "top" and "left" CSS attributes using the following JavaScript. var div = document.createElement('div'); div.style.position = 'absolute'; div.style.top = 200; di..

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

In an given Android activity, I would like to start a new activity for the user at some point. Once they leave the first activity and arrive at the second, the first activity is stale and I want to re..

Best way to check that element is not present using Selenium WebDriver with java

Im trying the code below but it seems it does not work... Can someone show me the best way to do this? public void verifyThatCommentDeleted(final String text) throws Exception { new WebDriverWait..

Remove a string from the beginning of a string

I have a string that looks like this: $str = "bla_string_bla_bla_bla"; How can I remove the first bla_; but only if it's found at the beginning of the string? With str_replace(), it removes all bl..

Git diff -w ignore whitespace only at start & end of lines

I love to use git diff -w to ignore whitespace differences. But, I just noticed that it ignores even whitespace differences in the middle of lines. How could I only ignore whitespace differences that ..

How to add a new line of text to an existing file in Java?

I would like to append a new line to an existing file without erasing the current information of that file. In short, here is the methodology that I am using the current time: import java.io.Buffere..

Failed to execute goal org.codehaus.mojo:exec-maven-plugin:1.2:java (default-cli)

Im working on Smooks - Camel Integration.Im stuck with an error.The Build Fails when I try to Run it using mvn exec:java [ERROR]: Failed to execute goal org.codehaus.mojo:exec-maven-plugin:1...

Convert HTML to PDF in .NET

I want to generate a PDF by passing HTML contents to a function. I have made use of iTextSharp for this but it does not perform well when it encounters tables and the layout just gets messy. Is there..

How do I specify the platform for MSBuild?

I am trying to use MSBuild to build a solution with a specified target platform (I need both binaries, x86 and x64). This is how I tried it: C:\WINDOWS\Microsoft.NET\Framework\v3.5>MsBuild Solutio..

Warning: X may be used uninitialized in this function

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

how to convert integer to string?

Possible Duplicate: How to convert from int to string in objective c: example code… How to convert integer to string in Objective C?..

Run a mySQL query as a cron job?

I would like to purge my SQL database from all entires older than 1 week, and I'd like to do it nightly. So, I'm going to set up a cron job. How do I query mySQL without having to enter my password ma..

Positional argument v.s. keyword argument

Based on this A positional argument is a name that is not followed by an equal sign (=) and default value. A keyword argument is followed by an equal sign and an expression that gives its..

Cannot GET / Nodejs Error

I'm using the tutorial found here: http://addyosmani.github.io/backbone-fundamentals/#create-a-simple-web-server and added the following code. // Module dependencies. var application_root = __dirname..

Big-oh vs big-theta

Possible Duplicate: What is the difference between T(n) and O(n)? It seems to me like when people talk about algorithm complexity informally, they talk about big-oh. But in formal situations, I oft..

How to center a checkbox in a table cell?

The cell contains nothing but a checkbox. It is rather wide because of text in the table header row. How do I center the checkbox (with inline CSS in my HTML? (I know)) I tried <td> &..

How to auto-remove trailing whitespace in Eclipse?

The question has two parts, one of which I already have the answer for. How to auto-remove trailing whitespace from the entire file being edited? -> Answer: use the AnyEdit plugin, which can be set ..

How can I get the latest JRE / JDK as a zip file rather than EXE or MSI installer?

I like to be sure that everything will work just by copying the contents of the Java folder and setting the environment variables. I usually run the installer in a virtual machine, zip the \java folde..

SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder". error

Regarding Eclipse IDE (Indigo, Juno and Kepler (32 and 64 bit versions)) Platforms: Windows, Ubuntu, Mac m2e version: 1.1.0.20120530-0009, 1.2.0.20120903-1050, 1.3.0.20130129-0926, 1.4.0.20130601-031..

Re-ordering factor levels in data frame

I have a data.frame as shown below: task measure right m1 left m2 up m3 down m4 front m5 back m6 . . . The task column takes only six different values, which are treated as fac..

How to force a SQL Server 2008 database to go Offline

How do I force my Database to go Offline, without regard to what or who is already using it? I tried: ALTER DATABASE database-name SET OFFLINE; But it's still hanging after 7 min. I want this bec..

SSL error : routines:SSL3_GET_SERVER_CERTIFICATE:certificate verify failed

I have a large number of file download links in a txt file. I am trying to write a python script to download all the files at once, but I end up with the following error: SSLError: [Errno 1] _ssl.c:4..

What should be the values of GOPATH and GOROOT?

I'm trying to install doozer like this: $ goinstall github.com/ha/doozer I get these errors. goinstall: os: go/build: package could not be found locally goinstall: fmt: go/build: package could n..

substring of an entire column in pandas dataframe

I have a pandas dataframe "df". In this dataframe I have multiple columns, one of which I have to substring. Lets say the column name is "col". I can run a "for" loop like below and substring the colu..

Finding the number of days between two dates

How to find number of days between two dates using PHP?..

How do I add images in laravel view?

The thing is, my image is not directly present in my view Route::Get('saakshar',function() { return view('version1'); }); and in my version1.blade.php <?php include(app_path()."/../resources/vi..

batch/bat to copy folder and content at once

I'm writing a batch script that does a copy. I want to script it to copy an entire folder. When I want to copy a single file, I do this copy %~dp0file.txt file.txt If I have a folder with this st..

How do I select the "last child" with a specific class name in CSS?

<ul> <li class="list">test1</li> <li class="list">test2</li> <li class="list">test3</li> <li>test4</li> </ul> How do I sel..

How to set a string's color

Does anyone know how I would set the color of a string that will be printed using System.out? This is the code I currently have: System.out.println("TEXT THAT NEEDS TO BE A DIFFERENT COLOR."); ..

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

What is App.config in C#.NET? How to use it?

I have done a project in C#.NET where my database file is an Excel workbook. Since the location of the connection string is hard coded in my coding, there is no problem for installing it in my system,..

How to add a JAR in NetBeans

Let's say you create a new project, and want it to make use of some 3rd party library, say, widget.jar. Where do you add this JAR: File >> Project Properties >> Libraries >> Compile-Time Libraries; ..

Inserting NOW() into Database with CodeIgniter's Active Record

I want to insert current time in database using mySQL function NOW() in Codeigniter's active record. The following query won't work: $data = array( 'name' => $name , 'email' => ..

Invalid default value for 'dateAdded'

I got a stupid problem with SQL that I can't fix. ALTER TABLE `news` ADD `dateAdded` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP AUTO_INCREMENT , ADD PRIMARY KEY ( `dateAdded` ) Error: (#10..

Can I have multiple :before pseudo-elements for the same element?

Is it possible to have multiple :before pseudos for the same element? .circle:before { content: "\25CF"; font-size: 19px; } .now:before{ content: "Now"; font-size: 19px; color: bl..

.htaccess File Options -Indexes on Subdirectories

I have the following .htaccess line, simple no indexes on root. Options -Indexes What do we add so it propagates to any sub directory instead of having to create one file for each? One .htaccess on..

Openssl : error "self signed certificate in certificate chain"

When I used openssl APIs to validate server certificate (self signed), I got following error : error 19 at 1 depth lookup:self signed certificate in certificate chain As per openssl documentat..

How to use onSavedInstanceState example please

I'm confused when it comes down to saving a state. So I know that onSaveInstanceState(Bundle) is called when the activity is about to be destroyed. But how do you store your information in it and brin..

AngularJS routing without the hash '#'

I'm learning AngularJS and there's one thing that really annoys me. I use $routeProvider to declare routing rules for my application: $routeProvider.when('/test', { controller: TestCtrl, templat..

Multi-line strings in PHP

Consider: $xml = "l"; $xml = "vv"; echo $xml; This will echo vv. Why and how can I do multi-line strings for things like SimpleXML, etc.?..

How to get a index value from foreach loop in jstl

I have a value set in the request object like the following, String[] categoriesList=null; categoriesList = engine.getCategoryNamesArray(); request.setAttribute("categoriesList", categoriesList ); ..

How do I call paint event?

My program draws text on its panel,but if I'd like to remove the text I have to repaint. How do I call(raise) the paint event by hand?..

Windows Scheduled task succeeds but returns result 0x1

I have a scheduled task on a Windows 2008 R2 server. The task includes a Start In directory entry. The task runs, and the batch file it runs does what it is supposed to do. When I run the batch fil..

How to reset AUTO_INCREMENT in MySQL?

How can I reset the AUTO_INCREMENT of a field? I want it to start counting from 1 again. ..

T-SQL datetime rounded to nearest minute and nearest hours with using functions

In SQL server 2008, I would like to get datetime column rounded to nearest hour and nearest minute preferably with existing functions in 2008. For this column value 2007-09-22 15:07:38.850, the outpu..

Delete worksheet in Excel using VBA

I have a macros that generates a number of workbooks. I would like the macros, at the start of the run, to check if the file contains 2 spreadsheets, and delete them if they exist. The code I tried w..

Iterate through a HashMap

What's the best way to iterate over the items in a HashMap?..

Compiler error: "initializer element is not a compile-time constant"

When compiling this code, I get the error "initializer element is not a compile-time constant". Can anyone explain why? #import "PreferencesController.h" @implementation PreferencesController - (id..

Java better way to delete file if exists

We need to call file.exists() before file.delete() before we can delete a file E.g. File file = ...; if (file.exists()){ file.delete(); } Currently in all our project we create a static m..

How to toggle a boolean?

Is there a really easy way to toggle a boolean value in javascript? So far, the best I've got outside of writing a custom function is the ternary: bool = bool ? false : true; ..

Connect Bluestacks to Android Studio

I have recently shifted to android studio. I would like to know how I can test my apps in Bluestacks app player. I had already had the bluestacks connected and working with eclipse using adb connect l..

How to remove spaces from a string using JavaScript?

How to remove spaces in a string? For instance: Input: '/var/www/site/Brand new document.docx' Output: '/var/www/site/Brandnewdocument.docx' ..

How can I style the border and title bar of a window in WPF?

We are developing a WPF application which uses Telerik's suite of controls and everything works and looks fine. Unfortunately, we recently needed to replace the base class of all our dialogs, changing..

In Java, how can I determine if a char array contains a particular character?

Here's what I have: char[] charArray = new char[] {'h','e','l','l','o'}; I want to write something to the effect of: if(!charArray contains 'q'){ break; } I realize that .contains() can't b..

%matplotlib line magic causes SyntaxError in Python script

I try to run the following codes on Spyder (Python 2.7.11): # -*- coding: utf-8 -*- import numpy as np import pandas as pd %matplotlib inline import matplotlib.pyplot as plt import matplotlib.cm a..

Selecting and manipulating CSS pseudo-elements such as ::before and ::after using javascript (or jQuery)

Is there any way to select/manipulate CSS pseudo-elements such as ::before and ::after (and the old version with one semi-colon) using jQuery? For example, my stylesheet has the following rule: .span:..

Get filename from input [type='file'] using jQuery

This is the uploaded form. <form class="alert alert-info"> <div> <b id = "select_file" class="span3" style="font-weight: bold; cursor: pointer; ">Please select image<..

Convert date time string to epoch in Bash

The date time string is in the following format: 06/12/2012 07:21:22. How can I convert it to UNIX timestamp or epoch?..

Batch program to to check if process exists

I want a batch program, which will check if the process notepad.exe exists. if notepad.exe exists, it will end the process, else the batch program will close itself. Here is what I've done: @echo..

What is the use of ByteBuffer in Java?

What are example applications for a ByteBuffer in Java? Please list any example scenarios where this is used. Thank you!..

How to get Rails.logger printing to the console/stdout when running rspec?

Same as title: How to get Rails.logger printing to the console/stdout when running rspec? Eg. Rails.logger.info "I WANT this to go to console/stdout when rspec is running" puts "Like how the puts fun..

How do I replace text inside a div element?

I need to set the text within a DIV element dynamically. What is the best, browser safe approach? I have prototypejs and scriptaculous available. <div id="panel"> <div id="field_name">T..

Download File Using jQuery

How can I prompt a download for a user when they click a link. For example, instead of: <a href="uploads/file.doc">Download Here</a> I could use: <a href="#">Download Here</..

Error: Can't set headers after they are sent to the client

I'm fairly new to Node.js and I am having some issues. I am using Node.js 4.10 and Express 2.4.3. When I try to access http://127.0.0.1:8888/auth/facebook, i'll be redirected to http://127.0.0.1:888..

Why does this CSS margin-top style not work?

I try to add margin values on a div inside another div. All works fine except the top value, it seems to be ignored. But why? What I expected: What I get: Code: _x000D_ _x000D_ #outer {_x000D_ ..

Handling a Menu Item Click Event - Android

I want to create an intent that starts a new activity once a Menu Item is clicked, but I'm not sure how to do this. I've been reading through the android documentation, but my implementation isn't cor..

Replace deprecated preg_replace /e with preg_replace_callback

$result = preg_replace( "/\{([<>])([a-zA-Z0-9_]*)(\?{0,1})([a-zA-Z0-9_]*)\}(.*)\{\\1\/\\2\}/iseU", "CallFunction('\\1','\\2','\\3','\\4','\\5')", $result ); The above code gives a..

Python - IOError: [Errno 13] Permission denied:

I'm getting IOError: [Errno 13] Permission denied and I don't know what is wrong wit this code. I'm trying to read a file given an absolute path (meaning only file.asm), and a relative path (meaning..

Online Internet Explorer Simulators

(Tried to find simular questions / duplicates, failed) I develop on a mac. I love my mac. I develop using Chrome, Firefox, and Safari. I love them all for different reasons. But I have to develop fo..

When doing a MERGE in Oracle SQL, how can I update rows that aren't matched in the SOURCE?

I have a main database and a report database, and I need to sync a table from main into report. However, when an item gets deleted in the main database, I only want to set an IsDeleted flag in the re..

How to detect when cancel is clicked on file input?

How can I detect when the user cancels a file input using an html file input? onChange lets me detect when they choose a file, but I would also like to know when they cancel (close the file choose di..

How does the vim "write with sudo" trick work?

Many of you have probably seen the command that allows you to write on a file that needs root permission, even when you forgot to open vim with sudo: :w !sudo tee % The thing is that I don't get wh..

scp from Linux to Windows

I am running a putty client on a Windows machine to connect successfully to a Linux box. Now I want to be able to copy a file from the Linux machine under the path /home/ubuntu/myfile to C:/Users/Ansh..

Retrieve the position (X,Y) of an HTML element relative to the browser window

I want to know how to get the X and Y position of HTML elements such as img and div in JavaScript relative to the browser window...

Fastest way to duplicate an array in JavaScript - slice vs. 'for' loop

In order to duplicate an array in JavaScript: which of the following is faster to use? ###Slice method var dup_array = original_array.slice(); ###For loop for(var i = 0, len = original_array.length; ..

Exploitable PHP functions

I'm trying to build a list of functions that can be used for arbitrary code execution. The purpose isn't to list functions that should be blacklisted or otherwise disallowed. Rather, I'd like to have ..

Global and local variables in R

I am a newbie for R, and I am quite confused with the usage of local and global variables in R. I read some posts on the internet that say if I use = or <- I will assign the variable in the curren..

Open mvc view in new window from controller

Is there any way to open a view from a controller action in a new window? public ActionResult NewWindow() { // some code return View(); } How would I get the NewWindow.cshtml view to open i..

How to add a touch event to a UIView?

How do I add a touch event to a UIView? I try: UIView *headerView = [[[UIView alloc] initWithFrame:CGRectMake(0, 0, tableView.bounds.size.width, nextY)] autorelease]; [headerView addTarget:self actio..

Initialize a byte array to a certain value, other than the default null?

I'm busy rewriting an old project that was done in C++, to C#. My task is to rewrite the program so that it functions as close to the original as possible. During a bunch of file-handling the previ..