Examples On Programing Languages

How to check if a String contains only ASCII?

The call Character.isLetter(c) returns true if the character is a letter. But is there a way to quickly find if a String only contains the base characters of ASCII?...

Seconds CountDown Timer

I have a lblCountdown with an int value of 60. I want to make the int value of the lblCountDown decrease with seconds until it reaches 0. This is what I have so far: private int counter = 60; private void button1_Click(object sender, EventAr...

MySQL, Check if a column exists in a table with SQL

I am trying to write a query that will check if a specific table in MySQL has a specific column, and if not — create it. Otherwise do nothing. This is really an easy procedure in any enterprise-class database, yet MySQL seems to be an exception. ...

Best way to compare dates in Android

I am trying to compare a date in a String format to the current date. This is how I did it (haven't tested, but should work), but am using deprecated methods. Any good suggestion for an alternative? Thanks. P.S. I really hate doing Date stuff in Jav...

The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication Required?

I want to send an email from my application and i have written following code for sending mail MailMessage msg = new MailMessage(); msg.From = new MailAddress("mymailid"); msg.To.Add("receipientid"); msg.Subject = "test"; msg.Bo...

find -exec with multiple commands

I am trying to use find -exec with multiple commands without any success. Does anybody know if commands such as the following are possible? find *.txt -exec echo "$(tail -1 '{}'),$(ls '{}')" \; Basically, I am trying to print the last line of eac...

Python: how to print range a-z?

1. Print a-n: a b c d e f g h i j k l m n 2. Every second in a-n: a c e g i k m 3. Append a-n to index of urls{hello.com/, hej.com/, ..., hallo.com/}: hello.com/a hej.com/b ... hallo.com/n...

How to get the number of characters in a std::string?

How should I get the number of characters in a string in C++?...

How to create a DateTime equal to 15 minutes ago?

I need to create a DateTime object that represents the current time minus 15 minutes....

Should I declare Jackson's ObjectMapper as a static field?

The Jackson library's ObjectMapper class seems to be thread safe. Does this mean that I should declare my ObjectMapper as a static field like this class Me { private static final ObjectMapper mapper = new ObjectMapper(); } instead of as an in...

How to obtain the query string from the current URL with JavaScript?

I have URL like this: http://localhost/PMApp/temp.htm?ProjectID=462 What I need to do is to get the details after the ? sign (query string) - that is ProjectID=462. How can I get that using JavaScript? What I've done so far is this: var url = wi...

Determine the line of code that causes a segmentation fault?

How does one determine where the mistake is in the code that causes a segmentation fault? Can my compiler (gcc) show the location of the fault in the program?...

How to get the selected date value while using Bootstrap Datepicker?

Using jquery and the Bootstrap Datepicker, how do I get the new date value I selected using the Bootstrap Datepicker? FYI, I'm using Rails 3 and Coffescript. I set up the datapicker using: <input id="startdate" class="span2 datepicker" type="te...

How to print a two dimensional array?

I have a [20][20] two dimensional array that I've manipulated. In a few words I am doing a turtle project with user inputting instructions like pen up = 0 and pen down = 1. When the pen is down the individual array location, for instance [3][4] is ma...

Function pointer to member function

I'd like to set up a function pointer as a member of a class that is a pointer to another function in the same class. The reasons why I'm doing this are complicated. In this example, I would like the output to be "1" class A { public: int f(); in...

How to align checkboxes and their labels consistently cross-browsers

This is one of the minor CSS problems that plagues me constantly. How do folks around Stack Overflow vertically align checkboxes and their labels consistently cross-browser? Whenever I align them correctly in Safari (usually using vertical-align: b...

extract part of a string using bash/cut/split

I have a string like this: /var/cpanel/users/joebloggs:DNS9=domain.com I need to extract the username (joebloggs) from this string and store it in a variable. The format of the string will always be the same with exception of joebloggs and domai...

Angular2 change detection: ngOnChanges not firing for nested object

I know I am not the first to ask about this, but I can't find an answer in the previous questions. I have this in one component <div class="col-sm-5"> <laps [lapsData]="rawLapsData" [selectedTps]="selectedTps" (l...

Reference an Element in a List of Tuples

Sorry in advance, but I'm new to Python. I have a list of tuples, and I was wondering how I can reference, say, the first element of each tuple within the list. I would think it's something like for i in number_of_tuples : first_element = myLis...

Go to URL after OK button if alert is pressed

I need to make sure that when the user clicks OK in a JavaScript alert window, the browser moves to a different URL. Is this possible? ...

how to reference a YAML "setting" from elsewhere in the same YAML file?

I have the following YAML: paths: patha: /path/to/root/a pathb: /path/to/root/b pathc: /path/to/root/c How can I "normalise" this, by removing /path/to/root/ from the three paths, and have it as its own setting, something like: paths: roo...

How to Validate on Max File Size in Laravel?

I'm trying to validate on a max file size of 500kb in Laravel: $validator = Validator::make($request->all(), [ 'file' => 'size:500', ]); But this says that the file should be exactly 500kb big. How can I edit this rule so that it return...

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 the python virtual machine speed?. Suppose that in...

PHP XML Extension: Not installed

So i'm currently installing mybb and went through a very long tutorial on how to do it. The problem is when I get to the requirements check this shows up How does one go about fixing this? I read that I may need to do sudo apt-get install php-xm...

Is List<Dog> a subclass of List<Animal>? Why are Java generics not implicitly polymorphic?

I'm a bit confused about how Java generics handle inheritance / polymorphism. Assume the following hierarchy - Animal (Parent) Dog - Cat (Children) So suppose I have a method doSomething(List<Animal> animals). By all the rules of inheritanc...

Update Row if it Exists Else Insert Logic with Entity Framework

Does anyone have suggestions on the most efficient way to implement "update row if it exists else insert" logic using Entity Framework?...

Sorting an IList in C#

So I came across an interesting problem today. We have a WCF web service that returns an IList. Not really a big deal until I wanted to sort it. Turns out the IList interface doesn't have a sort method built in. I ended up using the ArrayList.Adap...

Core dump file analysis

What are all the things I will need to check while analyzing a core dump file? Please tell me from scratch....

MySQL PHP - SELECT WHERE id = array()?

Possible Duplicate: MySQL query using an array Passing an array to mysql I have an array in PHP: $array = array(1, 4, 5, 7); As you can see, I have an array of different values, but I want to write a MYSQL statement that will check if...

How to insert a row between two rows in an existing excel with HSSF (Apache POI)

Somehow I manage to create new rows between two rows in an existing excel file. The problem is, some of the formatting were not include along the shifting of the rows. One of this, is the row that are hide are not relatively go along during the shi...

How to recompile with -fPIC

I was trying to reinstall my ffmpeg, following this guide, on my ARM Ubuntu machine. Unfortunately, when I compile a program which uses this lib I get the following failure: /usr/bin/ld: /usr/local/lib/libavcodec.a(amrnbdec.o): relocation R_ARM_MOVW...

Determine the number of lines within a text file

Is there an easy way to programmatically determine the number of lines within a text file? ...

Image inside div has extra space below the image

Why in the following code the height of the div is bigger than the height of the img ? There is a gap below the image, but it doesn't seems to be a padding/margin. What is the gap or extra space below image? _x000D_ _x000D_ #wrapper {_x000D_ bor...

dropdownlist set selected value in MVC3 Razor

Here is my model: public class NewsCategoriesModel { public int NewsCategoriesID { get; set; } public string NewsCategoriesName { get; set; } } My controller: public ActionResult NewsEdit(int ID, dms_New dsn) { dsn = (from a i...

Read values into a shell variable from a pipe

I am trying to get bash to process data from stdin that gets piped into, but no luck. What I mean is none of the following work: echo "hello world" | test=($(< /dev/stdin)); echo test=$test test= echo "hello world" | read test; echo test=$test t...

Remove a HTML tag but keep the innerHtml

I have some simple HTML which I need to strip simple formatting. A nice house was found in <b>Toronto</b>. I need to remove the bold, but leave the sentence intact. How is this possible in jQuery?...

Error:(23, 17) Failed to resolve: junit:junit:4.12

Why is it that every time I create a new project in Android Studio, it always comes up with: Error:(23, 17) Failed to resolve: junit:junit:4.12? When I remove testCompile 'junit:junit:4.12' in dependencies it is not a problem anymore. build.gr...

Convert pandas data frame to series

I'm somewhat new to pandas. I have a pandas data frame that is 1 row by 23 columns. I want to convert this into a series? I'm wondering what the most pythonic way to do this is? I've tried pd.Series(myResults) but it complains ValueError: cannot co...

Directory.GetFiles of certain extension

Is there a way to simplify this linq expression, or is there a better way of doing this? Directory.GetFiles(dir, "*.*", SearchOption.AllDirectories) .Where(s => s.EndsWith(".jpg", StringComparison.OrdinalIgnoreCase) || ...

What is the point of WORKDIR on Dockerfile?

I'm learning Docker. For many times I've seen that Dockerfile has WORKDIR command: FROM node:latest RUN mkdir -p /usr/src/app WORKDIR /usr/src/app COPY package.json /usr/src/app/ RUN npm install COPY . /usr/src/app EXPOSE 3000 CMD [ “npm”, “st...

How to make the 'cut' command treat same sequental delimiters as one?

I'm trying to extract a certain (the fourth) field from the column-based, 'space'-adjusted text stream. I'm trying to use the cut command in the following manner: cat text.txt | cut -d " " -f 4 Unfortunately, cut doesn't treat several spaces as on...

Change the Right Margin of a View Programmatically?

Can this attribute be changed dynamically in Java code? android:layout_marginRight I have a TextView, that has to change its position some pixels to the left dynamically. How to do it programmatically? ...

How to generate Javadoc from command line

Can anybody show me how to generate Javadoc from command line? My project contains the package com.test and I want to put the generated documentation in files located in a specific folder like this: C:/javadoc/test....

How do I turn off the output from tar commands on Unix?

I had a look at the options, but nothing seemed obvious as a manner in which to turn off the output when uncompressing a file. The below is the code I am currently using... I just need the option to switch off the output. tar -zxvf tmp.tar.gz -C ~/t...

<button> vs. <input type="button" />. Which to use?

When looking at most sites (including SO), most of them use: <input type="button" /> instead of: <button></button> What are the main differences between the two, if any? Are there valid reasons to use one instead of the other...

Can you style html form buttons with css?

I don't like the default button style. It's really boring. I am using <input type="submit"> type buttons. Can I style these somehow in css? If not, the other way of doing it i guess would be to use a div instead, and make it a link. How do ...

How to set background image in Java?

I am developing a simple platform game using Java using BlueJ as the IDE. Right now I have player/enemy sprites, platforms and other items in the game drawn using polygons and simple shapes. Eventually I hope to replace them with actual images. For ...

How to enable TLS 1.2 in Java 7

I am trying to enable TLS 1.2 in my web app which uses JBoss 6.4 and Java 1.7. I have -Dhttp.protocols = TLSv1.2 in my application environment but it doesn't seem to work for me. Is there anything I could do to enable TLS 1.2? I wrote a simple pro...

Are loops really faster in reverse?

I've heard this quite a few times. Are JavaScript loops really faster when counting backward? If so, why? I've seen a few test suite examples showing that reversed loops are quicker, but I can't find any explanation as to why! I'm assuming it's beca...

Include .so library in apk in android studio

I am trying my hands on developing a simple android application in which I am trying to use sqlcipher, which uses .so libraries internally. I have read the documentation on how to use sqlcipher with android app. I have followed the steps and it compi...

How to display Base64 images in HTML?

I'm having trouble displaying a Base64 image inline. Can someone point me in the right direction? <!DOCTYPE html> <html> <head> <title>Display Image</title> </head> <body> <img style='displ...

Best way to find os name and version in Unix/Linux platform

I need to find the OS name and version on Unix/Linux platform. For this I tried following: lsb_release utility /etc/redhat-release or specific file But it does not seem to be best solution as LSB_RELEASE support is no longer for RHEL 7. Is there...

How to include duplicate keys in HashMap?

I need linked and multiple keys in key set. I tried this: LinkedHashMap<Integer, String> map = new LinkedHashMap< Integer,String>(); map.put( -1505711364,"4"); map.put(294357273, "15"); map.put(-1593134417, "28"); map.put(-1231165758, ...

Is there a built-in function to print all the current properties and values of an object?

So what I'm looking for here is something like PHP's print_r function. This is so I can debug my scripts by seeing what's the state of the object in question....

curl: (35) SSL connect error

[root@vagrant-centos65 you-get]# curl -v https://api.xxx.cn * About to connect() to api.xxx.cn port 443 (#0) * Trying 123.xxx.xx.xx... connected * Connected to api.xxx.cn (123.xxx.xx.xx) port 443 (#0) * Initializing NSS with certpath: sql:/etc/pki...

Is there a C# case insensitive equals operator?

I know that the following is case sensitive: if (StringA == StringB) { So is there an operator which will compare two strings in an insensitive manner?...

Best practice: PHP Magic Methods __set and __get

Possible Duplicate: Are Magic Methods Best practice in PHP? These are simple examples, but imagine you have more properties than two in your class. What would be best practice? a) Using __get and __set class MyClass { private $first...

How do you add an SDK to Android Studio?

I'm using Google's Android Studio 0.1 based on IntelliJ, and I cannot figure out how to add additional SDKs to my project. I exported my existing project from Eclipse to a Gradle project, which I imported into Android Studio, as recommended by Googl...

Java: Getting a substring from a string starting after a particular character

I have a string: /abc/def/ghfj.doc I would like to extract ghfj.doc from this, i.e. the substring after the last /, or first / from right. Could someone please provide some help?...

How do I obtain a Query Execution Plan in SQL Server?

In Microsoft SQL Server how can I get a query execution plan for a query / stored procedure?...

c# replace \" characters

I am sent an XML string that I'm trying to parse via an XmlReader and I'm trying to strip out the \" characters. I've tried .Replace(@"\", "") .Replace("\\''", "''") .Replace("\\''", "\"") plus several other ways. Any ideas?...

Convert Json Array to normal Java list

Is there a way to convert JSON Array to normal Java Array for android ListView data binding?...

Control the size of points in an R scatterplot?

In R, the plot() function takes a pch argument that controls the appearance of the points in the plot. I'm making scatterplots with tens of thousands of points and prefer a small, but not too small dot. Basically, I find pch='.' to be too small, bu...

Is there a difference between "==" and "is"?

My Google-fu has failed me. In Python, are the following two tests for equality equivalent? n = 5 # Test one. if n == 5: print 'Yay!' # Test two. if n is 5: print 'Yay!' Does this hold true for objects where you would be comparing instan...

How to run the sftp command with a password from Bash script?

I need to transfer a log file to a remote host using sftp from a Linux host. I have been provided credentials for the same from my operations group. However, since I don't have control over other host, I cannot generate and share RSA keys with the ot...

Serving static web resources in Spring Boot & Spring Security application

I am trying to develop Spring Boot web application and securing it using Spring security java configuration. After placing my static web resources in 'src/main/resources/public' as advised here in Spring blog, I am able to get the static resources. ...

How to reverse a singly linked list using only two pointers?

I wonder if there exists some logic to reverse a singly-linked list using only two pointers. The following is used to reverse the single linked list using three pointers namely p, q, r: struct node { int data; struct node *link; }; void re...

How to list all methods for an object in Ruby?

How do I list all the methods that a particular object has access to? I have a @current_user object, defined in the application controller: def current_user @current_user ||= User.find(session[:user_id]) if session[:user_id] end And want to see...

Python error message io.UnsupportedOperation: not readable

I made a simple program but It shows the following error when I run it: line1 = [] line1.append("xyz ") line1.append("abc") line1.append("mno") file = open("File.txt","w") for i in range(3): file.write(line1[i]) file.write("\n") for line i...

Add a list item through javascript

So, I am trying to print out an array that gets user input text added to it, but what I want to print out is an ordered list of the array. As you can see, (if you run my code) the list item just keeps getting the user input added to it, and no new li...

Oracle SQL Developer - tables cannot be seen

I was using SQL Developer 1.1. I have recently upgraded to SQL Developer 3. After the upgrade, I noticed that some of my connections do not show their tables. I can do a select on the tables and the data is shown. I can see other objects like views e...

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

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

Loading custom configuration files

I know I can open config files that are related to an assembly with the static ConfigurationManager.OpenExe(exePath) method but I just want to open a config that is not related to an assembly. Just a standard .NET config file....

How to get number of rows inserted by a transaction

I have to manage a log where i have to see the number of rows that are inserted by a transaction. Is there any way of doing it dynamically ?...

How to get full path of selected file on change of <input type=‘file’> using javascript, jquery-ajax?

How to get full path of file while selecting file using <input type=‘file’> <input type="file" id="fileUpload"> <script type="text/javascript"> function getFilePath(){ $('input[type=file]').change(function () { va...

Using Notepad++ to validate XML against an XSD

Can someone explain how to use Notepad++ to validate an xml file against an xsd. There are no options in the "XML Tools" plugin dropdown that provides for specifying an XSD file. The XML plugin is installed properly in the plugins subdir and the 3...

Very Long If Statement in Python

I have a very long if statement in Python. What is the best way to break it up into several lines? By best I mean most readable/common. ...

Cleanest Way to Invoke Cross-Thread Events

I find that the .NET event model is such that I'll often be raising an event on one thread and listening for it on another thread. I was wondering what the cleanest way to marshal an event from a background thread onto my UI thread is. Based on the...

How can I set the color of a selected row in DataGrid

The default background color of a selected row in DataGrid is so dark that I can't read it. Is there anyway of overriding it? Tried this <dg:DataGrid.RowStyle> <Style TargetType="{x:Type dg:DataGridRow}"> <Style.Triggers...

Can't append <script> element

Any idea why the piece of code below does not add the script element to the DOM? var code = "<script></script>"; $("#someElement").append(code); ...

Regex to get string between curly braces

Unfortunately, despite having tried to learn regex at least one time a year for as many years as I can remember, I always forget as I use them so infrequently. This year my new year's resolution is to not try and learn regex again - So this year to s...

How to use LocalBroadcastManager?

How to use/locate LocalBroadcastManager as described in google docs and Service broadcast doc? I tried to google it, but there is no code available to start with? The documents say that I should use it if I want to do broadcast internally with in m...

What are the calling conventions for UNIX & Linux system calls (and user-space functions) on i386 and x86-64

Following links explain x86-32 system call conventions for both UNIX (BSD flavor) & Linux: http://www.int80h.org/bsdasm/#system-calls http://www.freebsd.org/doc/en/books/developers-handbook/x86-system-calls.html But what are the x86-64 system...

Android ViewPager with bottom dots

I want to add 3 bottom dots to my ViewPager, like this. I use FragmentActivity and support library ViewPager....

ASP.NET MVC - Attaching an entity of type 'MODELNAME' failed because another entity of the same type already has the same primary key value

In a nutshell the exception is thrown during POSTing wrapper model and changing the state of one entry to 'Modified'. Before changing the state, the state is set to 'Detached' but calling Attach() does throw the same error. I'm using EF6. Please fin...

How to set value to variable using 'execute' in t-sql?

DECLARE @dbName nvarchar(128) = 'myDb' DECLARE @siteId int exec ('SELECT TOP 1 @siteId = Id FROM ' + @dbName + '..myTbl') select @siteId When I run the script above I get the following error Msg 137, Level 15, State 1, Line 1 Must declare the s...

Maven does not find JUnit tests to run

I have a maven program, it compiles fine. When I run mvn test it does not run any tests (under TESTs header says There are no tests to run.). I've recreated this problem with a super simple setup which I will include below as well as the output w...

What is the function __construct used for?

I have been noticing __construct a lot with classes. I did a little reading and surfing the web, but I couldn't find an explanation I could understand. I am just beginning with OOP. I was wondering if someone could give me a general idea of what it ...

Get the current date in java.sql.Date format

I need to add the current date into a prepared statement of a JDBC call. I need to add the date in a format like yyyy/MM/dd. I've try with DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd"); Date date = new Date(); pstm.setDate(6, (java.sql...

How do I create dynamic variable names inside a loop?

I'm working on an ajax google maps script and I need to create dynamic variable names in a for loop. for (var i = 0; i < coords.length; ++i) { var marker+i = "some stuff"; } What I want to get is: marker0, marker1, marker2 and so on. and I ...

Vertical align text in block element

I know vertical alignment is always asked about, but I don't seem to be able to find a solution for this particular example. I'd like the text centered within the element, not the element centered itself: HTML: <ul> <li><a href="...

How to compile python script to binary executable

I need to convert a Python script to a Windows executable. I have Python 2.6 installed to python26. I have created one script and kept it in C:\pythonscript. Inside this folder there are two files Setup.py and oldlogs.py (this file need coversion)...

Hash Table/Associative Array in VBA

I can't seem to find the documentation explaining how to create a hash table or associative array in VBA. Is it even possible? Can you link to an article or better yet post the code?...

How can I get the current date and time in the terminal and set a custom command in the terminal for it?

I have to check the time in a Linux terminal. What is the command for getting date and time in a Linux terminal? Is there a way in which we can set a custom function?...

Press any key to continue

According to Microsoft's documentation, read-host lets the user type some input, and then press enter to continue. Not exactly the correct behavior if you want to have "Press any key to continue". (Wait... where's the Any key?!) Is there a way to ac...

How to get a view table query (code) in SQL Server 2008 Management Studio

I have a view in SQL Server 2008 and would like to view it in Management Studio. Example: --is the underlying query for the view Example_1 select * from table_aView View name: Example_1 How to get the query of the corresponding view table (que...

python paramiko ssh

i'm new on python. i wrote a script to connect to a host and execute one command ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.connect(host, username=user, password=pw) print 'running remote command' stdi...

How can I increase the size of a bootstrap button?

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

Android Studio Gradle DSL method not found: 'android()' -- Error(17,0)

I am attempting to run my project in Android Studio but the error appears below: I have followed many sources just to get this to run and have wound up here, but do not know what else to do. How can I configure this project to run? build.gradle...

Replacement for "rename" in dplyr

I like plyr's renaming function rename. I have recently started using dplyr, and was wondering if there is an easy way to rename variables using a function from dplyr, that is as easy to use as to plyr's rename?...

What does the CSS rule "clear: both" do?

What does the following CSS rule do: .clear { clear: both; } And why do we need to use it?...

Node.js https pem error: routines:PEM_read_bio:no start line

I am messing with login form right now with node.js, I tried creating a pem key and csr using openssl req -newkey rsa:2048 -new -nodes -keyout key.pem -out csr.pem However I been getting errors for running node server.js Here is my server.js va...

Limit to 2 decimal places with a simple pipe

I have found an example which limits a number to 2 decimal places AND turns the figure into a currency amount- eg £2.55. {{ number | currency : 'GBP' : true : '1.2-2'}} Is there a simple pipe which does the same without applying a currency?...

show dbs gives "Not Authorized to execute command" error

I've spent some time trying to figure out what is wrong but as I could not find out, I decided to ask here. I am running MongoDB(Windows 64-bit 2008 R2+) version 3.2.3 on Windows 8, the paths are : C:\MongoDB\bin for the installation C:\data\db fo...

git pull remote branch cannot find remote ref

I'm not sure why this doesn't work. When I do git branch -a, this is what I see: I'm trying to pull from the DownloadManager on the online GitHub repository. I have tried git pull, but then it complains about not knowing which branch to pull f...

Reading from text file until EOF repeats last line

The following C++ code uses a ifstream object to read integers from a text file (which has one number per line) until it hits EOF. Why does it read the integer on the last line twice? How to fix this? Code: #include <iostream> #include <fs...

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

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

CSS selector last row from main table

I have a table inside a table, and I want to fill the background of the last row of table 1 only — not table 2. <style> #test tr:last-child { background:#ff0000; } </style> <table border="1" width="100%" id="test"> <tr>...

set dropdown value by text using jquery

I have a dropdown as: <select id="HowYouKnow" > <option value="1">FRIEND</option> <option value="2">GOOGLE</option> <option value="3">AGENT</option></select> In the above dropdown i know the te...

strange error in my Animation Drawable

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

How to set environment variables in PyCharm?

I have started to work on a Django project, and I would like to set some environment variables without setting them manually or having a bash file to source. I want to set the following variables: export DATABASE_URL=postgres://127.0.0.1:5432/my_db_n...

Http Get using Android HttpURLConnection

I'm new to Java and Android development and try to create a simple app which should contact a web server and add some data to a database using a http get. When I do the call using the web browser in my computer it works just fine. However, when I do...

How to delete columns in a CSV file?

I have been able to create a csv with python using the input from several users on this site and I wish to express my gratitude for your posts. I am now stumped and will post my first question. My input.csv looks like this: day,month,year,lat,long...

Install IPA with iTunes 11

I have an IPA signed for ad-hoc distribution. I can install it fine with Xcode Organizer by dragging it to the device. It also worked with iTunes <=10 by dragging onto the device name. I'd like to install it via iTunes 11 though. Dragging it onto ...

CSS background image to fit height, width should auto-scale in proportion

I want background image fit with the height of the div, there's a way to do that? background-size:cover; fit only with the width and height autoscale (I need the opposite effect). Thanks....

How to connect html pages to mysql database?

I want to know how to connect html pages to mysql database? What are the codes? I also want to know how to add new data to MySQL database when I'm using HTML page and also how to publish the data?...

ngOnInit not being called when Injectable class is Instantiated

Why isn't ngOnInit() called when an Injectable class is resolved? Code import {Injectable, OnInit} from 'angular2/core'; import { RestApiService, RestRequest } from './rest-api.service'; @Injectable() export class MovieDbService implements OnInit ...

@ViewChild in *ngIf

Question What is the most elegant way to get @ViewChild after corresponding element in template was shown? Below is an example. Also Plunker available. Component.template.html: <div id="layout" *ngIf="display"> <div #co...

What is PostgreSQL equivalent of SYSDATE from Oracle?

I want to perform a query using sysdate like: select up_time from exam where up_time like sysdate which is possible in Oracle. However, it seems that PostgreSQL doesn't support sysdate. I couldn't find sysdate in postgres documentation. What is t...

How set background drawable programmatically in Android

To set Background: RelativeLayout layout =(RelativeLayout)findViewById(R.id.background); layout.setBackgroundResource(R.drawable.ready); Is the best way to do it?...

Enter key in textarea

I have a textarea, On every Enter key pressed in textarea I want new line to be started with a bullet say (*). How to go about it ? No jQuery please. I can observe for the Enter key , after that !? Should I have to get the whole value of textarea ...

python capitalize first letter only

I am aware .capitalize() capitalizes the first letter of a string but what if the first character is a integer? this 1bob 5sandy to this 1Bob 5Sandy ...

Replacing Spaces with Underscores

I have a PHP Script that users will enter a name like: Alex_Newton, However, some users will use a space rather than an underscore, so my question is: How do I auto-replace spaces with Underscores in PHP?...

@property retain, assign, copy, nonatomic in Objective-C

As someone that's new to Objective-C can someone give me an overview of the retain, assign, copy and any others I'm missing, that follow the @property directive? What are they doing and why would I want to use one over another?...

Format numbers in django templates

I'm trying to format numbers. Examples: 1 => 1 12 => 12 123 => 123 1234 => 1,234 12345 => 12,345 It strikes as a fairly common thing to do but I can't figure out which filter I'm supposed to use. Edit: If you've a generic...

DataTables: Cannot read property 'length' of undefined

I understand this a popular issue, and I have read all the similar questions here on Stack Overflow and other sites (including the datatables website). To clarify, I am using PHP Codeigniter Materliazecss I have also made sure that I received th...

What is the purpose of a question mark after a type (for example: int? myVariable)?

Typically the main use of the question mark is for the conditional, x ? "yes" : "no". But I have seen another use for it but can't find an explanation of this use of the ? operator, for example. public int? myProperty { get; set; } ...

How to stop creating .DS_Store on Mac?

I'm developing sites on mac and every time I create some folder (or file in that folder) .DS_Store is created in that folder. How to prevent creating .DS_Store file ?...

Efficient way to Handle ResultSet in Java

I'm using a ResultSet in Java, and am not sure how to properly close it. I'm considering using the ResultSet to construct a HashMap and then closing the ResultSet after that. Is this HashMap technique efficient, or are there more efficient ways of ha...

Date validation with ASP.NET validator

I'm trying to use an ASP.NET RangeValidator to validate a date on a textbox. The format of the date entered on the textbox is dd MMMM yyyy. How can I use the range validator to validate a valid date? If I enter 1 January 1000 as the min or max value...

How to reset Jenkins security settings from the command line?

Is there a way to reset all (or just disable the security settings) from the command line without a user/password as I have managed to completely lock myself out of Jenkins?...

My Application Could not open ServletContext resource

i have Eclipse Maven web project where i use Spring mvc and Spring security. When i truy to launch it, it doesn't suceed to intialize the context: Could not open ServletContext resource [/WEB-INF/spring-dispatcher-servlet.xml] More details below: ...

How to prevent form from being submitted?

I have a form that has a submit button in it somewhere. However, I would like to somehow 'catch' the submit event and prevent it from occurring. Is there some way I can do this? I can't modify the submit button, because it's part of a custom contr...

How to reset the state of a Redux store?

I am using Redux for state management. How do I reset the store to its initial state? For example, let’s say I have two user accounts (u1 and u2). Imagine the following sequence of events: User u1 logs into the app and does something, so we cach...

Detect Click into Iframe using JavaScript

I understand that it is not possible to tell what the user is doing inside an iframe if it is cross domain. What I would like to do is track if the user clicked at all in the iframe. I imagine a scenario where there is an invisible div on top of th...

Waiting for another flutter command to release the startup lock

When I run my flutter application it show Waiting for another flutter command to release the startup lock this messages and not proceed further....

NameError: global name 'unicode' is not defined - in Python 3

I am trying to use a Python package called bidi. In a module in this package (algorithm.py) there are some lines that give me error, although it is part of the package. Here are the lines: # utf-8 ? we need unicode if isinstance(unicode_or_str, uni...

Difference between Width:100% and width:100vw?

I have to fit an iframe in screen height. Obviously, I wanted 100% as in width but, since that doesn't work, I used 100vh. But vh like vw is not exactly 100%. In my laptop through chrome while the 100% width renders perfectly without the need for a ...

Convert string to variable name in python

I have any string. like 'buffalo', x='buffalo' I want to convert this string to some variable name like, buffalo=4 not only this example, I want to convert any input string to some variable name. How should I do that (in python)?...

What goes into your .gitignore if you're using CocoaPods?

I've been doing iOS development for a couple of months now and just learned of the promising CocoaPods library for dependency management. I tried it out on a personal project: added a dependency to Kiwi to my Podfile, ran pod install CocoaPodsTest.x...

What is Python used for?

What is Python used for and what is it designed for?...

How to save a bitmap on internal storage

this is my code I and I want to save this bitmap on my internal storage. The public boolean saveImageToInternalStorage is a code from google but I don't know how to use it. when I touch button2 follow the button1 action. public class MainActivity ex...

Fixed size div?

I want a normal div for the body of my text and a bunch of little divs that are exactly 150px by 150px. How might i do this?...

How to set .net Framework 4.5 version in IIS 7 application pool

I installed the Visual Studio 11 Beta and suddenly all the async action methods I had created under the VS 11 Developer preview started hanging (apparently this issue: http://blogs.msdn.com/b/pfxteam/archive/2012/03/03/10277166.aspx). My app is usin...

How to load my app from Eclipse to my Android phone instead of AVD

I'm quite new to Android and have been using an AVD to debug my app so far. However, I want to start checking the media options and therfore need to start using my Android phone. How do I get Eclipse to load my app to my phone instead of my AVD?...

Htaccess: add/remove trailing slash from URL

My website runs a script called -> WSS wallpaper script My Problem -> I have been trying to force remove or add trailing slash to the end of my URL to prevent duplicated content and also to clean up my URLs. I have tried all sorts and tried everyth...

How to install latest version of git on CentOS 7.x/6.x

I used the usual: yum install git It did not install the latest version of git on my CentOS 6. How can I update to the latest version of git for CentOS 6? The solution can be applicable to newer versions of CentOS such as CentOS 7....

What is the { get; set; } syntax in C#?

I am learning ASP.NET MVC and I can read English documents, but I don't really understand what is happening in this code: public class Genre { public string Name { get; set; } } What does this mean: { get; set; }?...

How to run shell script file using nodejs?

I need to run a shell script file using nodeJS that executes a set of Cassandra DB commands. Can anybody please help me on this. inside db.sh file: create keyspace dummy with replication = {'class':'SimpleStrategy','replication_factor':3} creat...

What is the maximum number of edges in a directed graph with n nodes?

What is the maximum number of edges in a directed graph with n nodes? Is there any upper bound?...

Hidden Features of Xcode

With a huge influx of newbies to Xcode, I'm sure there are lots of Xcode tips and tricks to be shared. What are yours? ...

MySQL, Concatenate two columns

There are two columns in a MySQL table: SUBJECT and YEAR. I want to generate an alphanumeric unique number which holds the concatenated data from SUBJECT and YEAR. How can I do this? Is it possible to use a simple operator like +?...

Where is Xcode's build folder?

Before Xcode 4 the build used to be created in the root folder of my project. I can no longer find it. Where can i find the build folder?...

How to put an image next to each other

I'm trying to put these two 'hyperlinked' icons next to each other but I can't seem to do that. As you can see, the twitter icon falls to the next line.. (they are both hyperlinked to their respective website) HTML <div class="nav3" style="hei...

Multiple GitHub Accounts & SSH Config

I'm having some trouble getting two different SSH keys/GitHub accounts to play well together. I have the following setup: Repos accessible from one account using [email protected]:accountname Repos accessible from another account using [email protected]...

How to fix "The ConnectionString property has not been initialized"

When I start my application I get: The ConnectionString property has not been initialized. Web.config: <connectionStrings> <add name="MyDB" connectionString="Data Source=localhost\sqlexpress;Initial Catalog=mydatabase;User I...

How do I fetch multiple columns for use in a cursor loop?

When I try to run the following SQL snippet inside a cursor loop, set @cmd = N'exec sp_rename ' + @test + N',' + RIGHT(@test,LEN(@test)-3) + '_Pct' + N',''COLUMN''' I get the following message, Msg 15248, Level 11, State 1, Procedu...

Call to undefined method mysqli_stmt::get_result

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

How to remove pip package after deleting it manually

I deleted a pip package with rm -rf command thinking that the package will be removed. Now the package has been deleted but it still shows up in pip list and I'm unable to remove it with pip uninstall nor can I update with pip install --upgrade. I'...

PostgreSQL - query from bash script as database user 'postgres'

I have a table in my PostgreSQL database which has 3 columns - c_uid, c_defaults and c_settings. c_uid simply stores the name of a user and c_defaults is a long piece of text which contains a lot of data w.r.t that user. I have to execute a statemen...

Integer.valueOf() vs. Integer.parseInt()

Aside from Integer.parseInt() handling the minus sign (as documented), are there any other differences between Integer.valueOf() and Integer.parseInt()? And since neither can parse , as a decimal thousands separator (produces NumberFormatException),...

How to create a HTTP server in Android?

I would like to create a simple HTTP server in Android for serving some content to a client. Any advice on how to build the server or use any existing library? ...

Retrieving values from nested JSON Object

I've got JSON file, which I want to parse. The JSON file ("myfile") has format as follows: { "LanguageLevels": { "1": "Poczatkujacy", "2": "SrednioZaawansowany", "3": "Zaawansowany", "4": "Ekspert" } } I wan...

How to get the first word of a sentence in PHP?

I want to extract the first word of a variable from a string. For example, take this input: <?php $myvalue = 'Test me more'; ?> The resultant output should be Test, which is the first word of the input. How can I do this?...

How to open generated pdf using jspdf in new window

I am using jspdf to generate a pdf file. Every thing is working fine. But how to open generated pdf in new tab or new window. I am using doc.output('datauri'); Which is opening the pdf in same tab....

Extract names of objects from list

I have a list of objects. How do I grab the name of just one object from the list? As in: LIST <- list(A=1:5, B=1:10) LIST$A some.way.cool.function(LIST$A) #function I hope exists "A" #yay! it has returned what I want names(LIST) is not cor...

How do I get a class instance of generic type T?

I have a generics class, Foo<T>. In a method of Foo, I want to get the class instance of type T, but I just can't call T.class. What is the preferred way to get around it using T.class?...

Eclipse - Unable to install breakpoint due to missing line number attributes

I am getting this strange error in Eclipse while trying to set a breakpoint. Unable to insert breakpoint Absent Line Number Information I ticked the checkbox from Compiler options but no luck....

Making WPF applications look Metro-styled, even in Windows 7? (Window Chrome / Theming / Theme)

I like the window chrome on the new Office Suite and Visual Studio: I'm still developing applications for Windows 7 of course, but I'm wondering if there's a quick and easy way (read: WPF style or Windows Library) to emulate this style. I've done...

How can I roll back my last delete command in MySQL?

I accidentally deleted some huge number of rows from a table... How can I roll it back? I executed the query using PuTTY. I'll be grateful if any of you can guide me safely out of this......

Something like 'contains any' for Java set?

I have two sets, A and B, of the same type. I have to find if A contains any element from the set B. What would be the best way to do that without iterating over the sets? The Set library has contains(object) and containsAll(collection), but not co...

What is the purpose of the vshost.exe file?

When I create and compile a "Hello, World!" application in C#, I get three files in the Debug folder apart from the main exe (e.g. HelloWorld.exe) HelloWorld.vshost.exe HelloWorld.pdb HelloWorld.vshost.exe.manifest What purpose do these files ser...

How can I get client information such as OS and browser

I'm using JSP, Servlet to develop my web application. I want to get client information such as: operation system, browser, resolution, ... whenever a client is using my website....

Proper Linq where clauses

I write a fair amount of linq in my day to day life, but mostly simple statements. I have noticed that when using where clauses, there are many ways to write them and each have the same results as far as I can tell. For example; from x in Collecti...

No 'Access-Control-Allow-Origin' header is present on the requested resource—when trying to get data from a REST API

I'm trying to fetch some data from the REST API of HP Alm. It works pretty well with a small curl script - I get my data. Now doing that with JavaScript, fetch and ES6 (more or less) seems to be a bigger issue. I keep getting this error message: ...

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: translate(-20px,0px); } ...

When to use static methods

I am wondering when to use static methods? Say if I have a class with a few getters and setters, a method or two, and I want those methods only to be invokable on an instance object of the class. Does this mean I should use a static method? Example: ...

How do I change column default value in PostgreSQL?

How do I change column default value in PostgreSQL? I've tried: ALTER TABLE ONLY users ALTER COLUMN lang DEFAULT 'en_GB'; But it gave me an error: ERROR: syntax error at or near "DEFAULT" ...

delete map[key] in go?

I have a map: var sessions = map[string] chan int{} How do I delete sessions[key]? I tried: sessions[key] = nil,false; That didn't work. Update (November 2011): The special syntax for deleting map entries is removed in Go version 1: ...

How to use WHERE IN with Doctrine 2

I have the following code which gives me the error: Message: Invalid parameter number: number of bound variables does not match number of tokens Code: public function getCount($ids, $outcome) { if (!is_array($ids)) { $ids = array($id...

How to reshape data from long to wide format

I'm having trouble rearranging the following data frame: set.seed(45) dat1 <- data.frame( name = rep(c("firstName", "secondName"), each=4), numbers = rep(1:4, 2), value = rnorm(8) ) dat1 name numbers value 1 firstNa...

How to do exponential and logarithmic curve fitting in Python? I found only polynomial fitting

I have a set of data and I want to compare which line describes it best (polynomials of different orders, exponential or logarithmic). I use Python and Numpy and for polynomial fitting there is a function polyfit(). But I found no such functions for...

Regex to validate password strength

My password strength criteria is as below : 8 characters length 2 letters in Upper Case 1 Special Character (!@#$&*) 2 numerals (0-9) 3 letters in Lower Case Can somebody please give me regex for same. All conditions must be met by password ...

Printing out all the objects in array list

I need to be able to print out the Student objects(all variables) in my array list. Is this possible? When i try to print it outputs this sort of thing e.g student.Student@82701e. I think it's hexadecimal or something This is my code: package stude...

Converting Epoch time into the datetime

I am getting a response from the rest is an Epoch time format like start_time = 1234566 end_time = 1234578 I want to convert that epoch seconds in MySQL format time so that I could store the differences in my MySQL database. I tried: >>>...

What's the difference between primitive and reference types?

This is a past exam question and I was wondering what a primitive type and reference type are first off? With an array I know the a reference type is where the array is composed of objects or variables, but a primitive type is where you would create ...

Overlay normal curve to histogram in R

I have managed to find online how to overlay a normal curve to a histogram in R, but I would like to retain the normal "frequency" y-axis of a histogram. See two code segments below, and notice how in the second, the y-axis is replaced with "density"...

How can I bold the fonts of a specific row or cell in an Excel worksheet with C#?

I am exporting data from a List<> to excel. I want to make some specific rows and cells bold. I need to make some cell merged also. Below is the code I am using. try { Excel.Application application; Excel.Workbo...

Android ListView not refreshing after notifyDataSetChanged

My ListFragment code public class ItemFragment extends ListFragment { private DatabaseHandler dbHelper; private static final String TITLE = "Items"; private static final String LOG_TAG = "debugger"; private ItemAdapter adapter; ...

Using a custom typeface in Android

I want to use a custom font for my android application which I am creating. I can individually change the typeface of each object from Code, but I have hundreds of them. So, Is there a way to do this from the XML? [Setting a custom typeface] Is th...

Very simple C# CSV reader

I'd like to create an array from a CSV file. This is about as simple as you can imagine, the CSV file will only ever have one line and these values: Device, SignalStrength, Location, Time, Age. I'd like to put these values into one dimensional ar...

logout and redirecting session in php

the below one is the link in my php site.. after clicking this button the user's session should be terminated and he should be redirected again to the home page.. i have written the coding for this concept as follows but it shows me only a blank page...

HTML5 Email Validation

It is said "With HTML5, we need no more js or a server side code to check if the user's input is a valid email or url address" How can I validate email after a user enter? and without JS how to display a message if the user enter a wrong form of his...

How to use conditional statement within child attribute of a Flutter Widget (Center Widget)

So far whenever I needed to use a conditional statement within a Widget I have done the following (Using Center and Containers as simplified dummy examples): new Center( child: condition == true ? new Container() : new Container() ) Though when...

Must declare the scalar variable

I wrote this SQL in a stored procedure but not working, declare @tableName varchar(max) = 'TblTest' declare @col1Name varchar(max) = 'VALUE1' declare @col2Name varchar(max) = 'VALUE2' declare @value1 varchar(max) declare @value2 varchar(200) execut...

subtract time from date - moment js

I have for instance this datetime: 01:20:00 06-26-2014 and I want to subtract a time like this: 00:03:15 after that I'd like to format the result like this: 3 hours and 15 minutes earlier. How can I do that using moment.js ? edit: I tried: ...

How to show validation message below each textbox using jquery?

I am trying to make a login form in which I have email address and password as the textbox. I have done the validation on the email address part so that it should have proper email address and also on the empty check both for email address and passwo...

Email address validation in C# MVC 4 application: with or without using Regex

I have an MVC 4 web application and I need to enter and validate some email addresses, without sending an email to the user's email address. Currently I am using basic regex email validation with this pattern: [RegularExpression(@"\A(?:[a-z0-9!#$%&...

Easy way to get a test file into JUnit

Can somebody suggest an easy way to get a reference to a file as a String/InputStream/File/etc type object in a junit test class? Obviously I could paste the file (xml in this case) in as a giant String or read it in as a file but is there a shortcu...

Reading a single char in Java

How can a char be entered in Java from keyboard?...

How do I setup the InternetExplorerDriver so it works

I am using WebDriver and I have downloaded the InternetExplorerDriver and was wondering what I do with it after it is downloaded? This says to put the driver in my path. Not really certain what exactly they are talking about there. Has anyone used...

Reading images in python

I am trying to read a png image in python. The imread function in scipy is being deprecated and they recommend using imageio library. However, I am would rather restrict my usage of external libraries to scipy, numpy and matplotlib libraries. Thus,...

mysqldump Error 1045 Access denied despite correct passwords etc

This is a tricky one, I have the following output: mysqldump: Got error: 1045: Access denied for user 'root'@'localhost' (using password: YES) when trying to connect When attempting to export my database with mysqldump on Windows XP. The userna...

What is the difference between atomic / volatile / synchronized?

How do atomic / volatile / synchronized work internally? What is the difference between the following code blocks? Code 1 private int counter; public int getNextUniqueIndex() { return counter++; } Code 2 private AtomicInteger counter; pu...

How to annotate MYSQL autoincrement field with JPA annotations

Straight to the point, problem is saving the object Operator into MySQL DB. Prior to save, I try to select from this table and it works, so is connection to db. Here is my Operator object: @Entity public class Operator{ @Id @GeneratedValue ...

Read SQL Table into C# DataTable

I've read a lot of posts about inserting a DataTable into a SQL table, but is there an easy way to pull a SQL table into a .NET DataTable?...

How to bind inverse boolean properties in WPF?

What I have is an object that has an IsReadOnly property. If this property is true, I would like to set the IsEnabled property on a Button, ( for example ), to false. I would like to believe that I can do it as easily as IsEnabled="{Binding Path=!Is...

How to unpackage and repackage a WAR file

I have a WAR file. I would like to open it, edit an XML file, remove some jars and then re-package it. I used WINRAR to open the WAR file and I removed some Jars and did an 'Add to Archive' in WinRar and created a WAR. When I deployed the WAR in jb...

Docker remove <none> TAG images

root@server:~# docker images -a REPOSITORY TAG IMAGE ID CREATED VIRTUAL SIZE <none> <none> 5e2dfc857e73 5 days ago 261.6 MB <none...

Add my custom http header to Spring RestTemplate request / extend RestTemplate

My current code: RestTemplate restTemplate = new RestTemplate(); restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter()); Mall[] malls = restTemplate.getForObject(url, Mall[].class); I need to add some custom headers for...

How can I get the IP address from NIC in Python?

When an error occurs in a Python script on Unix , an email is sent. I have been asked to add {Testing Environment} to the subject line of the email if the IP address is 192.168.100.37 which is the testing server. This way we can have one version of ...

check if variable is dataframe

when my function f is called with a variable I want to check if var is a pandas dataframe: def f(var): if var == pd.DataFrame(): print "do stuff" I guess the solution might be quite simple but even with def f(var): if var.values ...

Angular @ViewChild() error: Expected 2 arguments, but got 1

When trying ViewChild I am getting the error. Error is "An argument for 'opts' was not provided." Both @ViewChild is giving the error. import { Component, OnInit, ElementRef, ViewChild, Output, EventEmitter } from '@angular/core'; import { Ingredie...

Making macOS Installer Packages which are Developer ID ready

Note: This is for OS X Installer packages only, packages for submission to the Mac App Store follow different rules. Because of Mountain Lion's Gatekeeper I finally had to take my PackageMaker build script behind the barn and shoot it. PackageMaker ...

How to fix the error "Windows SDK version 8.1" was not found?

I recently updated visual studio 2015 and now, when i try to build any project it always fails and i get the error Severity Code Description Project File Line Suppression State Error MSB8036 The Windows SDK version 8.1 was not f...

GIT fatal: ambiguous argument 'HEAD': unknown revision or path not in the working tree

I'm trying to initialize a new GIT repo from Debian (actually a VM on Virtualbox, installed and running on Mac OS X) : [david@server-VM-001:~ $] mkdir test [david@server-VM-001:~ $] cd test [david@server-VM-001:test $] git init Initialized empty Git...

Jquery $.ajax fails in IE on cross domain calls

I am doing a cross domain request using $.ajax. It works on Firefox and Chrome, but does not issue a call on IE 7 or 8. Can anyone tell me what's wrong with the following? I have used JSON and JSONP (which I stopped using, due to some custom restric...

How to find sum of several integers input by user using do/while, While statement or For statement

Please help out here. I want to create a program whereby a user inputs several numbers (let's say 6 numbers from his/ her head). The program should then go ahead and calculate the sum of all these numbers. I however have to use a loop statement, eith...

How to include CSS file in Symfony 2 and Twig?

I'm playing around with Symfony2, and I have problems including CSS and JS files in Twig template. I have a bundle named Webs/HomeBundle inside which I have HomeController with indexAction that renders a twig template file: public function indexActio...

make arrayList.toArray() return more specific types

So, normally ArrayList.toArray() would return a type of Object[]....but supposed it's an Arraylist of object Custom, how do I make toArray() to return a type of Custom[] rather than Object[]?...

Best way to represent a Grid or Table in AngularJS with Bootstrap 3?

I am creating an App with AngularJS and Bootstrap 3. I want to show a table/grid with thousands of rows. What is the best available control for AngularJS & Bootstrap with features like Sorting, Searching, Pagination etc....

Checking if a variable is not nil and not zero in ruby

I am using the following code to check if a variable is not nil and not zero if(discount != nil && discount != 0) ... end Is there a better way to do this?...

HTML code for INR

For pound (£) there is HTML code &pound;. For INR can you please tell me the HTML code?...

Git push error: "origin does not appear to be a git repository"

I am following the instructions given here to create a Git repository. All went well until the last line: $ git push -u origin master fatal: 'origin' does not appear to be a git repository fatal: The remote end hung up unexpectedly I'm ...

GridView sorting: SortDirection always Ascending

I have a gridview and I need to sort its elements when the user clicks on the header. Its datasource is a List object. The aspx is defined this way : <asp:GridView ID="grdHeader" AllowSorting="true" AllowPaging="false" AutoGenerateColumns="...

How to access /storage/emulated/0/

I have written a code to record audio and save it to below file location. private String getFilename() { String filepath = Environment.getExternalStorageDirectory().getPath(); File file = new File(filepath, AUDIO_RECORDER_FOLDER); if (!f...

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

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

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

In android how to set navigation drawer header image and name programmatically in class file?

In android studio 1.4.1, I have created new Navigation Drawer Project which is default.My issue is in this project there is nav_header_main.xml file which is for navigation header image and name. I want this image and name should be set programmatica...

Reset select2 value and show placeholder

How do I set the placeholder on value reset by select2. In my example If locations or grade select boxes are clicked and my select2 has a value than the value of select2 should reset and show the default placeholder. This script is resetting the valu...

Laravel 5 Eloquent where and or in Clauses

i try to get results from table with multiple where and/or clauses. My SQL statement is: SELECT * FROM tbl WHERE m__Id = 46 AND t_Id = 2 AND (Cab = 2 OR Cab = 4) How i can get this with Laravel Eloquent? My Code in Laravel is: $BType = CabRes::...

Easy login script without database

How do I create an easy login script that does not require a database. I would like it to be safe. Alright, what about this script, i just made it by my knowledge in php. <?php // Start session session_start(); // Username and password $ID = ...

event.preventDefault() function not working in IE

Following is my JavaScript (mootools) code: $('orderNowForm').addEvent('submit', function (event) { event.preventDefault(); allFilled = false; $$(".required").each(function (inp) { if (inp.getValue() != '') { allFille...

Efficient way to determine number of digits in an integer

What is a very efficient way of determining how many digits there are in an integer in C++?...

Array and string offset access syntax with curly braces is deprecated

I've just updated my php version to 7.4, and i noticed this error pops up: Array and string offset access syntax with curly braces is deprecated here is part of my code which is triggering the above error: public function getRecordID(string $zoneID...

jQuery plugin returning "Cannot read property of undefined"

I'm trying to do something i've done numerous times. I can't figure out why this isn't working. No matter how i write the jQuery code, it doesn't work. menuitems[i].action() just does NOT work. Below is Example 1 in which this example, no matter what...

Datagridview: How to set a cell in editing mode?

I need to programmatically set a cell in editing mode. I know that setting that cell as CurrentCell and then call the method BeginEdit(bool), it should happen, but in my case, it doesn't. I really want that, with my DGV with several columns, the use...

How can I remove the gloss on a select element in Safari on Mac?

On Macs and iOS devices, in Safari, a <select> element with a background color generates a gloss over itself. This does not seem to happen in other operating systems. For example, I have a select element with these style properties: select {...

Mocking python function based on input arguments

We have been using Mock for python for a while. Now, we have a situation in which we want to mock a function def foo(self, my_param): #do something here, assign something to my_result return my_result Normally, the way to mock this would...

Difference between static memory allocation and dynamic memory allocation

I would like to know what is the difference between static memory allocation and dynamic memory allocation? Could you explain this with any example?...

PHP & MySQL: mysqli_num_rows() expects parameter 1 to be mysqli_result, boolean given

I'm trying to Integrate HTML Purifier http://htmlpurifier.org/ to filter my user submitted data but I get the following error below. And I was wondering how can I fix this problem? I get the following error. on line 22: mysqli_num_rows() expects pa...

What exactly is the difference between Web API and REST API in MVC?

I have a little understanding on REST API. As per my knowledge it is used to work with HTTP services(GET POST PUT DELETE). When i add a webapi controller it provides me some basic methods like : public class Default1Controller : ApiController ...

get name of a variable or parameter

I would like to get the name of a variable or parameter: For example if I have: var myInput = "input"; var nameOfVar = GETNAME(myInput); // ==> nameOfVar should be = myInput void testName([Type?] myInput) { var nameOfParam = GETNAME(myInpu...

Truncate a string straight JavaScript

I'd like to truncate a dynamically loaded string using straight JavaScript. It's a url, so there are no spaces, and I obviously don't care about word boundaries, just characters. Here's what I got: var pathname = document.referrer; //wont work i...

What difference does .AsNoTracking() make?

I have a question regarding the .AsNoTracking() extension, as this is all quite new and quite confusing. I'm using a per-request context for a website. A lot of my entities don't change so don't need to be tracked, but I have the following scenario...

How to scroll to top of a div using jQuery?

I have a gridview inside a div.. I want to scroll to top of the div from the bottom of the div using jquery.. Any suggestion.. <div id="GridDiv"> // gridview inside.. </div> My gridview will have custom pagination generated link button...

DD/MM/YYYY Date format in Moment.js

How can i change the current date to this format(DD/MM/YYYY) using moment.js? I have tried below code. $scope.SearchDate = moment(new Date(), "DD/MM/YYYY"); But it's return 0037-11-24T18:30:00.000Z. Did't help to format current date. ...

Invalid CSRF Token 'null' was found on the request parameter '_csrf' or header 'X-CSRF-TOKEN'

After configuring Spring Security 3.2, _csrf.token is not bound to a request or a session object. This is the spring security config: <http pattern="/login.jsp" security="none"/> <http> <intercept-url pattern="/**" access="ROLE_...

jQuery Datepicker localization

I need a french calendar and I can't understand the problem. I guess I'm not using the regional options like it should be. But... Here is my code : $(function() { $('#Date').datepicker({ showMonthAfterYear: false, showOn: 'both', ...

How to force maven update?

I imported my already working project on another computer and it started to download dependencies. Apparently my internet connection crashed and now I get the following: >Build errors for comics; org.apache.maven.lifecycle.LifecycleExecuti...

How do I get the path to the current script with Node.js?

How would I get the path to the script in Node.js? I know there's process.cwd, but that only refers to the directory where the script was called, not of the script itself. For instance, say I'm in /home/kyle/ and I run the following command: node /...

JPA - Returning an auto generated id after persist()

I'm using JPA (EclipseLink) and Spring. Say I have a simple entity with an auto-generated ID: @Entity public class ABC implements Serializable { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) private int id; // ... } In...

Excel - extracting data based on another list

I have an Excel worksheet with two columns (name/ID) and then another list that is a subset of the names only from the larger aforementioned list. I want to go through the subset list and then pull the data from the larger list (name/ID) and put it s...

Is there an SQLite equivalent to MySQL's DESCRIBE [table]?

I'm just getting started learning SQLite. It would be nice to be able to see the details for a table, like MySQL's DESCRIBE [table]. PRAGMA table_info [table] isn't good enough, as it only has basic information (for example, it doesn't show if a colu...

How to obtain the last path segment of a URI

I have as input a string that is a URI. how is it possible to get the last path segment (that in my case is an id)? This is my input URL: String uri = "http://base_path/some_segment/id" and I have to obtain the id I have tried with this: S...

replace all occurrences in a string

Possible Duplicate: Fastest method to replace all instances of a character in a string How can you replace all occurrences found in a string? If you want to replace all the newline characters (\n) in a string.. This will only replace the...

The simplest way to comma-delimit a list?

What is the clearest way to comma-delimit a list in Java? I know several ways of doing it, but I'm wondering what the best way is (where "best" means clearest and/or shortest, not the most efficient. I have a list and I want to loop over it, printi...

Splitting a table cell into two columns in HTML

I have the following table: <table border="1"> <tr> <th scope="col">Header</th> <th scope="col">Header</th> <th scope="col">Header</th> </tr> <tr> <th scope="row"&g...

How to read text file in JavaScript

I am trying to load a text file into my JavaScript file and then read the lines from that file in order to get information, and I tried the FileReader but it does not seem to be working. Can anyone help? function analyze(){ var f = new FileReader...

How to atomically delete keys matching a pattern using Redis

In my Redis DB I have a number of prefix:<numeric_id> hashes. Sometimes I want to purge them all atomically. How do I do this without using some distributed locking mechanism?...

CSS vertical alignment of inline/inline-block elements

I'm trying to get several inline and inline-block components aligned vertically in a div. How come the span in this example insists on being pushed down? I've tried both vertical-align:middle; and vertical-align:top;, but nothing changes. HTML: &...

window.onload vs $(document).ready()

What are the differences between JavaScript's window.onload and jQuery's $(document).ready() method?...

Break out of a While...Wend loop

I am using a While...Wend loop of VBA. Dim count as Integer While True count=count+1 If count = 10 Then ''What should be the statement to break the While...Wend loop? ''Break or Exit While not working EndIf Wend I do...

How to retrieve all keys (or values) from a std::map and put them into a vector?

This is one of the possible ways I come out: struct RetrieveKey { template <typename T> typename T::first_type operator()(T keyValuePair) const { return keyValuePair.first; } }; map<int, int> m; vector<int>...

Difference between Spring MVC and Spring Boot

I have just started learning Spring. In my next step, I would like to develop bigger web applications. Now I am wondering if I should start with Spring Boot or Spring MVC. I have already read some stuff, but it is confusing because both look simila...

Normal arguments vs. keyword arguments

How are "keyword arguments" different from regular arguments? Can't all arguments be passed as name=value instead of using positional syntax?...

Sending email with attachments from C#, attachments arrive as Part 1.2 in Thunderbird

I have a C# application which emails out Excel spreadsheet reports via an Exchange 2007 server using SMTP. These arrive fine for Outlook users, but for Thunderbird and Blackberry users the attachments have been renamed as "Part 1.2". I found this ar...

BigDecimal equals() versus compareTo()

Consider the simple test class: import java.math.BigDecimal; /** * @author The Elite Gentleman * */ public class Main { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub ...

How to change xampp localhost to another folder ( outside xampp folder)?

How can I change my default xampp localhost c:xampp/htdoc to another folder i.e. c:/alan? When I use the IP address I should be able to view my website file in C:/alan. Thanks for helping me....

What is the difference between JavaScript and jQuery?

What is the main difference between JavaScript and jQuery. I know the minor difference like jQuery is high performance more reliable. ...

How to check if mysql database exists

Is it possible to check if a (MySQL) database exists after having made a connection. I know how to check if a table exists in a DB, but I need to check if the DB exists. If not I have to call another piece of code to create it and populate it. I kn...

Link to all Visual Studio $ variables

I was having a look at $(Configuration),$(ProjectDir) etc. in Visual Studio 2008 for Prebuild events. Is there a link to all of these variables with a definition for each one of them?...

Scroll / Jump to id without jQuery

I have search a lot of topics for a usable solution. But dont found something. Most scripts are just too cluttered for my purposes. Seeking a solution based only on Javascript. In my project it is not possible to use jQuery. I need a jump or scroll t...

What is the idiomatic Go equivalent of C's ternary operator?

In C/C++ (and many languages of that family), a common idiom to declare and initialize a variable depending on a condition uses the ternary conditional operator : int index = val > 0 ? val : -val Go doesn't have the conditional operator. What i...

Changing precision of numeric column in Oracle

Currently I have a column that is declared as a NUMBER. I want to change the precision of the column to NUMBER(14,2). SO, I ran the command alter table EVAPP_FEES modify AMOUNT NUMBER(14,2)' for which, I got an error : column to be modifie...

Make an image width 100% of parent div, but not bigger than its own width

I’m trying to get an image (dynamically placed, with no restrictions on dimensions) to be as wide as its parent div, but only as long as that width isn’t wider than its own width at 100%. I’ve tried this, to no avail: img { width: 100%; ...

How to make Apache serve index.php instead of index.html?

If I put the following line in a index.html file, to make Apache include the index.php file: <?php include("/Live/ls_client/index.php"); ?> visiting the index.html page shows me this: <!--?php include("/Live/ls_client/index.php"); ...

Invalid application path

IIS7 Windows 7 64bit No matter what I do I can't seem to add an application to a web site. When I 'Test settings' I get "Invalid application path". Any one have a guess as to what I could be doing wrong? ...

Get changes from master into branch in Git

In my repository I have a branch called aq which I'm working on. I then committed new work and bugs in master. What is the best way to get those commits into the aq branch? Create another new branch out of master and merge it with aq?...

How to redirect to a 404 in Rails?

I'd like to 'fake' a 404 page in Rails. In PHP, I would just send a header with the error code as such: header("HTTP/1.0 404 Not Found"); How is that done with Rails?...

What is "String args[]"? parameter in main method Java

I'm just beginning to write programs in Java. What does the following Java code mean? public static void main(String[] args) What is String[] args? When would you use these args? Source code and/or examples are preferred over abstract explanat...

python requests file upload

I'm performing a simple task of uploading a file using Python requests library. I searched Stack Overflow and no one seemed to have the same problem, namely, that the file is not received by the server: import requests url='http://nesssi.cacr.caltec...

JavaScript: function returning an object

I'm taking some JavaScript/jQuery lessons at codecademy.com. Normally the lessons provide answers or hints, but for this one it doesn't give any help and I'm a little confused by the instructions. It says to make the function makeGamePlayer return ...

How to make a pure css based dropdown menu?

I am looking horizontal dropdown menu pure css based and browser compatible.... i am looking like mentioned below example ...

C# - Print dictionary

I have made a dictionary which contains two values a DateTime and a string. Now I want to print everything from the dictionary to a Textbox. Does anybody know how to do this. I have used this code to print the dictionary to the console: private void...

How to display my application's errors in JSF?

In my JSF/Facelets app, here's a simplified version of part of my form: <h:form id="myform"> <h:inputSecret value="#{createNewPassword.newPassword1}" id="newPassword1" /> <h:message class="error" for="newPassword1" /> <h:i...

Create a remote branch on GitHub

In SVN I have at least two ways to create a branch: svn cp /home/me/localcheckout/trunk /home/me/localcheckout/branches/newbranch svn cp http://server/trunk http://server/branches/newbranch The first creates it locally then I have to commit the wh...

How to sign an android apk file

I am trying to sign my apk file. I can't figure out how to do it. I can't find good in-depth directions. I have very little programing experience, so any help would be appreciated....

Select all elements with a "data-xxx" attribute without using jQuery

Using only pure JavaScript, what is the most efficient way to select all DOM elements that have a certain data- attribute (let's say data-foo). The elements may be different, for example: <p data-foo="0"></p><br/><h6 da...

How do I enable NuGet Package Restore in Visual Studio?

There's a similar post on stack but it doesn't help with my issue possibly because I am using Visual Studio 2015. How do I get the "Enable NuGet Package Restore" option to appear in VS2015? I chose File > New Project and created an empty ASP.NET We...

How do I know if jQuery has an Ajax request pending?

I'm having some problems with a jQuery control we made. Suppose you have a dropdownlist that allows you to enter the ID of the item you're looking for, and when you press ENTER or lose focus in a textbox it validates via jQuery that the ID you entere...

How to run python script with elevated privilege on windows

I am writing a pyqt application which require to execute admin task. I would prefer to start my script with elevate privilege. I am aware that this question is asked many times in SO or in other forum. But the solution people are suggesting is to hav...

Difference between SRC and HREF

The SRC and HREF attributes are used to include some external entities like an image, a CSS file, a HTML file, any other web page or a JavaScript file. Is there a clear differentiation between SRC and HREF? Where or when to use SRC or HREF? I think...

Can I add color to bootstrap icons only using CSS?

Twitter's bootstrap uses Icons by Glyphicons. They are "available in dark gray and white" by default: Is it possible to use some CSS trickery to change the colors of the icons? I was hoping for some other css3 brilliance that would prevent having ...

How to set auto increment primary key in PostgreSQL?

I have a table in PostgreSQL with many columns, and I want to add an auto increment primary key. I tried to create a column called id of type BIGSERIAL but pgadmin responded with an error: ERROR: sequence must have same owner as table it is linked t...

Why this line xmlns:android="http://schemas.android.com/apk/res/android" must be the first in the layout xml file?

Why is this line needed in xml layout file? xmlns:android="http://schemas.android.com/apk/res/android" ...

How to lookup JNDI resources on WebLogic?

I deployed a legacy application on WebLogic 11g. The application has the following code: Context context = new InitialContext(); dataSource = (javax.sql.DataSource) context.lookup("java:myDataSource"); I also have a data source configured in We...

Write a file in external storage in Android

I want to create a file in external storage sdCard and write to it.I have searched through internet and try but not getting the result,I have added permission in Android Manifest file as well,I am doing this on Emulator,I am trying the following code...

"Untrusted App Developer" message when installing enterprise iOS Application

I'm developing an enterprise application. When I was testing it in iOS8 beta I saw the following alert view: Untrusted App Developer Do you trust the developer "iPhone Distribution: ---" to run apps on you iPad? It only appears the first time. Can...

How can I disable all views inside the layout?

For example I have: <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent"> <Button androi...

In Java, what purpose do the keywords `final`, `finally` and `finalize` fulfil?

In Java, what purpose do the keywords final, finally and finalize fulfil? ...

Usages of doThrow() doAnswer() doNothing() and doReturn() in mockito

I was learning mockito and I understood the basic usages of the above mentioned functions from the link. But I would like to know whether it can be used for any other cases?...

The name 'InitializeComponent' does not exist in the current context

If I create a new project in Visual Studio 2010 SP1 and select "WPF Application" and tries to build the generated application, I get the error The name 'InitializeComponent' does not exist in the current context. I got a similar error this morn...

Difference between ApiController and Controller in ASP.NET MVC

I've been playing around with ASP.NET MVC 4 beta and I see two types of controllers now: ApiController and Controller. I'm little confused at what situations I can choose a particular controller. For ex: If I want to return a view then I've to us...

Accessing Arrays inside Arrays In PHP

Hello I want to access inactive tags inside this array any idea? stdClass::__set_state( array 'languages' => array 76 => array 'id' => string '76' (length=2) 'tag' => string 'Deutsch' (length=7) ...

Iterating over Typescript Map

I'm trying to iterate over a typescript map but I keep getting errors and I could not find any solution yet for such a trivial problem. My code is: myMap : Map<string, boolean>; for(let key of myMap.keys()) { console.log(key); } And I ge...

Sound effects in JavaScript / HTML5

I'm using HTML5 to program games; the obstacle I've run into now is how to play sound effects. The specific requirements are few in number: Play and mix multiple sounds, Play the same sample multiple times, possibly overlapping playbacks, Interrup...

How can I write a byte array to a file in Java?

How to write a byte array to a file in Java?...

Encrypting & Decrypting a String in C#

What is the most modern (best) way of satisfying the following in C#? string encryptedString = SomeStaticClass.Encrypt(sourceString); string decryptedString = SomeStaticClass.Decrypt(encryptedString); BUT with a minimum of fuss involving salts, k...

bash: npm: command not found?

I'm learning laravel and follwing this tutorial, But when I went try and install npm, is says bash: npm: command not found ...

Causes of getting a java.lang.VerifyError

I'm investigating the following java.lang.VerifyError java.lang.VerifyError: (class: be/post/ehr/wfm/application/serviceorganization/report/DisplayReportServlet, method: getMonthData signature: (IILjava/util/Collection;Ljava/util/Collection;Ljava/ut...

Remove characters except digits from string using Python?

How can I remove all characters except numbers from string?...

What is the most efficient/quickest way to loop through rows in VBA (excel)?

I know VBA in Excel isn't the quickest of things - but I need the most efficient (i.e. quickest) way to loop through a large sample of rows. Currently I have: For Each c In Range("$A$2:$A$" & Cells(Rows.count, "A").End(xlUp).row ' do stuff ...

Why is division in Ruby returning an integer instead of decimal value?

For example: 9 / 5 #=> 1 but I expected 1.8. How can I get the correct decimal (non-integer) result? Why is it returning 1 at all?...

PHPExcel How to apply styles and set cell width and cell height to cell generated dynamically

I have form that I generate its content to Excel through PHPExcel, my problem is that how can I set width and height and also styles to the heading cells. the excel generated demo is here: the excel i want is here: here is my code: for ($col ...

How to add not null constraint to existing column in MySQL

I have table name called "Person" with following column names P_Id(int), LastName(varchar), FirstName (varchar). I forgot to give NOT NULL Constraint to P_Id. Now I tried with following query to add NOT NULL Constraint to existing column called ...

ng-model for `<input type="file"/>` (with directive DEMO)

I tried to use ng-model on input tag with type file: <input type="file" ng-model="vm.uploadme" /> But after selecting a file, in controller, $scope.vm.uploadme is still undefined. How do I get the selected file in my controller?...

UEFA/FIFA scores API

Does anybody know if UEFA or FIFA provide a scores api for football matches, official team players list, transfers, etc? I found footytube api but not sure ofits stability and completeness.....

ES6 modules implementation, how to load a json file

I'm implementing an example from https://github.com/moroshko/react-autosuggest Important code is like this: import React, { Component } from 'react'; import suburbs from 'json!../suburbs.json'; function getSuggestions(input, callback) { const s...

How to add text at the end of each line in Vim?

In Vim, I have the following text: key => value1 key => value2 key => value1111 key => value12 key => value1122222 I would like to add "," at the end of each line. The previous text will become the following: key => value1, key ...

When do you use varargs in Java?

I'm afraid of varargs. I don't know what to use them for. Plus, it feels dangerous to let people pass as many arguments as they want. What's an example of a context that would be a good place to use them?...

How to convert a date to milliseconds

I want to convert String myDate = "2014/10/29 18:10:45" to long ms (i.e. currentinmlilies)? I look for it on Google, but I can only find how to convert ms to date. Note: To make it clear, I want to get the ms from the date in 1970/1/1 format....

How to change date format from DD/MM/YYYY or MM/DD/YYYY to YYYY-MM-DD?

i need to change the format of my date string using C# from : "06/16/2010"or "16/06/2010" to : "2010-06-16" can you please help me achieve this thanks...

MD5 is 128 bits but why is it 32 characters?

I read some docs about md5, it said that its 128 bits, but why is it 32 characters? I can't compute the characters. 1 byte is 8 bits if 1 character is 1 byte then 128 bits is 128/8 = 16 bytes right? EDIT: SHA-1 produces 160 bits, so how many cha...

How to ignore the certificate check when ssl

I am trying find a way to ignore the certificate check when request a Https resource, so far, I found some helpful article in internet. But I still have some problem. Please review my code. I just don't understand what does the code ServicePointMan...

How to check if multiple array keys exists

I have a variety of arrays that will either contain story & message or just story How would I check to see if an array contains both story and message? array_key_exists() only looks for that single key in the array. Is there a way to d...

Get path to execution directory of Windows Forms application

I would like to get the path to the execution directory of a Windows Forms application. (That is, the directory in which the executable is located.) Does anyone know of a built-in method in .NET to do this?...

Negative weights using Dijkstra's Algorithm

I am trying to understand why Dijkstra's algorithm will not work with negative weights. Reading an example on Shortest Paths, I am trying to figure out the following scenario: 2 A-------B \ / 3 \ / -2 \ / C From the website: ...

#define macro for debug printing in C?

Trying to create a macro which can be used for print debug messages when DEBUG is defined, like the following pseudo code: #define DEBUG 1 #define debug_print(args ...) if (DEBUG) fprintf(stderr, args) How is this accomplished with a macro?...

Replace a value in a data frame based on a conditional (`if`) statement

In the R data frame coded for below, I would like to replace all of the times that B appears with b. junk <- data.frame(x <- rep(LETTERS[1:4], 3), y <- letters[1:12]) colnames(junk) <- c("nm", "val") this provides: nm val 1 A ...

Showing an image from console in Python

What is the easiest way to show a .jpg or .gif image from Python console? I've got a Python console program that is checking a data set which contains links to images stored locally. How should I write the script so that it would display images pop-...

Windows batch: echo without new line

What is the Windows batch equivalent of the Linux shell command echo -n which suppresses the newline at the end of the output? The idea is to write on the same line inside a loop....

jquery dialog save cancel button styling

I am using jquery ui dialogs in my application. How do I style the "Save" and "Cancel" buttons differently in a jquery dialog? So "Save" is more appealing than the "Cancel". I could use a hyper link for "Cancel", but how do I place that in the same b...

Get current date in DD-Mon-YYY format in JavaScript/Jquery

I need to get the date format as 'DD-Mon-YYYY' in javascript. I had asked a question, and it got marked duplicate to jQuery date formatting But, the answers provided in the question are to get the current date in "DD-MM-YYYY" format and not "DD-MO...

The term "Add-Migration" is not recognized

I'm using this MSDN Tutorial to run in VS2015 the command PM> Add-Migration MyFirstMigration -context BloggingContext that ran yesterday successfully but today it's giving the following error that is also pointed out by other users here. I even de...

Convert LocalDate to LocalDateTime or java.sql.Timestamp

I am using JodaTime 1.6.2. I have a LocalDate that I need to convert to either a (Joda) LocalDateTime, or a java.sqlTimestamp for ormapping. The reason for this is I have figured out how to convert between a LocalDateTime and a java.sql.Timestamp: ...

How do I POST XML data to a webservice with Postman?

I want POST an XML request to a webservice using Postman. However, when I check the available request formats, I only see options for form-data, x-www-form-urlencoded, raw, and binary. How do I POST an XML request to a webservice with Postman?...

Remove spaces from a string in VB.NET

How do you remove spaces from a string in VB.NET?...

What is the best way to implement "remember me" for a website?

I want my website to have a checkbox that users can click so that they will not have to log in each time they visit my website. I know I will need to store a cookie on their computer to implement this, but what should be contained in that cookie? ...

Shell script current directory?

What is current directory of shell script? I this current directory from which I called it? Or this directory where script located?...

Limiting Powershell Get-ChildItem by File Creation Date Range

I use a Powershell command to generate a CSV report of certain file types. My goal is to find out how many were added during a particular date range. Right now, the script finds everything and I sort by date to find my number. I'd like to modify the ...

How to create empty text file from a batch file?

Can somebody remember what was the command to create an empty file in MSDOS using BAT file?...

Allow anything through CORS Policy

How can I disable cors? For some reason I wild carded the allowed origins and headers yet my ajax requests still complain that the origin was not allowed by my CORS policy.... My applications controller : class ApplicationController < ActionCont...

How to compile and run C files from within Notepad++ using NppExec plugin?

How can I configure the NppExec plugin for Notepad++? I would like NppExec to compile my C files, run them, and show their output, all within Notepad++....

Should I add the Visual Studio .suo and .user files to source control?

Visual Studio solutions contain two types of hidden user files. One is the solution .suo file which is a binary file. The other is the project .user file which is a text file. Exactly what data do these files contain? I've also been wondering whethe...

Make xargs execute the command once for each line of input

How can I make xargs execute the command exactly once for each line of input given? It's default behavior is to chunk the lines and execute the command once, passing multiple lines to each instance. From http://en.wikipedia.org/wiki/Xargs: ...

How to get current screen width in CSS?

I use the following CSS code for formatting when screen width is less than 480px, and it works well. @media screen and (min-width: 480px) { body { background-color: lightgreen; } } I would like to get the current width for calculatio...

How does one remove a Docker image?

I'm running Docker under Vagrant under OS X 10.8.4 (Mountain Lion), and whenever I try to delete a saved image, I get an error: $ docker rmi some-image-id 2013/07/15 hh:mm:ss unexpected JSON input According to the rmi help, the proper syntax is d...

How to write to file in Ruby?

I need to read the data out of database and then save it in a text file. How can I do that in Ruby? Is there any file management system in Ruby?...

Why is it bad practice to call System.gc()?

After answering a question about how to force-free objects in Java (the guy was clearing a 1.5GB HashMap) with System.gc(), I was told it's bad practice to call System.gc() manually, but the comments were not entirely convincing. In addition, no one ...

set font size in jquery

I'm not able to change font size using Jquery. I want to change font size of a div. I have defined default font size for body as 12. I tried to change it as follows, but it didn't work :( $("#SelFontSize").change(function(){ $("#"+styleTarget).css({...

Android sample bluetooth code to send a simple string via bluetooth

I want to send a simple string data such as 'a' from an android device to other one via bluetooth. I looked sample bluetooth code in android sdk but it is so complex for me. I cannot understand how I can send only specific data when I press a button....

What is the point of "final class" in Java?

I am reading a book about Java and it says that you can declare the whole class as final. I cannot think of anything where I'd use this. I am just new to programming and I am wondering if programmers actually use this on their programs. If they do,...

Differences between TCP sockets and web sockets, one more time

Trying to understand as best as I can the differences between TCP socket and websocket, I've already found a lot of useful information within these questions: fundamental difference between websockets and pure TCP How to establish a TCP Socket conn...

What is trunk, branch and tag in Subversion?

Possible Duplicate: What do “branch”, “tag” and “trunk” really mean? What is a trunk, branch and tag in Subversion and what are the best practices to use them? What tools can I use for Subversion in Vis...

Error in installation a R package

Please help me, I cannot install "MASS" package. > library(MASS) Error in library(MASS) : there is no package called ‘MASS’ I tried to install MASS package from local: > utils:::menuInstallLocal() package ‘MASS’ successfully unpac...

PHP: maximum execution time when importing .SQL data file

I am trying to import a large .sql data file using phpMyAdmin in XAMPP. However this is taking a lot of time and I keep getting: Fatal error: Maximum execution time of 300 seconds exceeded in C:\xampp\phpMyAdmin\libraries\dbi\DBIMysqli.class.php ...

link button property to open in new tab?

In my application I have some link buttons there but when I right click on them I cannot (they are in disable mode) find the menu items Open in new tab or Open in new window. How do I show those menu items? Code example: <asp:LinkButton id="lb...

SQL Statement with multiple SETs and WHEREs

I am wondering if this is a valid query: UPDATE table SET ID = 111111259 WHERE ID = 2555 AND SET ID = 111111261 WHERE ID = 2724 AND SET ID = 111111263 WHERE ID = 2021 AND SET ID = 111111264 WHERE ID = 2017 ...

find the array index of an object with a specific key value in underscore

In underscore, I can successfully find an item with a specific key value var tv = [{id:1},{id:2}] var voteID = 2; var data = _.find(tv, function(voteItem){ return voteItem.id == voteID; }); //data = { id: 2 } but how do I find what array index tha...

Background color of text in SVG

I want to color the background of svg text similar to background-color in css I was only able to find documentation on fill, which colors the text itself Is it even possible?...

Set min-width in HTML table's <td>

My table has several columns. Each column should have dynamic width that depends on the browser window size. On the other hand, each column must not be too tiny. So I tried to set min-width for those columns but it's not a valid property. Tried min...

Checking that a List is not empty in Hamcrest

I was wondering if anyone knew of a way to check if a List is empty using assertThat() and Matchers? Best way I could see just use JUnit: assertFalse(list.isEmpty()); But I was hoping that there was some way to do this in Hamcrest....

Can I change the name of `nohup.out`?

When I run nohup some_command &, the output goes to nohup.out; man nohup says to look at info nohup which in turn says: If standard output is a terminal, the command's standard output is appended to the file 'nohup.out'; if that cannot ...

Difference between System.DateTime.Now and System.DateTime.Today

Can anyone explain the difference between System.DateTime.Now and System.DateTime.Today in C#.NET? Pros and cons of each if possible....

Is it possible to format an HTML tooltip (title attribute)?

Is it possible to format an HTML tooltip? E.g. I have a DIV with attribute title="foo!". When I have text-size of my browser zoomed in or out in, the text size of the tooltip remains unchanged. Is there a way to make the tooltip font scale with th...

Is there a way to use SVG as content in a pseudo element :before or :after

I want to place some SVG images before some selected elements. I am using jQuery but that is irrelevant. I would like to have the :before element to be as: #mydiv:before { content: '<svg.. code here</svg>'; display: block; width: 22px;...

Difference of two date time in sql server

Is there any way to take the difference between two datetime in sql server? For example, my dates are 2010-01-22 15:29:55.090 2010-01-22 15:30:09.153 So, the result should be 14.063 seconds....

How to set thymeleaf th:field value from other variable

I have a simple text input field where i have to set default value from one object and save its final value in other. The following code is not working. <div th:object="${form}"> <input class="form-control" type="text" ...

Difference between onCreate() and onStart()?

Possible Duplicate: Android Activity Life Cycle - difference between onPause() and OnStop() I was wondering - what is the difference between onCreate() and onStart() methods? I think that onStart() is a redundant method. onCreate() will A...

Postgresql: password authentication failed for user "postgres"

I have installed PostgreSQL 8.4, Postgres client and Pgadmin 3. Authentication failed for user "postgres" for both console client and Pgadmin. I have typed user as "postgres" and password "postgres", because it worked before. But now authentication i...

SQL Server returns error "Login failed for user 'NT AUTHORITY\ANONYMOUS LOGON'." in Windows application

An application that has been working without problem (and has not had any active development done on it in about 6 months or so) recently began failing to connect to database. Operations admins cant say what might have changed that would cause the p...

How can I trigger the click event of another element in ng-click using angularjs?

I'm trying to trigger the click event of the <input type="file"> element from the button. <input id="upload" type="file" ng-file-select="onFileSelect($files)" style="display: none;"> <button type="button" ng-click="an...

How to execute Python scripts in Windows?

I have a simple script blah.py (using Python 2): import sys print sys.argv[1] If I execute my script by: python c:/..../blah.py argument It prints argument but if I execute script by: blah.py argument error occurs: IndexError... So arg...

CSS selector for disabled input type="submit"

Is there a CSS selector for disabled input type="submit" or "button"? Should I just use input[type="submit"][disabled]? Does that work in IE6?...

How to calculate probability in a normal distribution given mean & standard deviation?

How to calculate probability in normal distribution given mean, std in Python? I can always explicitly code my own function according to the definition like the OP in this question did: Calculating Probability of a Random Variable in a Distribution i...

Difference between rake db:migrate db:reset and db:schema:load

The difference between rake db:migrate and rake db:reset is pretty clear in my head. The thing which I don't understand is how rake db:schema:load different from the former two. Just to be sure that I am on the same page: rake db:migrate - Runs th...

How to change angular port from 4200 to any other

I want to use 5000 instead of 4200. I have tried to create a file on root name ember-cli and put JSON according to the code below: { "port": 5000 } But my app still runs on 4200 instead of 5000...

Adding header for HttpURLConnection

I'm trying to add header for my request using HttpUrlConnection but the method setRequestProperty() doesn't seem working. The server side doesn't receive any request with my header. HttpURLConnection hc; try { String authorization = ""; ...

How do I access ViewBag from JS

My attempted methods. Looking at the JS via browser, the @ViewBag.CC is just blank... (missing) var c = "#" + "@ViewBag.CC"; var d = $("#" + "@ViewBag.CC").value; var e = $("#" + "@ViewBag.CC").val(); var c = "@View...

Web API Routing - api/{controller}/{action}/{id} "dysfunctions" api/{controller}/{id}

I have the default Route in Global.asax: RouteTable.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = System.Web.Http.RouteParameter.Optional } ); I wanted to...

How to read the value of a private field from a different class in Java?

I have a poorly designed class in a 3rd-party JAR and I need to access one of its private fields. For example, why should I need to choose private field is it necessary? class IWasDesignedPoorly { private Hashtable stuffIWant; } IWasDesignedPoo...

C# - using List<T>.Find() with custom objects

I'm trying to use a List<T> with a custom class of mine, and being able to use methods like Contains(), Find(), etc., on the list. I thought I'd just have to overload the operator == but apparently, one way of doing that is to use a delegate me...

Adding and removing style attribute from div with jquery

I've inherited a project I'm working on and I'm updating some jquery animations (very little practice with jquery). I have a div I need to add and remove the style attribute from. Here is the div: <div id='voltaic_holder'> At one point in t...

How to fix Array indexOf() in JavaScript for Internet Explorer browsers

If you have worked with JavaScript at any length you are aware that Internet Explorer does not implement the ECMAScript function for Array.prototype.indexOf() [including Internet Explorer 8]. It is not a huge problem, because you can e...

Exception sending context initialized event to listener instance of class org.springframework.web.context.ContextLoaderListener

I am trying to implement the spring security log in and I have tried something like : spring-security.xml: <beans:beans xmlns="http://www.springframework.org/schema/security" xmlns:beans="http://www.springframework.org/schema/beans" xmlns:xsi...

Register comdlg32.dll gets Regsvr32: DllRegisterServer entry point was not found

I have Windows 7, 64-bit. I'm trying to register a .dll (comdlg32.dll) using regsvr32. But I get an error that says the dll is read but the DLLRegistryServer entry point is not found. I have run the command under both System32 and SysWOW64 and I ha...

What is Robocopy's "restartable" option?

robocopy /Z = "copy files in restartable mode". What does this option do? All the documentation I've found simply quotes the on-board manual. What is "restartable" mode, why would someone use it, and how does it differ from "Backup mode" (/B) ?...

Does a TCP socket connection have a "keep alive"?

I have heard of HTTP keep-alive but for now I want to open a socket connection with a remote server. Now will this socket connection remain open forever or is there a timeout limit associated with it similar to HTTP keep-alive?...

Which comment style should I use in batch files?

I've been writing some batch files, and I ran into this user guide, which has been quite informative. One thing it showed me was that lines can be commented not just with REM, but also with ::. It says: Comments in batch code can be made by using...

python catch exception and continue try block

Can I return to executing try-block after exception occurs? (The goal is to write less) For Example: try: do_smth1() except: pass try: do_smth2() except: pass vs try: do_smth1() do_smth2() except: ??? # magic word to ...

Multiple left-hand assignment with JavaScript

var var1 = 1, var2 = 1, var3 = 1; This is equivalent to this: var var1 = var2 = var3 = 1; I'm fairly certain this is the order the variables are defined: var3, var2, var1, which would be equivalent to this: var var3 = 1, var2 = var3, va...

SSL Proxy/Charles and Android trouble

I want to test Https calls from android device using Charles proxy tool. I need to see the raw request/response contents for debugging app. I've configured Charles by adding the host and port under "Proxy Settings" -> SSL Tab. When I run the app, all...

Show week number with Javascript?

I have the following code that is used to show the name of the current day, followed by a set phrase. <script type="text/javascript"> <!-- // Array of day names var dayNames = new Array( "It's Sunday, the weekend is nearly...

filters on ng-model in an input

I have a text input and I don't want to allow users to use spaces, and everything typed will be turned into lowercase. I know I'm not allowed to use filters on ng-model eg. ng-model='tags | lowercase | no_spaces' I looked at creating my own direc...

How to create a file name with the current date & time in Python?

Here is a functional code (create file with success) sys.stdout = open('filename1.xml', 'w') Now I'm trying to name the file with the current date/time (I'm not an expert in Python) filename1 = datetime.now().strftime("%Y%m%d-%H%M%S") sys....

Change a HTML5 input's placeholder color with CSS

Chrome supports the placeholder attribute on input[type=text] elements (others probably do too). But the following CSS doesn't do anything to the placeholder's value: _x000D_ _x000D_ input[placeholder], [placeholder], *[placeholder] { color: red ...

Bizarre Error in Chrome Developer Console - Failed to load resource: net::ERR_CACHE_MISS

As far as I can tell, this error was not being thrown yesterday on Chrome, and as of this morning, it is. I have not changed any of my browser settings. I have attached a screenshot (after opening/closing Developer Tools window four times): This i...

How to add Google Maps Autocomplete search box?

I am trying to add a Google autocomplete search box to a website so that users can search for an address as easily as possible. My problem is, I have looked a numerous questions on here as well as the Google Maps Javascript API v3 regarding this and...

CSS technique for a horizontal line with words in the middle

I'm trying to make a horizontal rule with some text in the middle. For example: ----------------------------------- my title here ----------------------------- Is there a way to do that in CSS? Without all the "-" dashes obviously....

Regular Expression to get all characters before "-"

How can I get the string before the character "-" using regular expressions? For example, I have "text-1" and I want to return "text"....

Set CSS property in Javascript?

I've created the following... var menu = document.createElement('select'); How would I now set CSS attributes e.g width: 100px?...

Transfer files to/from session I'm logged in with PuTTY

I'm logged into a remote host using PuTTY. What is the command to transfer files from my local machine to the machine I'm logged into on PuTTY?...

ImportError: No module named sklearn.cross_validation

I am using python 2.7 in Ubuntu 14.04. I installed scikit-learn, numpy and matplotlib with these commands: sudo apt-get install build-essential python-dev python-numpy \ python-numpy-dev python-scipy libatlas-dev g++ python-matplotlib \ ipython B...

How to Set Focus on JTextField?

I make my game run without mouse so using pointer is not a choice. High Score menu will show when player lose. this is my code highScore=new MyTextField("Your Name"); highScore.addKeyListener(this); highScore.setFont(font); highScor...

Can I create a One-Time-Use Function in a Script or Stored Procedure?

In SQL Server 2005, is there a concept of a one-time-use, or local function declared inside of a SQL script or Stored Procedure? I'd like to abstract away some complexity in a script I'm writing, but it would require being able to declare a function....

Switch: Multiple values in one case?

I have the following piece of code, but yet when I enter "12" I still get "You an old person". Isn't 9 - 15 the numbers 9 UNTIL 15? How else do I handle multiple values with one case? int age = Convert.ToInt32(txtBoxAge.Text); switch (age) ...

Send Message in C#

I'm creating an application that uses a main project that is connected to several different DLLs. From one DLL window I need to be able to open a window in another but the DLL's can't reference each other. It was suggested to me to use the sendmess...

How to unsubscribe to a broadcast event in angularJS. How to remove function registered via $on

I have registered my listener to a $broadcast event using $on function $scope.$on("onViewUpdated", this.callMe); and I want to un-register this listener based on a particular business rule. But my problem is that once it is registered I am not abl...

ASP.NET MVC 5 - Identity. How to get current ApplicationUser

I have an Article entity in my project which has the ApplicationUser property named Author. How can I get the full object of currently logged ApplicationUser? While creating a new article, I have to set the Author property in Article to the current A...

how to start stop tomcat server using CMD?

I set the path for the tomcat and set all variables like JAVA_HOME=C:\Program Files (x86)\Java\jdk1.6.0_22 CATALINA_HOME=G:\springwork\server\apache-tomcat-6.0.29 CLASSPATH=G:\springwork\server\apache-tomcat-6.0.29\lib\servlet-api.jar;G:\springwork...

Array of Matrices in MATLAB

I am looking for a way to store a large variable number of matrixes in an array in MATLAB. Are there any ways to achieve this? Example: for i: 1:unknown myArray(i) = zeros(500,800); end Where unknown is the varied length of the array, I can re...

Print in one line dynamically

I would like to make several statements that give standard output without seeing newlines in between statements. Specifically, suppose I have: for item in range(1,100): print item The result is: 1 2 3 4 . . . How get this to instead look l...

Should I use encodeURI or encodeURIComponent for encoding URLs?

Which of these two methods should be used for encoding URLs?...

Git commit date

Other than parsing git log for the date string, is there a Git native way to report the date of a certain commit?...

How can I retrieve a table from stored procedure to a datatable?

I created a stored procedure so as to return me a table. Something like this: create procedure sp_returnTable body of procedure select * from table end When I call this stored procedure on the frontend what code do I need to write to retrieve it ...

Android getting value from selected radiobutton

I have a piece of code with three RadioButtons within a RadioGroup. I want to set an onCheckedListener that will show the value of the RadioButton in a Toast. However what I have gotten so far is not working. How do I get the value of the RadioButton...

Error in plot.new() : figure margins too large in R

I'm new to R but I've made numerous correlation plots with smaller data sets. However, when I try to plot a large dataset (2gb+), I can produce the plot just fine, but the legend doesn't show up. Any advice? or alternatives? library(gplots) r.cor &l...

macOS on VMware doesn't recognize iOS device

I am using Mac OS in VMWare for iOS app development. After updating the OS and Xcode, the iOS device isn't available so I cannot test it. When the device is plugged in to the PC, the device appears as connected in VMware and marked with green point...

Bootstrap alert in a fixed floating div at the top of page

I have a web application which uses Bootstrap (2.3.2 - corporate policy, we cannot upgrade to 3.0 without lots of testing across several web applications). We have several long pages within this application that require validation of forms and tables...

HTML - How to do a Confirmation popup to a Submit button and then send the request?

I am learning web development using Django and have some problems in where to put the code taking chage of whether to submit the request in the HTML code. Eg. There is webpage containing a form(a blog) to be filled by the user, and upon click on the...

Styling an input type="file" button

How do you style an input type="file" button?...

Python base64 data decode

I have the following piece of base64 encoded data, and I want to use python base64 module to extract information from it. It seems that module does not work. Can anyone tell me how? Q5YACgAAAABDlgAbAAAAAEOWAC0AAAAAQ5YAPwAAAABDlgdNAAAAAEOWB18AAAAAQ...

What's the difference between "end" and "exit sub" in VBA?

In VBA, sometimes we want to exit the program after some condition is true. But do I use end or exit sub? ...

How to insert tab character when expandtab option is on in Vim

When I'm in insert mode and I have the expandtab option switched on, pressing Tab ? results in inserting the configured number of spaces. But occasionally I want to insert an actual tab character. Do you know how to do this?...

How to show text on image when hovering?

I'm trying to show a description when hovering over an image. I've already done it in a less than desirable way, using image sprites and hovers here: I want it to look exactly like how I have it, but using real text instead of an image. I've tried a...

Chrome: Uncaught SyntaxError: Unexpected end of input

When loading my page in Google Chrome, I get a vague error in the console: Uncaught SyntaxError: Unexpected end of input I have no idea what is causing it. How would I go about debugging this error?...

What is the use of the @ symbol in PHP?

I have seen uses of @ in front of certain functions, like the following: $fileHandle = @fopen($fileName, $writeAttributes); What is the use of this symbol?...

How can I convert ticks to a date format?

I am converting a ticks value to a date like this: Convert(datetime, (MachineGroups.TimeAdded - 599266080000000000)/864000000000); Using this i get: 9/27/2009 10:50:27 PM But I want just the date in this format: October 1, 2009 My sample tic...

How can I export a GridView.DataSource to a datatable or dataset?

How can I export GridView.DataSource to datatable or dataset?...

shared global variables in C

How can I create global variables that are shared in C? If I put it in a header file, then the linker complains that the variables are already defined. Is the only way to declare the variable in one of my C files and to manually put in externs at the...

How can VBA connect to MySQL database in Excel?

Dim oConn As ADODB.Connection Private Sub ConnectDB() Set oConn = New ADODB.Connection Dim str As String str = "DRIVER={MySQL ODBC 5.2.2 Driver};" & _ "SERVER=sql100.xtreemhost.com;" & _ ...

Git: Merge a Remote branch locally

I've pulled all remote branches via git fetch --all. I can see the branch I'd like to merge via git branch -a as remotes/origin/branchname. Problem is it is not accessible. I can't merge or checkout....

Installing OpenCV for Python on Ubuntu, getting ImportError: No module named cv2.cv

I have an Ubuntu 14.04 system, on which I want to install OpenCV and use it with Python 2.x. I installed OpenCV using the instructions here: https://help.ubuntu.com/community/OpenCV The install seemed to run properly, no errors, the script ended wi...

Forbidden You don't have permission to access /wp-login.php on this server

I have one problem with all my WordPress's sites. I can access in all and navigate in the posts, pages and other. But when I go to wp-login.php I view the form and put user and password. And when I clicking access goes here: Forbidden You don't have...

Passing a string with spaces as a function argument in bash

I'm writing a bash script where I need to pass a string containing spaces to a function in my bash script. For example: #!/bin/bash myFunction { echo $1 echo $2 echo $3 } myFunction "firstString" "second string with spaces" "thirdStri...

C# - Fill a combo box with a DataTable

I'm used to work with Java where large amounts of examples are available. For various reasons I had to switch to C# and trying to do the following in SharpDevelop: // Form has a menu containing a combobox added via SharpDevelop's GUI // --- Variabl...

How to remove a file from the index in git?

How to remove a file from the index ( = staging area = cache) without removing it from the file system?...

Calling an API from SQL Server stored procedure

Calling an API from ASP.NET Web Form is very easy. WebClient wc = new WebClient(); string urlData = wc.DownloadString("http://xxx.xxx.xx.xx/sssss/getResponse.do?ID=testing"); But can we call an API from SQL Server stored procedure. If yes then ho...

Error message "No exports were found that match the constraint contract name"

This morning I faced a problem while opening my Visual Studio solution, and when I tried to run it, it said: No exports were found that match the constraint contract name How can I fix this problem?...

Get a UTC timestamp

How can I get the current UTC timestamp in JavaScript? I want to do this so I can send timestamps from the client-side that are independent of their timezone....

How to include quotes in a string

I have a string "I want to learn "c#"". How can I include the quotes before and after c#?...

Running Internet Explorer 6, Internet Explorer 7, and Internet Explorer 8 on the same machine

Like everyone else, I need to test my code on Internet Explorer 6 and Internet Explorer 7. Now Internet Explorer 8 has some great tools for developer, which I'd like to use. I'd also like to start testing my code with Internet Explorer 8, as it will ...

Stop node.js program from command line

I have a simple TCP server that listens on a port. var net = require("net"); var server = net.createServer(function(socket) { socket.end("Hello!\n"); }); server.listen(7777); I start it with node server.js and then close it with Ctrl + Z on ...

Change Git repository directory location.

With Git/Github for Windows, if I have a repository with this directory: C:\dir1\dir2, what do I need to do to move the repo files to C:\dir1? I can obviously physically copy and paste the files, but what do I need to do on the Git side? I have thi...

Javascript: How to detect if browser window is scrolled to bottom?

I need to detect if a user is scrolled to the bottom of a page. If they are at the bottom of the page, when I add new content to the bottom, I will automatically scroll them to the new bottom. If they are not at the bottom, they are reading previous ...

A connection was successfully established with the server, but then an error occurred during the pre-login handshake

I am getting following error when i am trying to connect Production DB from Local Environment. I was able to connect Production DB before, but suddenly i am getting following error, any idea? A connection was successfully established with the server...

Can't connect to MySQL server error 111

I installed mysql server on linux box IP = 192.168.1.100 but when i try to connect to this IP it alway error(111). but use localhost and 127.0.0.1 is OK. beer@beer-laptop# ifconfig | grep "inet addr" inet addr:127.0.0.1 Mask:255.0.0.0 ...

PostgreSQL IF statement

How can I do such query in Postgres? IF (select count(*) from orders) > 0 THEN DELETE from orders ELSE INSERT INTO orders values (1,2,3); ...

How to access cookies in AngularJS?

What's the AngularJS way to access cookies? I've seen references to both a service and a module for cookies, but no examples. Is there, or is there not an AngularJS canonical approach?...

How to run php files on my computer

Could anyone please tell me how to run a php file locally on my system. Currently I am using a server to run files. I know both php & Apache to be installed. I need to see out put of this program, for example: <?php $a=5; $b=10; $c=$a+$b; pr...

How to plot a function curve in R

What are the alternatives for drawing a simple curve for a function like eq = function(x){x*x} in R? It sounds such an obvious question, but I could only find these related questions on stackoverflow, but they are all more specific Plot line fu...

Determining 32 vs 64 bit in C++

I'm looking for a way to reliably determine whether C++ code is being compiled in 32 vs 64 bit. We've come up with what we think is a reasonable solution using macros, but was curious to know if people could think of cases where this might fail or if...

How to set an image as a background for Frame in Swing GUI of java?

I have created one GUI using Swing of Java. I have to now set one sample.jpeg image as a background to the frame on which I have put my components.How to do that ?...

What does 'x packages are looking for funding' mean when running `npm install`?

I usually get "x packages are looking for funding." when running npm install on a react project. Any idea what that means?...

Javascript validation: Block special characters

How can I restrict users from entering special characters in the text box. I want only numbers and alphabets to be entered ( Typed / Pasted ). Any samples?...

How to know if two arrays have the same values

I have these two arrays: one is filled with information from an ajax request and another stores the buttons the user clicks on. I use this code (I filled with sample numbers): var array1 = [2, 4]; var array2 = [4, 2]; //It cames from the user button...

How to decrease prod bundle size?

I have a simple app, initialized by angular-cli. It display some pages relative to 3 routes. I have 3 components. On one of this page I use lodash and Angular 2 HTTP modules to get some data (using RxJS Observables, map and subscribe). I display the...

How do I edit a file after I shell to a Docker container?

I successfully shelled to a Docker container using: docker exec -i -t 69f1711a205e bash Now I need to edit file and I don't have any editors inside: root@69f1711a205e:/# nano bash: nano: command not found root@69f1711a205e:/# pico bash: pico: com...

Handling errors in Promise.all

I have an array of Promises that I'm resolving with Promise.all(arrayOfPromises); I go on to continue the promise chain. Looks something like this existingPromiseChain = existingPromiseChain.then(function() { var arrayOfPromises = state.routes.ma...

How to show an alert box in PHP?

I want to display an alert box showing a message with PHP. Here is my PHP code: <?php header("Location:form.php"); echo '<script language="javascript">'; echo 'alert(message successfully sent)'; //not showing an alert box. echo...

How to show matplotlib plots in python

I am sure the configuration of matplotlib for python is correct since I have used it to plot some figures. But today it just stop working for some reason. I tested it with really simple code like: import matplotlib.pyplot as plt import numpy as np ...

Database Structure for Tree Data Structure

What would be the best way to implement a customizable tree data structure (meaning, a tree structure with an unknown number of level) in a database? I've done this once before using a table with a foreign key to itself. What other implementations c...

failed to open stream: HTTP wrapper does not support writeable connections

I have uploaded my localhost files to my website but it is showing me this error:- : [2] file_put_contents( ***WebsiteURL*** /cache/lang/ ***FileName*** .php) [function.file-put-contents]: failed to open stream: HTTP wrapper does not support write...

Adding <script> to WordPress in <head> element

I'm trying to insert this code: <script type="text/javascript"> some Javascript codes comes here </script> to WordPress' <head></head> section in front end and in admin panel E.g., Joomla! 1.6 has an API that allows t...

Why use Gradle instead of Ant or Maven?

What does another build tool targeted at Java really get me? If you use Gradle over another tool, why?...

Explain ggplot2 warning: "Removed k rows containing missing values"

I get this warning when I am trying to generate a plot with ggplot. After researching online for a while many suggested that my database contains either null values or missing data in general, which was not the case. In this question the accepted a...

Installing Git on Eclipse

How can I install Git on Eclipse? I found tutorials on http://cho.hapgoods.com/wordpress/?p=159 but there was said that "You should then see the eight Eclipse projects 'org.spearce.something.'" I don't see those eight projects....

Pointer arithmetic for void pointer in C

When a pointer to a particular type (say int, char, float, ..) is incremented, its value is increased by the size of that data type. If a void pointer which points to data of size x is incremented, how does it get to point x bytes ahead? How does the...

async at console app in C#?

I have this simple code : public static async Task<int> SumTwoOperationsAsync() { var firstTask = GetOperationOneAsync(); var secondTask = GetOperationTwoAsync(); return await firstTask + await secondTask; } private async Task<...

COPYing a file in a Dockerfile, no such file or directory?

I have a Dockerfile set up in my root (~) folder. The first three lines of my file look like this: COPY file1 /root/folder/ COPY file2 /root/folder/ COPY file3 /root/folder/ but it returns the following error for each line: No such file or dir...

could not extract ResultSet in hibernate

I have a problem with Hibernate. I try to parse to List but It throws an exception: HTTP Status 500 - could not extract ResultSet. When I debug, It fault at line query.list()... My sample code here @Entity @Table(name = "catalog") public class Ca...

Exception in thread "main" java.lang.OutOfMemoryError: Java heap space

I have written a code and I run it a lot but suddenly I got an OutOfMemoryError: Exception in thread "main" java.lang.OutOfMemoryError: Java heap space at javax.media.j3d.BoundingBox.<init>(BoundingBox.java:86) at javax.media...

Unsupported operand type(s) for +: 'int' and 'str'

I am currently learning Python so I have no idea what is going on. num1 = int(input("What is your first number? ")) num2 = int(input("What is your second number? ")) num3 = int(input("What is your third number? ")) numlist = [num1, num2, num3] prin...

Checking if element exists with Python Selenium

I have a problem - I am using the selenium (firefox) web driver to open a webpage, click a few links etc. then capture a screenshot. My script runs fine from the CLI, but when run via a cronjob it is not getting past the first find_element() test. I...

Why is jquery's .ajax() method not sending my session cookie?

After logging in via $.ajax() to a site, I am trying to send a second $.ajax() request to that site - but when I check the headers sent using FireBug, there is no session cookie being included in the request. What am I doing wrong?...

Set encoding and fileencoding to utf-8 in Vim

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

How to fix/convert space indentation in Sublime Text?

Example: If I have a document with 2 space indentation, and I want it to have 4 space indentation, how do I automatically convert it by using the Sublime Text editor?...

Programmatically register a broadcast receiver

I'd like to know what is the best practice/way of programmatically register a broadcast receiver. I want to register specific receivers according to user choice. As the registration is done through the manifest file, I'm wondering if there's a prope...

How do I get a list of all subdomains of a domain?

I want to find out all the subdomains of a given domain. I found a hint which tells me to dig the authoritative Nameserver with the following option: dig @ns1.foo.bar some_domain.com axfr But this never works. Has anyone a better idea/approach...

How to remove \xa0 from string in Python?

I am currently using Beautiful Soup to parse an HTML file and calling get_text(), but it seems like I'm being left with a lot of \xa0 Unicode representing spaces. Is there an efficient way to remove all of them in Python 2.7, and change them into spa...

Best way to save a trained model in PyTorch?

I was looking for alternative ways to save a trained model in PyTorch. So far, I have found two alternatives. torch.save() to save a model and torch.load() to load a model. model.state_dict() to save a trained model and model.load_state_dict() to l...

SQL 'like' vs '=' performance

This question skirts around what I'm wondering, but the answers don't exactly address it. It would seem that in general '=' is faster than 'like' when using wildcards. This appears to be the conventional wisdom. However, lets suppose I have a col...

SQL select * from column where year = 2010

This is probably a simple where clause but I want to say, from columnX (which is datetime) I want all rows where just the year = 2010. so: select * from mytable where Columnx = ...

Android Studio error: "Environment variable does not point to a valid JVM installation"

When trying to run Android Studio on my computer, I get the following error: The Environment variable JAVA_HOME (with a value of C:\Program Files(x86)\Java\jdk1.7.0_51\bin) does not point to a valid JVM installation I tried to remove the \bin ...

Alter a MySQL column to be AUTO_INCREMENT

I’m trying to modify a table to make its primary key column AUTO_INCREMENT after the fact. I have tried the following SQL, but got a syntax error notification. ALTER TABLE document ALTER COLUMN document_id AUTO_INCREMENT Am I doing something wr...

Get value of a string after last slash in JavaScript

I am already trying for over an hour and cant figure out the right way to do it, although it is probably pretty easy: I have something like this : foo/bar/test.html I would like to use jQuery to extract everything after the last /. In the example a...

How to check for a valid Base64 encoded string

Is there a way in C# to see if a string is Base 64 encoded other than just trying to convert it and see if there is an error? I have code code like this: // Convert base64-encoded hash value into a byte array. byte[] HashBytes = Convert.FromBase64S...

Using "If cell contains #N/A" as a formula condition.

I need help on my Excel sheet. How can I declare the following IF condition properly? if A1 = "n/a" then C1 = B1 else if A1 != "n/a" or has value(int) then C1 = A1*B1 ...

Splitting string into multiple rows in Oracle

I know this has been answered to some degree with PHP and MYSQL, but I was wondering if someone could teach me the simplest approach to splitting a string (comma delimited) into multiple rows in Oracle 10g (preferably) and 11g. The table is as foll...

How to convert a byte to its binary string representation

For example, the bits in a byte B are 10000010, how can I assign the bits to the string str literally, that is, str = "10000010". Edit I read the byte from a binary file, and stored in the byte array B. I use System.out.println(Integer.toBi...

How do I keep jQuery UI Accordion collapsed by default?

I am working with jQuery UI Accordion and it works great, but I would like to have the accordion stay closed unless it I click on it. I am using this code right now, which allows be to toggle it closed: $("#accordion").accordion({ header: "h3", col...

Find a value in an array of objects in Javascript

I know similar questions have been asked before, but this one is a little different. I have an array of unnamed objects, which contain an array of named objects, and I need to get the object where "name" is "string 1". Here is an example array. var ...

Page unload event in asp.net

Is it possible to call a write a Page_Unload event in code behind similar to Page_Load event? I wanted to call a method on Page Unload. How do I achieve that?...

How can I display a pdf document into a Webview?

I want to display pdf contents on webview. Here is my code: WebView webview = new WebView(this); setContentView(webview); webview.getSettings().setJavaScriptEnabled(true); webview.loadUrl("http://www.adobe.com/devnet/acrobat/pdfs/pdf_open_paramete...

How to write a cursor inside a stored procedure in SQL Server 2008

I have two tables in my database Coupon Table id (int) Name (nvarchar(max)) NoofUses (int) CouponUse Table id(int) Couponid(int) CreateDate(datetime) Whenever a user clicks on a coupon an entry goes into the CouponUse table containing that...

Usage of \b and \r in C

\b and \r are rarely used in practice. I just found out that I misunderstood these two escape sequences. A simple test: printf("foo\bbar\n"); I expected it to output fobar, because \b will backspace the cursor, and b will overwrite the second o, b...

Simplest way to do grouped barplot

I have the following dataframe: Catergory Reason Species 1 Decline Genuine 24 2 Improved Genuine 16 3 Improved Misclassified 85 4 Decline Misclassified 41 5 Decline Taxonomic 2 6 Improved ...

Change keystore password from no password to a non blank password

I have a jks keystore with no password. When I run the command keytool -list -keystore mykeystore.jks And it prompts me for the keystore password, I simply hit 'enter'. Please note that the keystore password IS NOT the default java password of '...

How do I set the default locale in the JVM?

I want to set the default Locale for my JVM to fr_CA. What are the possible options to do this? I know of only one option Locale.setDefault()...