Id int64 34.6M 60.5M | Title stringlengths 15 150 | Body stringlengths 33 36.7k | Tags stringlengths 3 112 | CreationDate stringdate 2016-01-01 00:21:59 2020-02-29 17:55:56 | Y stringclasses 3 values |
|---|---|---|---|---|---|
35,387,227 | Get device token with react native | <p>Is there any way to get the device token for notifications on demand with react native? It seems, from the docs, like the only time the token is exposed is on the PushNotification register event.</p>
<p>More generally, what's the common practice for handling device tokens? </p>
<p>If one user logs into my app, the app requests permissions from PushNotification, the register event is fired and I can associate that device with the logged in user. So far so good, but if that user logs out, and I break that association to stop the notifications, what do I do when another user logs in? The app already has permissions, so register won't fire again. How do I get the device token to associate it with the new user? </p>
<p>Or am I thinking about this the wrong way?</p>
| <push-notification><react-native> | 2016-02-14 01:03:16 | HQ |
35,387,327 | How do I make a new line in swift | <p>Is there a way to have a way to make a new line in swift like "\n" for java?</p>
<pre><code>var example: String = "Hello World \n This is a new line"
</code></pre>
| <string><swift> | 2016-02-14 01:17:11 | HQ |
35,387,668 | Why should use Version Control software rather a wordprocessor | <p>A word-processor has most if not all the features of a version control software without the gobbledegook and the complexity. You can set a word-processor to always keep history and probably save as versions every time you save. You could have an online word-processor- if one doesn't exist then it sounds like a great opportunity- with general access to allow multiple users to access it. Git and others are acknowledged to have multiple issues but I can't see a word-processor having big issues so why the preference for version control software? </p>
| <version-control> | 2016-02-14 02:19:51 | LQ_CLOSE |
35,387,680 | loan payment project in Python | I am learning Python and am stuck. I am trying to find the loan payment amount. I currently have:
def myMonthlyPayment(Principal, annual_r, n):
years = n
r = ( annual_r / 100 ) / 12
MonthlyPayment = (Principal * (r * ( 1 + r ) ** years / (( 1 + r ) ** (years - 1))))
return MonthlyPayment
n=(input('Please enter number of years of loan'))
annual_r=(input('Please enter the interest rate'))
Principal=(input('Please enter the amount of loan'))
However, when I run, I am off by small amount. If anyone can point to my error, it would be great. I am using Python 3.4. | <python><python-3.x><finance> | 2016-02-14 02:22:49 | LQ_EDIT |
35,387,843 | An iterator for reading a file byte by byte | <p>Is there an iterator for reading a file <a href="https://docs.python.org/3.1/library/functions.html#bytearray" rel="nofollow">byte by byte</a>?</p>
| <python><python-2.7><file><iterator><byte> | 2016-02-14 02:52:10 | LQ_CLOSE |
35,388,115 | Cant connect to SQL data base C# | Ive installed and reinstalled SQL server express 2014 and visual studio still wont let me connect to a database. It wont even let me create a database. here is a image of the error message. Has anyone encountered this before?
[error message][1]
[1]: http://i.stack.imgur.com/GEjPp.png | <c#><sql-server><database> | 2016-02-14 03:42:04 | LQ_EDIT |
35,389,897 | Java Program using Linked List | <p>I am making a program in which the program shows some options like insert Book, delete Book etc. The program asks us to enter certain details about a book by Insert method.</p>
<p>I have made every method but I have no any idea of how to make a delete method. It's my assignment in class. First of all I am very very weak in programming and especially in linked list. So any help regarding delete method will be appreciated. Here is my code...</p>
<pre><code>import java.util.Scanner;
public class BookApplication {
static Book head, pointer;
static Scanner scan = new Scanner(System.in);
public static void main(String[] args) {
System.out.println("Welcome to Smart Book Store");
System.out.println("Please choose an option from the list below");
int choice = 0;
do {
System.out.println("1. Insert Book\n2. Delete Book\n3. Search Book\n4. Update Book\n5. View Book\n6. Exit");
choice = scan.nextInt();
try {
choice = Integer.parseInt(scan.nextLine());
} catch (Exception e) {
switch (choice) {
case 1:
addBook();
break;
case 2:
case 3:
searchBook();
break;
case 4:
updateBook();
viewBook();
break;
case 5:
viewBook();
break;
case 6:
scan.close();
System.exit(0);
break;
default:
System.out.println("Please choose from 1 to 5");
break;
}
}
} while (true);
}
static void addBook() {
if (head == null) {
String details[] = enterDetails();
pointer = new Book(details[0], details[1], details[2]);
head = pointer;
pointer.next = null;
} else {
String details[] = enterDetails();
pointer.next = new Book(details[0], details[1], details[2]);
pointer = pointer.next;
}
}
static String[] enterDetails() {
String[] details = new String[4];
try {
String title;
String ISBN;
String authors;
System.out.println("Please enter Book title");
title = scan.nextLine();
System.out.println("Please enter ISBN of book");
ISBN = scan.nextLine();
System.out.println("Please enter book's Author(s)");
authors = scan.nextLine();
details[0] = title;
details[1] = ISBN;
details[2] = authors;
} catch (Exception e) {
e.printStackTrace();
}
return details;
}
private static void searchBook() {
System.out.println();
System.out.println("1. Search by TITLE");
System.out.println("2. Search by ISBN");
System.out.println("3. Search by AUTHOR");
int choice = 0;
choice: try {
choice = Integer.parseInt(scan.nextLine());
} catch (Exception e) {
System.out.println();
System.out.println("PLEASE ENTER VALUE BETWEEN 1 - 3");
break choice;
}
switch (choice) {
case 1:
System.out.println("Please enter Title of BOOK");
String title = scan.nextLine();
if (head == null) {
System.out.println("List is EMPTY !");
return;
} else {
System.out.println();
System.out.println("BOOK(S) IN THE SYSTEM ARE: ");
System.out.println();
pointer = head;
while (pointer != null) {
if (pointer.getTitle().equals(title)) {
System.out.println(pointer.getBook());
}
pointer = pointer.next;
}
}
break;
case 2:
System.out.println("Please enter ISBN of BOOK");
String ISBN = scan.nextLine();
if (head == null) {
System.out.println("List is EMPTY !");
return;
} else {
System.out.println();
System.out.println("BOOK(S) IN THE SYSTEM ARE: ");
System.out.println();
pointer = head;
while (pointer != null) {
if (pointer.getISBN().equals(ISBN)) {
System.out.println(pointer.getBook());
break;
}
pointer = pointer.next;
}
}
break;
case 3:
System.out.println("Please enter Author(s) of BOOK");
String authors = scan.nextLine();
if (head == null) {
System.out.println("List is EMPTY !");
return;
} else {
System.out.println();
System.out.println("BOOK(S) IN THE SYSTEM ARE: ");
System.out.println();
pointer = head;
while (pointer != null) {
if (pointer.getAuthors().contains(authors)) {
System.out.println(pointer.getBook());
break;
}
pointer = pointer.next;
}
}
break;
default:
System.out.println("PLEASE ENTER VALUE BETWEEN 1 - 5");
}
}
static void updateBook() {
System.out.println();
System.out.println("1. Update by TITLE");
System.out.println("2. Update by ISBN");
System.out.println("3. Update by AUTHOR");
int choice = 0;
choice: try {
choice = Integer.parseInt(scan.nextLine());
} catch (Exception e) {
System.out.println();
System.out.println("PLEASE ENTER VALUE BETWEEN 1 - 3");
break choice;
}
switch (choice) {
case 1:
System.out.println("Please provide the Title of Book you want to update: ");
String another1 = scan.nextLine();
if (head == null) {
System.out.println("No Books to Update");
return;
} else {
Boolean found = false;
pointer = head;
while (!found & pointer != null) {
if (pointer.getTitle().equals(another1)) {
found = true;
System.out.println("Here is the current book:" + pointer.getBook());
System.out.println("Please enter the new Title:");
pointer.setTitle(scan.nextLine());
System.out.println("Please Enter the new ISBN:");
pointer.setISBN(scan.nextLine());
System.out.println("Please Enter the new Author:");
pointer.setAuthors(scan.nextLine());
}
pointer = pointer.next;
}
}
break;
case 2:
System.out.println("Please provide the ISBN of Book you want to update: ");
String ISBN = scan.nextLine();
if (head == null) {
System.out.println("No Books to Update!");
return;
} else {
Boolean found = false;
pointer = head;
while (!found && pointer != null) {
if (pointer.getISBN().equals(ISBN)) {
found = true;
System.out.println("Here is the current book:" + pointer.getBook());
System.out.println("Please enter the new Title:");
pointer.setTitle(scan.nextLine());
System.out.println("Please Enter the new ISBN:");
pointer.setISBN(scan.nextLine());
System.out.println("Please Enter the new Author:");
pointer.setAuthors(scan.nextLine());
}
pointer = pointer.next;
}
}
case 3:
System.out.println("Please enter Author(s) of the Book you want to Update: ");
String upauthor1 = scan.nextLine();
if (head == null) {
System.out.println("List is EMPTY !");
return;
} else {
Boolean found = false;
pointer = head;
while (!found && pointer != null) {
if (pointer.getAuthors().contains(upauthor1)) {
found = true;
System.out.println("Here is the current book:" + pointer.getBook());
System.out.println("Please enter the new Title:");
pointer.setTitle(scan.nextLine());
System.out.println("Please Enter the new ISBN:");
pointer.setISBN(scan.nextLine());
System.out.println("Please Enter the new Author:");
pointer.setAuthors(scan.nextLine());
}
pointer = pointer.next;
}
break;
}
}
}
private static void viewBook() {
Book element = head;
System.out.println();
System.out.println("Printing List");
while (element != null) {
System.out.println(element.getBook());
element = element.next;
}
System.out.println("Book Printing Ended");
System.out.println();
}
private static void deleteBook() {
System.out.println();
System.out.println("1. Delete by Title");
System.out.println("2. Delete by ISBN");
System.out.println("3. Delete by Author(s)");
}
}
</code></pre>
<p>As you can see I have left delete Method blank because I have no idea how to delete a specific book which is inserted in the beginning of compilation.</p>
<p>Here is my Book class</p>
<pre><code>public class Book {
private String authors;
private String ISBN;
private String title;
public Book next;
Book(String title, String ISBN, String authors) {
this.title = title;
this.authors = authors;
this.ISBN = ISBN;
}
public String getAuthors() {
return authors;
}
public void setISBN(String ISBN){
this.ISBN = ISBN;
}
public void setTitle(String title){
this.title = title;
}
public void setAuthors(String authors) {
this.authors = authors;
}
public String getISBN() {
return ISBN;
}
public String getTitle() {
return title;
}
public String getBook() {
return "Book [authors=" + authors + ", ISBN=" + ISBN + ", title="+ title + "]";
}
</code></pre>
<p>}</p>
| <java> | 2016-02-14 08:40:42 | LQ_CLOSE |
35,389,936 | What this sentence means? | <p>i have read this sentence in the object oriented paradigm approach.</p>
<blockquote>
<p>A class can never have property values or state. Only objects can.</p>
</blockquote>
<p>Can anybody elaborate this ?</p>
| <php><oop> | 2016-02-14 08:47:17 | LQ_CLOSE |
35,390,874 | How to use WD My Book Live share as Raspberry PI owncloud server data directory? | <p>I have installed owncloud based on MySQL on a raspberry pi. On my My Book Live NAS I created a new share called owncloud. On my PI I added the following line to /etc/fstab</p>
<pre><code>//nas001.local/Owncloud /mnt/shares/nas001/owncloud cifs username=<user>,password=<pwd> 0 0
</code></pre>
<p>The share is accessible on /mnt/shares/nas001/owncloud</p>
<p>When I try to finish the owncloud setup I am getting the error message:</p>
<pre><code>Can't create or write into the data directory /mnt/shares/nas001/owncloud
</code></pre>
<p>When I enter the following command I am getting no error message and the content of the directory will be displayed.</p>
<pre><code>sudo -u www-data ls -lisa /mnt/shares/nas001/owncloud
</code></pre>
<p>The owncloud share looks like this</p>
<pre><code>drwxr-xr-x 2 root root 0 Feb 14 07:34 owncloud
</code></pre>
<p>Tried the following</p>
<pre><code>chown -R www-data:www-data /mnt/shares/nas001/owncloud
chmod -R 0777 /mnt/shares/nas001/owncloud
</code></pre>
<p>Nothing changed.</p>
<p>Is there a way to use a My Book Live share as data directory for a Rasperry PI owncloud server?</p>
| <linux><raspberry-pi><nas><owncloud> | 2016-02-14 10:48:15 | LQ_CLOSE |
35,391,639 | Powershell Editor with debugging and intellisense feature | <p>I am new in <code>Powershell</code> and trying to write a <code>Powershell</code> script which will automate the web application deployment to a windows server. But I don't find any good IDE for this. Right now I am using Notepad++ but that has no <strong>debugging</strong> feature. Is there any IDE or editor for <code>Powershell</code> with debugging feature?</p>
| <c#><.net><windows><powershell> | 2016-02-14 12:18:54 | LQ_CLOSE |
35,392,226 | If statement not detecting boolean change | <p>Even though I changed the boolean, "root", the if statement uses the event that is supposed to find the square root of a number instead of doing the normal operations (addition, subtraction, etc.)</p>
<pre><code> String piCheck = "pi";
String rootCheck = "square root";
Double n1 = null;
boolean root = false;
Scanner reader = new Scanner(System.in);
System.out.println("Welcome to Calculator!");
System.out.println(" ");
System.out.println("Enter a number, ");
System.out.println("or enter 'pi' to insert PI,");
System.out.println("or enter 'square root' to find the square root of a number.");
String input = reader.nextLine();
if (input.toLowerCase().contains(piCheck)) {
n1 = Math.PI;
root = false;
} else if (input.toLowerCase().contains(rootCheck)) {
root = true;
} else {
n1 = Double.parseDouble(input);
root=false;
}
if (root = true) {
System.out.println("Which number would you like to find the square root of?");
n1 = reader.nextDouble();
System.out.println("The square root of " + n1 + " is:");
System.out.println(Math.sqrt(n1));
} else if (root != true) {
Scanner reader2 = new Scanner(System.in);
System.out.println("Would you like to multiply, divide, add, subtract?");
String uOperation = reader2.nextLine();
</code></pre>
| <java><if-statement> | 2016-02-14 13:16:37 | LQ_CLOSE |
35,392,699 | How to merge two arrays in Angular? | <p>According to <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/concat" rel="nofollow">JS documentation</a> there a concat() method for concatenating arrays, but if I try it in angular:</p>
<pre><code>$scope.array1 = [];
$scope.array2 = [];
$scope.myConcatenatedData = array1 .concat(array2);
</code></pre>
<p>I got an error: <code>ReferenceError: array1 is not defined</code> because I don't use var in declaring arrays. </p>
| <javascript><arrays><angularjs><concat> | 2016-02-14 14:06:44 | LQ_CLOSE |
35,393,256 | Can you speed up this algorithm? C# / C++ | <p>Hey I've been working on something from time to time and it has become relatively large now (and slow). However I managed to pinpoint the bottleneck after close up measuring of performance in function of time.</p>
<p>Say I want to "permute" the string "ABC". What I mean by "permute" is not quite a permutation but rather a continuous substring set following this pattern:</p>
<pre><code>A
AB
ABC
B
BC
C
</code></pre>
<p>I have to check for every substring if it is contained within another string S2 so I've done some quick'n dirty literal implementation as follows:</p>
<pre><code>for (int i = 0; i <= strlen1; i++)
{
for (int j = 0; j <= strlen2- i; j++)
{
sub = str1.Substring(i, j);
if (str2.Contains(sub)) {do stuff}
else break;
</code></pre>
<p>This was very slow initially but once I realised that if the first part doesnt exist, there is no need to check for the subsequent ones meaning that if sub isn't contained within str2, i can call break on the inner loop.</p>
<p>Ok this gave blazing fast results but calculating my algorithm complexity I realised that in worst case this will be N^4 ? I forgot that str.contains() and str.substr() both have their own complexities (N or N^2 I forgot which).</p>
<p>The fact that I have a huge amount of calls on those inside a 2nd for loop makes it perform rather.. well N^4 ~ said enough.</p>
<p>However I calculated the average run-time of this both mathematically using probability theory to evaluate the probability of growth of the substring in a pool of randomly generated strings (this was my base line) measuring when the probability became > 0.5 (50%)</p>
<p>This showed an exponential relationship between the number of different characters and the string length (roughly) which means that in the scenarios I use my algorithm the length of string1 wont (most probably) never exceed 7</p>
<p>Thus the average complexity would be ~O(N * M) where N is string length1 and M is string length 2. Due to the fact that I've tested N in function of constant M, I've gotten linear growth ~O(N) (not bad opposing to the N^4 eh?)</p>
<p>I did time testing and plotted a graph which showed nearly perfect linear growth so I got my actual results matching my mathematical predictions (yay!)</p>
<p>However, this was NOT taking into account the cost of string.contains() and string.substring() which made me wonder if this could be optimized even further?</p>
<p>I've been also thinking of making this in C++ because I need rather low-level stuff? What do you guys think? I have put a great time into analysing this hope I've elaborated everything clear enough :)!</p>
| <c#><c++><string><algorithm> | 2016-02-14 15:06:38 | LQ_CLOSE |
35,394,559 | Nonlinear system of equation in R packages | <p>Can anybody help to give some name of the R packages which will able to solve non-linear system of equation?</p>
| <r><packages> | 2016-02-14 17:07:05 | LQ_CLOSE |
35,394,810 | Resizing images with javascript on a JSF page in a ui:repeat | I need to resize images sitting in JSF's repeat loop.
This is the loop:
<ui:repeat value="#{searchResults.products}" var="product">
<img id="thumbnailId" src='#{product.thumbnailUrl}' class="img-responsive galleryproductimg" style="border: 0px solid blue; margin-top:10px;" />
</ui:repeat>
And my `javascript code`:
<h:outputScript target="head">
$(document).ready(function() {
console.log("ready to go");
var imgs = getElementsById("thumbnailId");
for (var i = 0; i < imgs.length; i++) {
var img = imgs[i];
img.onload = function () {
console.log("image is loaded");
}
resizeImage(img);
}
});
The methods called from this:
function getElementsById(elementID) {
var elementCollection = new Array();
var allElements = document.getElementsByTagName("*");
for(i = 0; i < allElements.length; i++) {
if(allElements[i].id == elementID)
elementCollection.push(allElements[i]);
}
return elementCollection;
}
And
function resizeImage(img) {
console.log("width, height, src " + img.width + ", " + img.height + ", " + img.src);
console.log("loaded? " + img.complete);
var width = img.width;
var height = img.height;
var constant = 100;
var ratio = width / height;
console.log("ratio " + ratio);
if(width > constant || height > constant) {
var newWidth = constant;
var newHeight = constant*ratio;
if(width > height) {
newWidth = constant;
newHeight = constant*ratio;
} else {
newWidth = constant*ratio;
newHeight = constant;
}
console.log("newWidth, newHeight " + newWidth + ", " + newHeight);
//img.width = newWidth;
//img.height = newHeight;
img.style.width = newWidth + "px;";
img.style.height = newHeight + + "px;";
console.log("img from url AFTER " + img.width + ", " + img.height);
}
console.log("==========================");
}
The code seems right, and works for one image. But not inside the repeat. The output I get is this:
ready to go
resizeImages called
width, height, src 84, 110, http://thumbs1.ebaystatic.com/m/mPlrV_wS_b1vK9avUQ22r9w/140.jpg
loaded? true
ratio 0.7636363636363637
newWidth, newHeight 76.36363636363637, 100
img from url AFTER 84, 110
==========================
width, height, src 86, 110, http://thumbs1.ebaystatic.com/m/mIeHLNVqUI1opFM0NmZvH_A/140.jpg
loaded? true
ratio 0.7818181818181819
newWidth, newHeight 78.18181818181819, 100
img from url AFTER 86, 110
==========================
2 image is loaded
So basically I'm not even getting the correct dimensions of the image at the start. For some reason the width is always 110. Any idea what's going on here? | <javascript><jquery><image-resizing> | 2016-02-14 17:29:08 | LQ_EDIT |
35,394,886 | How to prevent page refresh after sending email? | <p>I made a landing site with a email form.</p>
<p>Every time I click submit, whether the form is completely filled out or not, the page refreshes and goes to the top.</p>
<p>How can I not letting it refresh and still send the mail?</p>
<p>If that's not possible, how do I automatically go back to the contact section/div after the page refresh?</p>
| <php><html><email> | 2016-02-14 17:36:16 | LQ_CLOSE |
35,395,278 | Empty span dissappeared | I have this html:
<div class="panel panel-info">
<div class="panel-heading">Person</div>
<div class="panel-body">
<div class="data">
<p class="keys">
<label>Name: </label>
<label>Family: </label>
</p>
<p>
<span ng-bind="name"></span>
<span ng-bind="family"></span>
</p>
</div>
</div>
</div>
.data {
display: flex;
}
.keys, .values {
display: flex;
flex-direction: column;
margin: 0;
}
For some reason, if my first span is empty, the second one will appear instead. I dont want the empty span to disappear. First time it happens to me! | <html><angularjs><css><flexbox> | 2016-02-14 18:11:10 | LQ_EDIT |
35,395,553 | how to use parent constructor? | <p>please help solve the problem. i have base class 'Unit':</p>
<pre><code>var Unit = function() {
this.x_coord = x_coord;
this.y_coord = y_coord;
this.color = color;
};
</code></pre>
<p>and child class 'playerUnit':</p>
<pre><code>var playerUnit = function(gameObj, x_coord, y_coord, color) {
Unit.apply(this, arguments);
};
playerUnit.prototype = Object.create(Unit.prototype);
var Game = function(options) {
new playerUnit(this,1,1,'red');
};
var app = new Game();
</code></pre>
<p>I plan in the future to do a lot of these child classes: 'enemyUnit', 'tankUnit', 'boatUnit', etc. and i need use common properties: x_coord, y_coord, color.</p>
<pre><code>i try use Unit.apply(this, arguments);
</code></pre>
<p>but after start script i have in console follow error message: </p>
<blockquote>
<p>Uncaught ReferenceError: x_coord is not defined</p>
</blockquote>
<p>jsfiddle: <a href="https://jsfiddle.net/vzk73qah/2/" rel="nofollow">https://jsfiddle.net/vzk73qah/2/</a></p>
| <javascript><oop> | 2016-02-14 18:36:05 | LQ_CLOSE |
35,395,622 | Conversion of array of double value in to a character array | I need to send an array of 4 double value in to a character buffer of size 8 byte and also
would like to extract the value from the character array in to double value for its usage.
-I am trying with the below code but not getting correct output as
char str is of size 8 byte is too little to store 4 double value !!
-There might be some bit operation could solve the issue!!
Ex:
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
int main()
{
char str[8]={'\0'};
double x=-10.456678,p=12.678906,q=80.8956876,r=360.67,y,z,h,k;
sprintf(&str[0],"%2.6f",x);
sprintf(&str[1],"%2.6f",p);
sprintf(&str[2],"%2.6f",q);
sprintf(&str[3],%3.4f",r);
//Extracting the same from str
y=atof((char *)&str[0]);
z=atof((char *)&str[1]);
h=atof((char *)&str[2]);
k=atof((char *)&str[3]);
printf("\ny= %2.6f",y);
printf("\nz= %2.6f",z);
printf("\nh= %2.6f",h);
printf("\nk= %2.6f",k);
return 0;
}
Could anyone please answer
Thanks in Advance!!
| <c><string><bit-shift> | 2016-02-14 18:41:34 | LQ_EDIT |
35,397,289 | Code for "fizzbuzz" doesn't work properly, it only return "fizzbuzz" throught out the string as answer | Can someone please explain why the following code does not work properly? It only returns "fizzbuzz" 100 times as the answer. Thank you.
def fizzbuzz(number)
idx = 0
while idx <= number
num = number[idx]
if num % 3 == 0 && num % 5 == 0
puts 'fizzbuzz'
elsif num % 5 == 0
puts 'buzz'
elsif num % 3 == 0
puts 'fizz'
else puts num
end
idx += 1
end
end
fizzbuzz(100) | <ruby><fizzbuzz> | 2016-02-14 19:58:34 | LQ_EDIT |
35,397,356 | Is there a difference between malloc() and creating a variable and then using the & operator? | <p>In C, is there a difference between</p>
<pre><code>struct Foo foo;
struct Foo* fooPtr = &foo;
</code></pre>
<p>and</p>
<pre><code>struct Foo* fooPtr = (struct Foo*) malloc(sizeof(struct Foo));
</code></pre>
| <c> | 2016-02-14 20:05:47 | LQ_CLOSE |
35,399,144 | I'm trying to find the sum of each row, and then print them out from largest to smallest | `enter code here`import java.util.Arrays;
`enter code here`import java.util.Scanner;
`enter code here`import java.util.Collections;
`enter code here`public class array_PA3{
`enter code here`public static void main(String[] args){
`enter code here`int[][] hoursArray = {
`enter code here`{2,3,3,4,5,8,8,0},
`enter code here`{7,4,4,3,3,4,4,0},
`enter code here`{3,4,3,3,3,2,2,0},
`enter code here`{9,4,7,7,3,4,1,0},
`enter code here`{3,4,3,3,6,3,8,0},
`enter code here`{3,4,6,3,3,4,4,0},
`enter code here`{3,4,8,8,3,8,4,0},
`enter code here`{6,5,9,9,2,7,9,0}};
`enter code here`int maxRow = 0;
`enter code here`int indexRow = 0;
`enter code here`int [] totalRow = new int[8];
`enter code here`for (int row = 0; row <= 7; row++) {
`enter code here`for (int column = 0; column <= 7; column++){
`enter code here`totalRow[row] += hoursArray[row][column];
`enter code here`}
`enter code here`System.out.println("The sum of row " + row + " is " + totalRow[row] + ".");
`enter code here`}
`enter code here`Arrays.sort(totalRow, Collections.reverseOrder());
}
} | <java><multidimensional-array> | 2016-02-14 23:07:34 | LQ_EDIT |
35,399,462 | why my output is wronging this code? | Basically my code is to write a program that shows how many people uses a specific email provider based on input from the user I have csv file and every time i run the program prtints 0 this is my code:
user = input('Enter an email'):
c=0
f_in = open('us-500.csv','r')
f_in.readline()
for line in f_in:
line = line.strip(' ')
first, last, company, address, city, country, state, zip, phone1, phone2, email, web = line.split(',')
for count in email:
if count == user:
c +=1
print(c)
f_in.close()
| <python><csv><python-3.x> | 2016-02-14 23:44:10 | LQ_EDIT |
35,399,693 | Which of /usr/bin/perl or /usr/local/bin/perl should be used? | <p>If I have both <code>/usr/bin/perl</code> and <code>/usr/local/bin/perl</code> available on a system, which one should I use?</p>
| <perl><unix><executable> | 2016-02-15 00:17:22 | LQ_CLOSE |
35,399,840 | How you you assign the value of a char pointer to an integer | <p>Is there a way to assign the value of a char pointer to an integer</p>
| <c> | 2016-02-15 00:38:21 | LQ_CLOSE |
35,400,884 | xCode/Swift user input from textfield | I'm trying to create a class Course with properties such as setting a var to a string/int of user input from a textField. How would I implement this in swift? I was thinking it would be something along the lines of
`class Course {
let x = self.textFieldname.text!
}`
But I wind up with an error saying "Instance member can not be used on type ViewController.
I'm a noob to iOS and swift so any help is greatly appreciated. | <ios><swift> | 2016-02-15 03:06:38 | LQ_EDIT |
35,401,134 | cannot resolve method setcontentview(android.widget.TextView) | <p>How to setContentView in a fragment?
I having error with setContentView(tvv);
Any helps will be appreciated. </p>
<p><a href="http://i.stack.imgur.com/sGpxy.png" rel="nofollow">image</a></p>
<p>Continue</p>
<pre><code> Button btnBF = (Button) view.findViewById(R.id.btnBF);
btnBF.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(v.getContext(),SelectImage.class);
startActivityForResult(intent, 0);
}
});
return view;
}
}
</code></pre>
| <android><android-fragments> | 2016-02-15 03:39:22 | LQ_CLOSE |
35,401,482 | Looping through Arrays | I am trying to write a program to simulate an airline reservation system. I an supposed to use an array of type boolean to represent the number of seats. First five seats represent first class and last five represent economy. Initially the program must allow the user to make a choice between first class and economy and then his choice is processed as follows:
A user can only be assigned an empty seat in the class he chooses.
Once a class is full, the user is offered the option to move to the next class
If the user agrees to move to the next class a simple boarding pass is printed.
If the user refuses to move to the next class. The time for the next flight is displayed. i would appreciate help on how to loop through the elements of the array to determine whether its true of false. Also i am trying to display the number of seats available in each class before the user makes a selection this is what i've written so far.. My code is far from complete, i acknowledge that, i am a novice programmer please help. Thank you.
import java.util.Scanner;
public class AirlineReservation
{
private boolean[] seats =; // array to hold seating capacity
private String AirlineName; // name of airline
private int[] counter = new int[5]
// constructor to initialize name and seats
public Airline(String name, boolean[] capacity )
{
AirlineName = name;
seats = capacity;
} // end constructor
// method to set the Airline name
public void setName( String name )
{
AirlineName = name; // store the course name
} // end method setCourseName
// method to retreive the course name
public String getName()
{
return AirlineName;
} // end method getName
// display a welcome message to the Airline user
public void displayMessage()
{
// display welcome message to the user
System.out.printf("Welcome to the Self-Service menu for\n%s!\n\n",
getName() );
} // end method displayMessage
// processUserRequest
public void processUserRequest()
{
// output welcome message
displayMessage();
// call methods statusA and StatusB
System.out.printf("\n%s %d:\n%s %d:\n\n",
"Number of available seats in First class category is:", statusA(),
"Number of available seats in Economy is", statusB() );
// call method choice
choice();
// call method determine availability
availability();
// call method boarding pass
boardingPass();
} // end method processUserRequest
public int statusA()
{
for ( int counter = 0; counter <= (seats.length)/2; counter++ )
} // revisit method
// method to ask users choice
public String choice()
{
System.out.printf(" Enter 0 to select First Class or 1 to select Economy:")
Scanner input = new Scanner( System.in );
boolean choice = input.nextBoolean();
} // end method choice
// method to check availability of user request
public String availability()
{
if ( input == 0)
System.out.printf("You have been assigned seat number \t%d", seats[ counter ]);
else
System.out.printf("You have been assigned seat number \t%d", seats[ counter ]);
}
} | <java><arrays><loops> | 2016-02-15 04:26:22 | LQ_EDIT |
35,402,954 | Java Method Implementation | <p>I'm required to implement methods into a simple program to familiarize myself with them in Java.</p>
<p>My code so far is:</p>
<pre><code>import java.util.*;
public class Lab5a
{
public static void main(String args[])
{
double[] a = {1, 0, 0};
double[] b = {0, 1, 1};
double[] c = {1, 1, 1};
double[] d = {0, 0, 1};
double ab = Math.sqrt (
(a[0]-b[0])*(a[0]-b[0]) +
(a[1]-b[1])*(a[1]-b[1]) +
(a[2]-b[2])*(a[2]-b[2]) );
double ac = Math.sqrt (
(a[0]-c[0])*(a[0]-c[0]) +
(a[1]-c[1])*(a[1]-c[1]) +
(a[2]-c[2])*(a[2]-c[2]) );
double ad = Math.sqrt (
(a[0]-d[0])*(a[0]-d[0]) +
(a[1]-d[1])*(a[1]-d[1]) +
(a[2]-d[2])*(a[2]-d[2]) );
System.out.println("ab=" + ab + ", ac=" + ac + ", ad=" + ad);
}
}
</code></pre>
<p>And my instructions are to: </p>
<pre><code>Next, copy the class to Lab5b.java, and replace the individual distance calculations by calls to a single
public static method that computes the distance between two points passed in as parameters. Also, implement
the method. Your method should have a signature something like the following:
public static double distance(double[] a, double[] b)
</code></pre>
<p>I am very much new to Java and am struggling to understand what exactly the statement means.</p>
| <java><methods> | 2016-02-15 06:38:48 | LQ_CLOSE |
35,402,956 | How to send text to other user in same app | <p>Guys.. I am developing an app based on 20 questions concept. i need to send Question as text to other user and other user will respond to that Question in yes or No by pressing yes No button.. This must be online app and questions and answers history will be stored in database on server.. kindly help me i have no clue how to do this this is my final year project my whole degree depends on it.. any suggestions any API any builtin functions??</p>
<pre><code>broadcast()
</code></pre>
<p>will work or not?</p>
| <android> | 2016-02-15 06:39:01 | LQ_CLOSE |
35,404,269 | Generate random value at interval of 5 Sec in JavaScript | <p>Can anyone tell me how to generate random value between <code>0 and 100</code> in an interval of <code>5 seconds</code>.</p>
| <javascript><random><setinterval> | 2016-02-15 08:08:14 | LQ_CLOSE |
35,404,655 | Javascript global variable naming conflicts | <p>A newbie learning javascript :)</p>
<p>This is my html page and the associated js code</p>
<pre><code><!DOCTYPE html>
<html>
<head>
<title> A Basic Function </title>
<link rel="stylesheet" href="css/c03.css" />
</head>
<body>
<h1>Travelworth</h1>
<div id="message">Welcome to our site!</div>
<script src="js/basic-function.js"></script>
</body>
</html>
</code></pre>
<p><strong>basic-function.js</strong></p>
<pre><code>var msg="A New Message"; //Line 1
var msg="A Second Message";//Line 2
function updatemessage()
{
var e = document.getElementById('message');
e.textContent = msg;
}
updatemessage();
</code></pre>
<p><strong>Q1:-</strong></p>
<p>This webpage displays the message from the Line2 instead of Line1.</p>
<p>I am guessing this is because the "msg" variable declared in Line 2 is considered the "latest" and the interpreter has proceeded with that.</p>
<p>Is my assumption right ?</p>
<p><strong>Q2:-</strong></p>
<p>If that is the case, then there will be instances where a webpage may utilize multiple js files written by different people.</p>
<p>How the naming conflict will be handled on global variables between these two different js files referenced in the same webpage ?</p>
<p>Can someone explain ?</p>
| <javascript> | 2016-02-15 08:33:51 | LQ_CLOSE |
35,404,824 | i would like to know way to extract a particular substring from a regex in Jquery..here is my code | var patt1 =/[a-zA-Z\s]+:[a-zA-Z0-9\S]*/g;
this would extract the pattern string:someString
the "someString" is what i wish to extract i am aware that the slice() method could be used to do this, but I'm not entirely sure how to do this.
Any help would be greatly appreciated | <jquery><regex> | 2016-02-15 08:45:14 | LQ_EDIT |
35,405,313 | Adding a key-value pair in evelry json multi-dimensional array | I have a list of JSON objects and I want every object to be inserted by a certain key value. Please take note that it is an angularjs $scope. I'm aware that this can be done by
Here is the code:
$scope.Items = [
{name:'Jani',country:'Norway'},
{name:'Hege',country:'Sweden'},
{name:'Kai',country:'Denmark'},
];
But what I want is to make it from that to this:
$scope.Items = [
{name:'Jani',country:'Norway', edit:false},
{name:'Hege',country:'Sweden', edit:false},
{name:'Kai',country:'Denmark', edit:false},
]; | <javascript><arrays><angularjs> | 2016-02-15 09:12:31 | LQ_EDIT |
35,405,784 | How i return a search results in my page? | I have this search bar and I would like if someone can help me when I press the search button to look for keywords in a text file that you have on your computer and bring me the words are found back to the page ...i'm a beginner and do not really manage how to fix it ... if someone can show me how to do it in writing i would be grateful.
Search engine:
<form id="frmSearch" class="search1" method="get" action="default.html" />
<input class="search" id="txtSearch" type="text" name="search_bar" size="31" maxlength="255"
value=""
<style="left: 396px; top: 20000px; width: 293px; height: 60px;" />
Button:
<input class="search2" type="submit" name="submition" value="Cauta" style=" padding-
bottom:20px; left: 300px; top: 0px; height: 50px" />
<input class="search2" type="hidden" name="sitesearch" value="default.html" />
JS:
<script type="text/javascript">
document.getElementById('frmSearch').onsubmit = function() {
window.location = 'http://www.google.ro/search?q=' + document.getElementById('txtSearch').value;
}
</script>
| <javascript><html> | 2016-02-15 09:36:28 | LQ_EDIT |
35,406,766 | Change label value Using jQuery | This my first question,On My Form, i want change Color to Choose Color
<label for="ProductSelect-option-0">Color</label>
output will be
<label for="ProductSelect-option-0">Choose Color</label>
Without add class or ID. How possible to do with jQuery?
| <javascript><jquery><css><forms> | 2016-02-15 10:21:04 | LQ_EDIT |
35,407,274 | sql server sql queries to linq | How i write the linq queries for the following procedure!!!!!!
create proc [dbo].[sp_remainUser] @userid int as begin select * from userlog where user_id not in(select followed_id from userfollowing where follower_id=@userid) and user_id not in (select follower_id from userfollowing where follower_id=@userid) end | <sql><sql-server><linq> | 2016-02-15 10:45:09 | LQ_EDIT |
35,407,754 | Making some sort of n00b mistake here - "The name 'var' does not exist in the current context" | So I'm a beginner with c# experimenting with the Microsoft.Office.Interop.Excel reference, and I've ran into an issue. Here's my main form:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Microsoft.Office.Interop.Excel;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public void Form1_Load(object sender, EventArgs e)
{
var BankAccounts = new List<Account>
{
new Account
{
ID = 345,
Balance = 541.27
},
new Account
{
ID = 123,
Balance = -127.44
}
};
}
public void button1_Click(object sender, EventArgs e)
{
ThisAddIn.DisplayInExcel(BankAccounts, (Account, cell) =>
// This multiline lambda expression sets custom processing rules
// for the bankAccounts.
{
cell.Value = Account.ID;
cell.Offset[0, 1].Value = Account.Balance;
if (Account.Balance < 0)
{
cell.Interior.Color = 255;
cell.Offset[0, 1].Interior.Color = 255;
}
});
}
}
}
Returns the error:
> The name 'BankAccounts' does not exist in the current context
I can't understand how this is happening, could someone please help me fix this and perhaps explain what's caused it?
Thanks a lot!
| <c#><c#-4.0> | 2016-02-15 11:07:17 | LQ_EDIT |
35,408,494 | How to solve Non linear equation in R | <p>How to solve the equation ,y=x^a in R so that we get the optimize value for 'a'.
Here y and x are (n x 1) matrix and 'a' is unknown parameter.
How to solve this in R??</p>
| <r> | 2016-02-15 11:43:21 | LQ_CLOSE |
35,409,065 | object is not callablel web crawler | import requests
from bs4 import BeautifulSoup
def lolz(max_pages):
page = 1
while page <= max_pages:
url = 'https://www.thenewboston.com/search.php?type=1&sort=pop&page=' + str(page)
sorce_code = requests.get(url)
plain_text = sorce_code.text
soup = BeautifulSoup(plain_text)
for link in soup.findall('a',{'class' : 'item-name'}):
href = link.get('href')
print(href)
page += 1
lolz(1)
here is the code i keep geting error nonetype object is not callable | <python> | 2016-02-15 12:11:04 | LQ_EDIT |
35,409,096 | Find next item using Linq based on the last Index | I want to search for a string in a list of strings and get its index
List<string> list;
int index;
private void button1_Click(object sender, EventArgs e)
{
index = list.FindIndex(x => x.Contains(textBox1.Text));
if (index >= 0)
{
listView1.Items[index].Selected = true;
}
}
Now if the user hits the button another time, the index should be the next occurrence of the search item in the list. How can I do this based on the last index `index`? | <c#> | 2016-02-15 12:12:25 | LQ_EDIT |
35,410,990 | Is this a good approach to random byte array genaration in C? | I know this kind of question has been already discussed here: http://stackoverflow.com/questions/822323/how-to-generate-a-random-number-in-c
But I wanted to share the way I implemented it just to know what people may think about it.
#include <stdlib.h>
#include <string.h>
#include <sys/time.h>
#include <time.h>
long int getNanoSecs(){
struct timespec unixtimespec;
clock_gettime(CLOCK_REALTIME_COARSE, &unixtimespec);
return unixtimespec.tv_nsec;
}
.
.
.
unsigned char personal_final_token[PERSONAL_FINAL_TOKEN_SIZE_SIZE];
unsigned char pwd_ptr_ctr;
srandom(getNanoSecs()*(getNanoSecs()&0xFF));
for(pwd_ptr_ctr=0;pwd_ptr_ctr<PERSONAL_FINAL_TOKEN_SIZE_SIZE;pwd_ptr_ctr++){
memset(personal_final_token+pwd_ptr_ctr,(random()^getNanoSecs())&0xFF,1);
}
just define PERSONAL_FINAL_TOKEN_SIZE_SIZE and you can generate a quite random token of the size you want. | <c++><c><random> | 2016-02-15 13:45:31 | LQ_EDIT |
35,411,014 | How to check a condition in android alwaysly? | i want to develop an app to change device audio status , if that is silent change it with a button to Normal and so on.
i Want to check Audio Status of device in my app always and if device is silent change my button text to silent and if it was normal , change it to normal.
here is my only class :
public class MainActivity extends ActionBarActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Button btn1= (Button) findViewById(R.id.btn1);
final AudioManager audio = (AudioManager)getSystemService(Context.AUDIO_SERVICE);
if (audio.getRingerMode()==AudioManager.RINGER_MODE_NORMAL)
{
btn1.setText("Normal");
}
else if (audio.getRingerMode()==AudioManager.RINGER_MODE_SILENT)
{
btn1.setText("Silent");
}
btn1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
btn1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (audio.getRingerMode()==AudioManager.RINGER_MODE_NORMAL)
{
audio.setRingerMode(AudioManager.RINGER_MODE_SILENT);
btn1.setText("Silent");
}
else if (audio.getRingerMode()==AudioManager.RINGER_MODE_SILENT)
{
audio.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
btn1.setText("Normal");
}
}
});
}
});
how i can check this condition always in android ? | <java><android><audio><android-studio><silent> | 2016-02-15 13:46:34 | LQ_EDIT |
35,411,466 | Problems building a GUI which will compare algorithms | <p>I'm looking to build a GUI that will let the user randomly populate an array and then compare the time it takes to sort by bubble sort, insertion sort and selection sort. i have the code for the 3 algorithms but i'm struggling to put it all together and compare it using System.currentTimeMillis() </p>
| <java><algorithm><sorting><user-interface> | 2016-02-15 14:05:59 | LQ_CLOSE |
35,413,507 | java.lang.ClassCastException: java.lang.Integer cannot be cast to java.util.HashMap | <p>I have looked through numerous questions that are very similar to mine and have tried all the fixes that the other questions recommended to no avail. So I decided I'd post my own question in hopes that someone can help. </p>
<p>NewsActivity:</p>
<pre><code>import android.app.ActionBar;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.media.Image;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserFactory;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
public class NewsActivity extends Activity {
private String xmlData;
private ListView listView;
private ArrayList<News> allNews;
private Image newsImage;
public final static String ITEM_TITLE = "newsTitle";
public final static String ITEM_DATE = "newsDate";
public final static String ITEM_DESCRIPTION = "newsDescription";
public final static String ITEM_IMGURL = "newsImageURL";
public Map<String, ?> createItem(String title, String date, String url) {
Map<String,String> item = new HashMap<>();
item.put(ITEM_TITLE, title);
item.put(ITEM_DATE, date);
item.put(ITEM_IMGURL, url);
return item;
}
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ActionBar bar = getActionBar();
bar.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#f8f8f8")));
bar.setDisplayShowHomeEnabled(false);
bar.setDisplayShowTitleEnabled(true);
bar.setDisplayUseLogoEnabled(false);
bar.setTitle("News");
setContentView(R.layout.news_layout);
Bundle newsBundle = getIntent().getExtras();
xmlData = newsBundle.getString("xmlData");
final ArrayList<News> newsData = getNewsData(xmlData);
allNews = new ArrayList<News>();
List<Map<String, ?>> data = new LinkedList<Map<String, ?>>();
for(int i = 0; i < newsData.size(); i++) {
News currentNews = newsData.get(i);
String newsTitle = currentNews.getNewsTitle();
String newsDate = currentNews.getNewsDate();
String newsDescription = currentNews.getNewsDescription();
String newsImageURL = currentNews.getNewsImageUrl();
data.add(createItem(newsTitle, newsDate, newsImageURL));
allNews.add(currentNews);
}
listView = (ListView) findViewById(R.id.news_list);
LazyNewsAdapter adapter = new LazyNewsAdapter(this, newsData);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Map<String, String> item = (HashMap<String, String>) parent.getItemAtPosition(position); //**ERROR IS HERE: java.lang.ClassCastException: java.lang.Integer cannot be cast to java.util.HashMap** //
String title = item.get(ITEM_TITLE);
String url = item.get(ITEM_IMGURL);
String date = item.get(ITEM_DATE);
Iterator<News> itp = allNews.iterator();
News currentNews = null;
while (itp.hasNext()) {
currentNews = itp.next();
if (title == currentNews.getNewsTitle() && url == currentNews.getNewsImageUrl() && date == currentNews.getNewsDate())
break;
}
String newsTitle = currentNews.getNewsTitle();
String newsDescription = currentNews.getNewsDescription();
String newsUrl = currentNews.getNewsImageUrl();
String newsDate = currentNews.getNewsDate();
Intent detailnewsScreen = new Intent(getApplicationContext(), DetailNewsActivity.class);
detailnewsScreen.putExtra("newsTitle", newsTitle);
detailnewsScreen.putExtra("newsDescription", newsDescription);
detailnewsScreen.putExtra("url", newsUrl);
detailnewsScreen.putExtra("newsDate", newsDate);
startActivity(detailnewsScreen);
}
});
}
private ArrayList<News> getNewsData(String src) {
ArrayList<News> newsList = new ArrayList<>();
News currentNews = new News();
String newsTitle = new String();
String newsDate = new String();
String newsUrl = new String();
String newsDescription = new String();
try {
StringReader sr = new StringReader(src);
XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
factory.setNamespaceAware(true);
XmlPullParser xpp = factory.newPullParser();
xpp.setInput(sr);
int eventType = xpp.getEventType();
while (eventType != XmlPullParser.END_DOCUMENT) {
String name = null;
switch (eventType) {
case XmlPullParser.START_TAG:
name = xpp.getName();
if (name.equals("news")) {
currentNews = new News();
}
else if (name.equals("ntitle")) {
newsTitle = xpp.nextText();
newsTitle = newsTitle.trim();
}
else if (name.equals("ndate")) {
newsDate = xpp.nextText();
newsDate = newsDate.trim();
}
else if (name.equals("nimage")) {
newsUrl = xpp.nextText();
newsUrl = newsUrl.trim();
}
else if (name.equals("ndescription")) {
newsDescription = xpp.nextText();
newsDescription = newsDescription.trim();
}
break;
case XmlPullParser.END_TAG:
name = xpp.getName();
if (name.equals("news")) {
currentNews.setNewsTitle(newsTitle);
currentNews.setNewsDate(newsDate);
currentNews.setNewsImageUrl("http://www.branko-cirovic.appspot.com/iWeek/news/images/" + newsUrl);
currentNews.setNewsDescription(newsDescription);
newsList.add(currentNews);
}
break;
}
eventType = xpp.next();
}
}
catch (Exception e){
e.printStackTrace();
}
return newsList;
}
}
</code></pre>
<p>LazyNewsAdapter:</p>
<pre><code>import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.ArrayList;
public class LazyNewsAdapter extends BaseAdapter {
private Activity activity;
private ArrayList<News> listData;
private LayoutInflater inflater = null;
public LazyNewsAdapter(Activity activity, ArrayList<News> listData) {
this.activity = activity;
this.listData = listData;
inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public int getCount() {
return listData.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
News newsItem = listData.get(position);
View view = convertView;
if(convertView == null)
view = inflater.inflate(R.layout.news_cell, null);
TextView newsTitle = (TextView) view.findViewById(R.id.newsTitle);
TextView newsDate = (TextView) view.findViewById(R.id.newsDate);
ImageView image = (ImageView) view.findViewById(R.id.newsImage);
newsTitle.setText(newsItem.getNewsTitle());
newsDate.setText(newsItem.getNewsDate());
String url = newsItem.getNewsImageUrl();
ImageLoader imageLoader = new ImageLoader(activity, 600, R.mipmap.placeholder);
imageLoader.displayImage(url, image);
return view;
}
}
</code></pre>
<p>The error that I am getting has a comment next to it in the NewsActivity. It seems to be trying to cast an integer to a HashMap for some reason. I have multiple other classes that use this exact method and have no issue, but for this NewsActivity I am getting this error.</p>
<p>Any suggestions?</p>
<p>Thanks so much!</p>
| <java><android><hashmap><integer><classcastexception> | 2016-02-15 15:47:40 | LQ_CLOSE |
35,414,193 | implement C=|A-B| with inc,dec,jnz (A,B are none negative) | Its a question I saw in an interview :
A,B are none negative numbers and you need to return C=|A-B| where you have only the following instruction :
**Inc register** - adds one to **register**
**Dec register** - substracts one from **register**
**JNZ LABEL** - jumps to labael if last instruction result was not zero
In addition you can use other registers that their initial value is zero;
Thanks for your help | <assembly> | 2016-02-15 16:21:43 | LQ_EDIT |
35,415,469 | SQLite3 UNIQUE constraint failed error | <p>I am trying to create a database which allows users to create 'to do' lists and fill them with items to complete. However, when inserting data into the tables it gives me a UNIQUE constraint failed error and I don't know how to solve it. This is my code for creating the database and inserting data.</p>
<pre><code>CREATE TABLE user (
user_id integer NOT NULL PRIMARY KEY,
first_name varchar(15) NOT NULL,
title varchar(5) NOT NULL,
username varchar(15) NOT NULL,
password varchar(20) NOT NULL,
email varchar(50) NOT NULL,
bio text NOT NULL
);
CREATE TABLE list (
list_id integer NOT NULL PRIMARY KEY,
list_name varchar(10) NOT NULL,
user_user_id integer NOT NULL,
FOREIGN KEY (user_user_id) REFERENCES user(user_id)
);
CREATE TABLE item (
item_id integer NOT NULL PRIMARY KEY,
item text NOT NULL,
completed boolean NOT NULL,
list_list_id integer NOT NULL,
FOREIGN KEY (list_list_id) REFERENCES list(list_id)
);
-- Data:
INSERT INTO user VALUES (1, "Name1", "Title1", "Username1", "Password1", "Email1", "Bio1");
INSERT INTO user VALUES (2, "Name2", "Title2", "Username2", "Password2", "Email2", "Bio2");
INSERT INTO user VALUES (3, "Name3", "Title3", "Username3", "Password3", "Email3", "Bio3");
INSERT INTO list VALUES (1, "user1-list1", 1);
INSERT INTO list VALUES (2, "user1-list2", 1);
INSERT INTO list VALUES (3, "user1-list3", 1);
INSERT INTO list VALUES (1, "user2-list1", 2);
INSERT INTO list VALUES (1, "user3-list1", 3);
INSERT INTO list VALUES (2, "user3-list2", 3);
INSERT INTO item VALUES (1, "user1-list1-item1", "FALSE", 1);
INSERT INTO item VALUES (2, "user1-list1-item2", "FALSE", 1);
INSERT INTO item VALUES (1, "user1-list2-item1", "FALSE", 2);
INSERT INTO item VALUES (1, "user1-list3-item1", "FALSE", 3);
INSERT INTO item VALUES (2, "user1-list3-item2", "FALSE", 3);
INSERT INTO item VALUES (1, "user2-list1-item1", "FALSE", 1);
INSERT INTO item VALUES (2, "user2-list1-item1", "FALSE", 1);
INSERT INTO item VALUES (1, "user3-list1-item1", "FALSE", 1);
INSERT INTO item VALUES (1, "user3-list3-item1", "FALSE", 2);
</code></pre>
<p>I have copied the errors I receive below:</p>
<pre><code>Error: near line 43: UNIQUE constraint failed: list.list_id
Error: near line 44: UNIQUE constraint failed: list.list_id
Error: near line 45: UNIQUE constraint failed: list.list_id
Error: near line 49: UNIQUE constraint failed: item.item_id
Error: near line 50: UNIQUE constraint failed: item.item_id
Error: near line 51: UNIQUE constraint failed: item.item_id
Error: near line 52: UNIQUE constraint failed: item.item_id
Error: near line 53: UNIQUE constraint failed: item.item_id
Error: near line 54: UNIQUE constraint failed: item.item_id
Error: near line 55: UNIQUE constraint failed: item.item_id
</code></pre>
<p>Any help would be appreciated!</p>
| <sql><database><sqlite> | 2016-02-15 17:28:43 | HQ |
35,415,978 | Syntax: const {} = variableName, can anyone explain or point me into the right direction | <p>What does this syntax mean in JavaScript (ES6 probably):</p>
<p>const {} = variablename;</p>
<p>I'm currently trying to get a grip of React. In a lot of examples I came across that syntax. For example:</p>
<pre><code>const {girls, guys, women, men} = state;
</code></pre>
| <javascript><reactjs><ecmascript-6> | 2016-02-15 17:57:38 | HQ |
35,416,525 | How to correctly dismiss a UINavigationController that's presented as a modal? | <p>In my <code>TabBarViewController</code>, I create a UINavigationController and present it as a modal.</p>
<pre><code>var navController = UINavigationController()
let messageVC = self.storyboard?.instantiateViewControllerWithIdentifier("MessagesViewController") as! MessagesViewController
self.presentViewController(self.navController, animated: false, completion: nil)
self.navController.pushViewController(messageVC, animated: false)
</code></pre>
<p>Inside my <code>MessageViewController</code>, this is how I want to dismiss it:</p>
<pre><code>func swipedRightAndUserWantsToDismiss(){
if self == self.navigationController?.viewControllers[0] {
self.dismissViewControllerAnimated(true, completion: nil) //doesn't deinit
}else{
self.navigationController?.popViewControllerAnimated(true) //deinits correctly
}
}
deinit{
print("Deinit MessagesViewController")
}
</code></pre>
<p>The problem is that when I get to the root View Controller and try to dismiss both the child and the UINavigationController, my <code>MessagesViewController</code> deinit does not get called. Something's holding on to it -- most likely UINavigationController</p>
| <ios><objective-c><swift> | 2016-02-15 18:28:24 | HQ |
35,417,633 | Unable to view images in php | <p>I am unable to view images on my webserver in <code>php</code> and I keep getting <code>server 500</code> error.</p>
<p>I believe that it is this line of code <code>echo "<img src='$row["sourchPath"]'>"</code>:</p>
<pre><code>while ($row = mysqli_fetch_assoc($result)){
if($row){
echo $row["sourchPath"]; // this works
echo "<img src='$row["sourchPath"]'>";
}
else {
echo "error";
}
}
</code></pre>
<p>My file directory is like <code>images/football.jpg</code></p>
| <php><html><mysql> | 2016-02-15 19:35:58 | LQ_CLOSE |
35,417,674 | PHP mysqli query wrong result | <p>I am using the following script to get joindate of the account: </p>
<pre><code>$date = mysqli_query($conn,"SELECT joindate from account where id = 6");
</code></pre>
<p>The result of that query should be 2016-01-30 00:00:00 but when i use</p>
<pre><code>print_r($date);
</code></pre>
<p>i get only </p>
<pre><code>mysqli_result Object ( [current_field] => 0 [field_count] => 1 [lengths] => [num_rows] => 1 [type] => 0 )
</code></pre>
| <php><mysql> | 2016-02-15 19:38:14 | LQ_CLOSE |
35,418,076 | Atom setting to open files in the same window? | <p>I'm just trying out Atom for the first time and I find it bothersome that Atom keeps opening a new window for each file I click on - I'd prefer that it defaulted to opening each file in the same window.</p>
<p>I'm hoping for something along the lines of <code>"open_files_in_new_window" : false,</code> in Sublime. Unfortunately, all the google results I'm seeing just lament that this toggle is not immediately obvious.</p>
| <configuration><atom-editor> | 2016-02-15 20:05:16 | HQ |
35,418,759 | npm WARN deprecated npmconf@2.1.2: this package has been reintegrated into npm and is now out of date with respect to npm | <p>I am installing node.js on a CentOS 7 server, and am getting the following error when I try to install yeoman: </p>
<pre><code>npm WARN deprecated npmconf@2.1.2: this package has been
reintegrated into npm and is now out of date with respect to npm
</code></pre>
<p>The install of yeoman seems to otherwise work correctly. Is there something that I can do to avoid this warning? What are the implications of leaving it unhandled? </p>
<p>Here is the rest of the first part of the terminal output from the yeoman install: </p>
<pre><code>[root@localhost ~]# npm install -g yo
npm WARN deprecated npmconf@2.1.2: this package has been reintegrated into npm and is now out of date with respect to npm
/usr/bin/yo -> /usr/lib/node_modules/yo/lib/cli.js
> yo@1.6.0 postinstall /usr/lib/node_modules/yo
> yodoctor
Yeoman Doctor
Running sanity checks on your system
✔ Global configuration file is valid
✔ NODE_PATH matches the npm root
✔ Node.js version
✔ No .bowerrc file in home directory
✔ No .yo-rc.json file in home directory
✔ npm version
Everything looks all right!
/usr/lib
.... many lines of directory structure follow
</code></pre>
| <javascript><node.js><yeoman> | 2016-02-15 20:46:18 | HQ |
35,418,798 | Google Cloud API - Application Default Credentials | <p>I have the following code, modified from <a href="https://developers.google.com/identity/protocols/application-default-credentials" rel="noreferrer">Google's documentation</a>:</p>
<pre><code> $GOOGLE_APPLICATION_CREDENTIALS = "./[path].json";
$_ENV["GOOGLE_APPLICATION_CREDENTIALS"] = "./[path].json";
$_SERVER["GOOGLE_APPLICATION_CREDENTIALS"] = "./[path].json";
$projectId = "[my project's ID']";
$client = new Google_Client();
$client->useApplicationDefaultCredentials();
$client->setScopes(['https://www.googleapis.com/auth/books']);
$service = new Google_Service_Books($client);
$results = $service->volumes->listVolumes('Henry David Thoreau');
</code></pre>
<p>Yet when I run it it returns the error:</p>
<pre><code>PHP Fatal error: Uncaught exception 'DomainException' with message 'Could not load the default credentials. Browse to https://developers.google.com/accounts/docs/application-default-credentials for more information'
</code></pre>
<p>I have tried various configurations, for example changing the path of the file. As you see, I've also done the three different forms of variables that I could immediately think of (two environment, one not).</p>
<p>I'm not quite sure where to look next. Should I look into different ways of setting the environment variable or should I define the path in a different way? What are the correct ways of doing this? Is there any other reason for the error?</p>
| <php><google-api><google-cloud-platform><google-api-php-client> | 2016-02-15 20:48:37 | HQ |
35,418,902 | Search form slow show [html] | <p>Anyone can help me create search form like this:</p>
<pre><code>http://gledanjefilmova.net/
</code></pre>
<p>I know there is some elements in css but I forgot which was...</p>
| <html><css> | 2016-02-15 20:55:20 | LQ_CLOSE |
35,419,036 | How to call strings inside a list in Python | <p>So, I'm making a chat bot, and I want to enable it so if the user inputs a word/phrase thats in the dictionary (a pickled file), it will reply with a suitable message to what the user input. It might make more sense if you see the code:</p>
<pre><code>""" startup """
import pickle
'''opening the dictionary'''
inFile = open('words.txt', 'rb')
dictionary = pickle.load(inFile)
'''printing the dictionary'''
print("PRE TESTS...")
print("-")
print("Pickle protocol import:")
print(dictionary)
print("END OF PRE TESTS...")
print("-")
print(" ")
""" end of startup """
print("Hello! My name is Pinnochio. I'm currently very young, and my communication is extremely limited.")
print("-")
''' handling the replies '''
reply = input()
if reply != dictionary:
print("Sorry, I don't know that word.")
reply = input()
if reply == dictionary[0] | dictionary[1] | dictionary[2]:
print("Hey there")
reply = input()
if reply == dictionary[3]:
print("I'm feeling great!")
reply = input()
if reply == dictionary[4] | dictionary[5]:
print("It is, isn't it?")
reply = input()
</code></pre>
<p>The dictionary is a list inside another file, which I've pickled:</p>
<pre><code>import pickle
dictionary = ["hello", "hi", "hey", "how are you?", "good morning", "good afternoon"]
outFile = open('words.txt', 'wb')
pickle.dump(dictionary, outFile)
outFile.close()
</code></pre>
<p>Thanks in advance!</p>
| <python> | 2016-02-15 21:03:29 | LQ_CLOSE |
35,419,985 | How to programmatically scroll to the bottom of a Recycler View? | <p>I want to scroll to the bottom of a recycler view on click of a button, how do I do this?</p>
| <android><android-layout><android-recyclerview> | 2016-02-15 22:07:06 | HQ |
35,420,997 | Possible to include HTML within php define()? | I want to know if it is possible to include HTML code within PHP define().
I use define() for emailing purposes. I use it to send a verification email to users who register on the site, however, instead of a plain, old boring text, I want to know if it would be possible to include HTML elements, such as headers, images etc..
Here's my current code:
define("EMAIL_VERIFICATION_CONTENT", "Activate your account by clicking the link below");
So the above code includes the email content with simply just text. I wish to add images, headers and colors into the email etc.
Any help and guidance would be great.
Thank you! | <php><html> | 2016-02-15 23:27:17 | LQ_EDIT |
35,421,935 | What are the platforms in the .NET Platform Standard? | <p>Currently trying to learn about the .NET Platform Standard I've found myself quite confused about the idea of "different platforms". </p>
<p>I'll try to make my point clear. What I currently now about the .NET Framework is that .NET is roughly speaking made up of the CLR, the BCL and supporting software to boot the CLR and provide the interface between the virtual machine and the underlying OS.</p>
<p>So when we code using the .NET Framework we indeed target some version of the framework because the types we are using from the BCL come with the framework and so depend on the specific version.</p>
<p>Now, .NET Core is quite different as I understood. It is not all packed together like that. We have the CoreCLR which is a lightweight VM to run the IL, the CoreFX which are the libraries properly organized as NuGet packages and we had up to now the DNX/DNVM/DNU which provided the supporting stuff like booting the CoreCLR and interfacing with the OS.</p>
<p>Anyway, despite if we install the framework on Windows 7, Windows 8 or Windows 10, we code <em>against the framework</em>.</p>
<p>Now, on the .NET Platform Standard spec we see the following definition:</p>
<blockquote>
<p>Platform - e.g. .NET Framework 4.5, .NET Framework 4.6, Windows Phone 8.1, MonoTouch, UWP, etc.</p>
</blockquote>
<p>Also we see after that a list of platforms, which includes </p>
<ul>
<li>.NET Framework 2.0 - 4.6</li>
<li>Windows 8</li>
<li>Windows Phone 8.1</li>
<li>Silverlight 4, 5</li>
<li>DNX on .NET Framework 4.5.1 - 4.6</li>
<li>DNX on .NET Core 5.0</li>
</ul>
<p>Now this confuses me completely. I always though: we code against the .NET Framework and the framework is the framework no matter what. </p>
<p>But here we have these platforms which includes the .NET framework as just <em>one of many platforms</em>. We have for example Windows 8, but wait a minute, running .NET on Windows 8 is not just the same thing as running .NET on any other OS? Why it is separate from the .NET Framework 2.0 - 4.6 platform?</p>
<p>We also have DNX as a specific platform. This makes me wonder: the platform is that "supporting stuff" related to booting the Virtual Machine and providing the interface with the OS? Or the platform includes the Virtual Machine?</p>
<p>Anyway, as can be seen I'm quite confused. What are those platforms indeed and how this relates to my current understanding of the .NET Framework? Also, why .NET Framework 2.0 - 4.6 is described separetely? Isn't <em>everything</em> described here some version of .NET Framework unless .NET Core?</p>
| <c#><.net><windows><dnx><.net-core> | 2016-02-16 01:06:52 | HQ |
35,421,942 | temp += {expression}; vs temp = {expression}; sum += temp; | I just finished spending ~4hours debugging an issue I had with a larger program, and even after fixing it, I still can't figure out why it was causing an issue.
Here's the mini version of the code:
#include <cstdlib>
#include<iostream>
#include <math.h>
#define PI 3.1415926535897932384626433832795 // the value of PI
void calculate_idct(double input_data[8][8], double out64[8][8], double fcosine[8][8]){
double temp;
for (int x=0;x<8;x++){
for (int y=0;y<8;y++){
temp = 0.0;
for (int u=0;u<8;u++){
for (int v=0;v<8;v++){
temp += input_data[u][v] * fcosine[x][u] * fcosine[y][v];
if (u == 0){
temp /= (double) sqrt(2);
}
if (v==0){
temp /= (double) sqrt(2);
}
}
}
out64[x][y] = temp/4;
}
}
}
///THE WORKING ONE
void calculate_idct2(double input[8][8], double out[8][8], double fcosine[8][8]){
double temp, sum;
for (int x =0;x<8;x++){
for (int y=0;y<8;y++){
sum = 0;
for (int u=0;u<8;u++){
for (int v=0;v<8;v++){
temp = input[u][v] * fcosine[x][u] * fcosine[y][v];
//I don't get it at all, but making the above line a
// += gives the wrong result
if (!u){
temp /= (double) sqrt(2);
}
if (!v){
temp /= (double) sqrt(2);
}
sum +=temp;
}
}
out[x][y] = (sum/4);
}
}
}
void calculate_dct(double input_data[8][8], double out64[8][8], double fcosine[8][8]) {
unsigned char u, v, x, y;
double temp;
// do forward discrete cosine transform
for (u = 0; u < 8; u++)
for (v = 0; v < 8; v++) {
temp = 0.0;
for (x = 0; x < 8; x++)
for (y = 0; y < 8; y++)
temp += input_data[x][y] * fcosine[x][u] * fcosine[y][v];
if ((u == 0) && (v == 0))
temp /= 8.0;
else if (((u == 0) && (v != 0)) || ((u != 0) && (v == 0)))
temp /= (4.0*sqrt(2.0));
else
temp /= 4.0;
out64[u][v] = temp;
}
}
void make_cosine_tbl(double cosine[8][8]) {
// calculate the cosine table as defined in the formula
for (unsigned char i = 0; i < 8; i++)
for (unsigned char j = 0; j < 8; j++)
cosine[i][j] = cos((((2*i)+1)*j*PI)/16);
}
using namespace std;
int main(int argc, char** argv) {
double cosine[8][8];
make_cosine_tbl(cosine);
double input_data[8][8] = {{255, 0, 255, 0, 255, 0, 255, 0},
{0, 255, 0, 255, 0, 255, 0, 255},
{255, 0, 255, 0, 255, 0, 255, 0},
{0, 255, 0, 255, 0, 255, 0, 255},
{255, 0, 255, 0, 255, 0, 255, 0},
{0, 255, 0, 255, 0, 255, 0, 255},
{255, 0, 255, 0, 255, 0, 255, 0},
{0, 255, 0, 255, 0, 255, 0, 255} };
double out64[8][8];
calculate_dct(input_data, out64, cosine);
double out5[8][8];
cout << "Input" << endl;
for (int i = 0;i<8;i++){
for (int j=0;j<8;j++){
cout << input_data[i][j] << " ";
}
cout << endl;
}
cout << "\n Version 1 \n " << endl;
calculate_idct(out64,out5,cosine);
for (int i = 0;i<8;i++){
for (int j=0;j<8;j++){
cout << out5[i][j] << " ";
}
cout << endl;
}
cout << "\n Version 2 \n " << endl;
calculate_idct2(out64,out5,cosine);
for (int i = 0;i<8;i++){
for (int j=0;j<8;j++){
cout << out5[i][j] << " ";
}
cout << endl;
}
}
Here's the output:
Version 1
60.7617 -58.7695 60.7617 -58.7695 60.7617 -58.7695 60.7617 -58.7695
-116.404 118.396 -116.404 118.396 -116.404 118.396 -116.404 118.396
135.3 -133.308 135.3 -133.308 135.3 -133.308 135.3 -133.308
-139.93 141.922 -139.93 141.922 -139.93 141.922 -139.93 141.922
141.922 -139.93 141.922 -139.93 141.922 -139.93 141.922 -139.93
-133.308 135.3 -133.308 135.3 -133.308 135.3 -133.308 135.3
118.396 -116.404 118.396 -116.404 118.396 -116.404 118.396 -116.404
-58.7695 60.7617 -58.7695 60.7617 -58.7695 60.7617 -58.7695 60.7617
Version 2
255 -1.42109e-14 255 -7.10543e-15 255 2.13163e-14 255 -7.10543e-14
3.55271e-15 255 -1.13687e-13 255 -9.9476e-14 255 1.7053e-13 255
255 -5.68434e-14 255 0 255 -2.84217e-14 255 -1.91847e-13
6.39488e-14 255 0 255 -5.68434e-14 255 1.56319e-13 255
255 -5.68434e-14 255 -5.68434e-14 255 -2.84217e-14 255 -1.27898e-13
7.10543e-15 255 0 255 0 255 2.13163e-13 255
255 2.98428e-13 255 2.55795e-13 255 2.13163e-13 255 1.52767e-13
3.55271e-15 255 -4.9738e-14 255 -2.84217e-14 255 1.74083e-13 255
Version 2 is right, but Version 1 is no where close to being correct.
I got the program working, but I am curiosity as to why there was such a big difference. This was for a school assignment, and fdct was given to us.
| <c++><dct> | 2016-02-16 01:07:49 | LQ_EDIT |
35,422,331 | how to calculate circumference when given the diameter | I have to write a code that will give me the circumference when I am given the diameter of 2 meters
My code is written like this:
Sub WorksheetFunctionDemo3()
Debug.Print WorksheetFunction. Pi(2)
End sub
but it is coming up with an error. I know without the (2) it'll give me the value of pi, but i can't figure out how to multiply it by 2 | <vba><excel> | 2016-02-16 01:56:43 | LQ_EDIT |
35,422,819 | SQLSTATE[HY093]: All parameters are filled properly and the syntax is right, so what's wrong? | I am getting the following error and I can't figure out just why:
`SQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number of tokens in`
Here's the code:
$transactions_sql = "INSERT INTO transactions (usr, service, txn_id, orig_amount, currency, date, description, fee_amt,
fee_currency, fee_descr, fee_type, net_amt, status) VALUES ";
$transactions_sql_data = array_fill(0, count($transactions) - 1, "(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
$transactions_sql .= implode(",", $transactions_sql_data);
$stmt = $conn->prepare($transactions_sql);
foreach ($transactions["data"] as $tr) {
$stmt->bindValue(1, $id, PDO::PARAM_INT);
$stmt->bindValue(2, tr["service"], PDO::PARAM_STR);
$stmt->bindValue(3, $tr["id"], PDO::PARAM_INT);
$stmt->bindValue(4, $tr["amount"], PDO::PARAM_INT);
$stmt->bindValue(5, $tr["currency"], PDO::PARAM_STR);
$stmt->bindValue(6, $tr["created"], PDO::PARAM_STR);
$stmt->bindValue(7, $tr["description"], PDO::PARAM_STR);
$stmt->bindValue(8, $tr["fee_details"][0]["amount"], PDO::PARAM_INT);
$stmt->bindValue(9, $tr["fee_details"][0]["currency"], PDO::PARAM_STR);
$stmt->bindValue(10, $tr["fee_details"][0]["description"], PDO::PARAM_STR);
$stmt->bindValue(11, $tr["fee_details"][0]["type"], PDO::PARAM_STR);
$stmt->bindValue(12, $tr["net"], PDO::PARAM_INT);
$stmt->bindValue(13, $tr["status"], PDO::PARAM_STR);
}
$stmt->execute();
Doing `var_dump($transactions_sql)` prints `"INSERT INTO balance_transactions (usr, service, txn_id, orig_amount, currency, date, description, fee_amt, fee_currency, fee_descr, fee_type, net_amt, status) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?),(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?),(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"`, which is correct (in terms of number of question marks - there will only be three arrays inside the `$tr` array).
So what's wrong here?
**EDIT: If you're going to down vote, then please tell me what's wrong. Down voting and just leaving doesn't help me or any future reader.** | <php><mysql> | 2016-02-16 02:53:40 | LQ_EDIT |
35,423,133 | Even, Odd with min and max for the Odd only | <p>Prompt the user to enter the size of an array and allow the user to
input integer values to your array. Check each element if it is even
or odd. If even, print solved elemets (ascending order), If odd, get
the max and min using conditional statement. Output the result.</p>
<pre><code>public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter a number: ");
int n = sc.nextInt();
int s[] = new int[n];
for (int i = 0; i < n; i++) {
int e = sc.nextInt();
s[i] = e;
}
Arrays.sort(s);
System.out.println("\nEven numbers in ascending order:");
for (int j = 0; j < n; j++) {
if (s[j] % 2 == 0) {
System.out.print(s[j] + " ");
}
}
System.out.println("\nOdd numbers in descending order:");
for(int j = (n -1); j >= 0; j--) {
if (s[j] % 2 == 1) {
System.out.print(s[j] + " ");
}
}
}
</code></pre>
<p>I don't know how to add min/max for the Odd</p>
| <java> | 2016-02-16 03:26:35 | LQ_CLOSE |
35,424,819 | What are the ways available for getting Database from SQL and display it in web page? | <ol>
<li>I know JSP,PHP and ASP.Net are there apart from these what are the
ways are there to get data from database. </li>
<li>It is possible by using J query,Bootstrap and Angular JS. If any
other way means suggest.</li>
</ol>
| <jquery><html><angularjs><twitter-bootstrap> | 2016-02-16 05:54:35 | LQ_CLOSE |
35,425,215 | android Push notifications with Google Cloud Messaging Service | I am new in android development.I have to work on android GCM push notification. Am search lots of tutorials and videos but no one is helpful for me.I have to implement GCM in client project its urgent.
Anyone help me to understand and how to work with GCM ? | <android><push-notification><google-cloud-messaging><android-notifications><android-developer-api> | 2016-02-16 06:21:59 | LQ_EDIT |
35,425,609 | List.contains() fails while .equals() works | <p>I have an <code>ArrayList</code> of <code>Test</code> objects, which use a string as the equivalency check. I want to be able to use <code>List.contains()</code> to check whether or not the list contains an object that uses a certain string.</p>
<p>Simply:</p>
<pre><code>Test a = new Test("a");
a.equals("a"); // True
List<Test> test = new ArrayList<Test>();
test.add(a);
test.contains("a"); // False!
</code></pre>
<p>Equals and Hash function:</p>
<pre><code>@Override
public boolean equals(Object o) {
if (o == null) return false;
if (o == this) return true;
if (!(o instanceof Test)) {
return (o instanceof String) && (name.equals(o));
}
Test t = (Test)o;
return name.equals(t.GetName());
}
@Override
public int hashCode() {
return name.hashCode();
}
</code></pre>
<p>I read that to make sure <code>contains</code> works for a custom class, it needs to override <code>equals</code>. Thus it's super strange to me that while <code>equals</code> returns true, <code>contains</code> returns false.</p>
<p>How can I make this work?</p>
<p><a href="http://ideone.com/sXC06t">Full code</a></p>
| <java><list><equals><contains> | 2016-02-16 06:47:45 | HQ |
35,425,753 | Exctracting a substring in iOS | I have a string like this: "/Myapp/auth/hrHeadcount+ME+All IOU+Headcount+Grade" and I want to save only the "HeadCount" in another string. How can I do that? | <ios><objective-c><nsstring><substring> | 2016-02-16 06:56:35 | LQ_EDIT |
35,426,169 | How to implement slider menu in react Native | <p>I'm new to react.
I need to develop slider menu in React-native.
I follow below link but that is not I want
<a href="http://www.reactnative.com/a-slide-menu-inspired-from-android-for-react-native/">http://www.reactnative.com/a-slide-menu-inspired-from-android-for-react-native/</a></p>
<p>Actually I need image which I attached here.</p>
<p><a href="https://i.stack.imgur.com/qrMZ7.png"><img src="https://i.stack.imgur.com/qrMZ7.png" alt="enter image description here"></a></p>
<p>Please help me..</p>
| <ios><facebook><reactjs><react-native> | 2016-02-16 07:19:49 | HQ |
35,426,275 | how to access database stored in array, specially particular rows and column | I am using laraval5.1 . i have stored by database table in array. Now i dont know how to access that array by rows or column.. how to get get particular data from array which is required by me from array.
please tell me how to do that.
$silver_plans = array();
$silver_plans = DB::select('select * from ins_gold ');
// print_r($silver_plans[0]);
// print_r($silver_plans['0']['age_band']);
this is code which is applied by me. i tried to access 'age_column'. | <php><mysql><arrays><arraylist><multidimensional-array> | 2016-02-16 07:25:22 | LQ_EDIT |
35,426,809 | how to set a value with span tag capyabara | Does anyone know how to set a value to span tag?
I tried using element.set or element.send_keys, they only selected the targeted element without modifing the previous value
<div data-offset-key="bbpvo-0-0" class="_1mf _1mj"><span data-offset-key="bbpvo-0-0"><span data-text="true">aa</span></span></div>
html snippet as above, I want to set aa to bb. can anyone help me out? thanks | <ruby><capybara> | 2016-02-16 07:56:04 | LQ_EDIT |
35,426,927 | i want to add non database field in a form in ORACLE APEX | i have a department table and it contains Employee information what i need is i want to add text fields(non-database) and performs and calculation tasks using stored procedures can anyone help me at this[i want to add text fields here][1]
[1]: http://i.stack.imgur.com/wJ194.jpg | <stored-procedures><plsql><oracle-apex> | 2016-02-16 08:03:48 | LQ_EDIT |
35,427,298 | finding streaks in pandas dataframe | <p>I have a pandas dataframe as follows:</p>
<pre><code>time winner loser stat
1 A B 0
2 C B 0
3 D B 1
4 E B 0
5 F A 0
6 G A 0
7 H A 0
8 I A 1
</code></pre>
<p>each row is a match result. the first column is the time of the match, second and third column contain winner/loser and the fourth column is one stat from the match.</p>
<p>I want to detect streaks of zeros for this stat per loser.</p>
<p>The expected result should look like this:</p>
<pre><code>time winner loser stat streak
1 A B 0 1
2 C B 0 2
3 D B 1 0
4 E B 0 1
5 F A 0 1
6 G A 0 2
7 H A 0 3
8 I A 1 0
</code></pre>
<p>In pseudocode the algorithm should work like this:</p>
<ul>
<li><code>.groupby</code> <code>loser</code> column. </li>
<li>then iterate over each row of each <code>loser</code> group</li>
<li>in each row, look at the <code>stat</code> column: if it contains <code>0</code>, then increment the <code>streak</code> value from the previous row by <code>0</code>. if it is not <code>0</code>, then start a new <code>streak</code>, that is, put <code>0</code> into the <code>streak</code> column.</li>
</ul>
<p>So the <code>.groupby</code> is clear. But then I would need some sort of <code>.apply</code> where I can look at the previous row? this is where I am stuck.</p>
| <python><pandas><dataframe> | 2016-02-16 08:24:08 | HQ |
35,427,784 | RAD STUDIO как установить TClientSocket и TServerSocket под мультиплатформу c++? | RAD STUDIO как установить TClientSocket и TServerSocket под мультиплатформу c++ ? Следовал инструкциям с официального сайта, поставилось вроде, но компоненты появляются только при создании VLC проекта, а мне нужно на C++ и под мультиплатформу.. | <c++><c++builder><multiplatform> | 2016-02-16 08:49:17 | LQ_EDIT |
35,427,815 | using cuda atomicAdd to port this peice of code | this is my sequential code:
float foo(float* in1, float* in2, float in3, unsigned int size) {
float tmp = 0.f;
for (int i = 0; i<size; i++)
if(in2[i]>0)tmp += (in1[i]/in3 - (in2[i] /in3)*(in2[i] /in3));
return tmp;
}
this is my effort for port it to cuda:
__global__ void kernel_foo(float* tmp, const float* in1, const float*
in2, float in3, unsigned int size) {
unsigned int i = blockDim.x * blockIdx.x + threadIdx.x;
if (i < size) {
if(in2[i]>0){
atomicAdd(tmp, in1[i]/in3 - (in2[i] /in3)*(in2[i] /in3));
}
}
}
void launch_kernel_foo(float* tmp, const float* in1, const float* in2,
float in3, unsigned int size) {
kernel_foo<<<(size+255)/256,256>>>(tmp, in1, in2, in3, size);
}
but it does't work, could anyone tell me where is wrong? thank you
| <cuda> | 2016-02-16 08:50:37 | LQ_EDIT |
35,427,996 | Long, single line ES6 string literal | <p>The google is full of blog posts and answers to question how one should benefit from ES6 string literals. And almost every blog post explaining this feature in depth has some details on how to implement multiline strings:</p>
<pre><code>let a = `foo
bar`;
</code></pre>
<p>But i can not find any details on how to implement long single line strings like the following:</p>
<pre><code>let a = `This is a very long single line string which might be used to display assertion messages or some text. It has much more than 80 symbols so it would take more then one screen in your text editor to view it. Hello ${world}`
</code></pre>
<p>Any clues or workarounds or should a one stick to the es3 strings instead?</p>
| <javascript><ecmascript-6> | 2016-02-16 09:01:11 | HQ |
35,428,177 | CODEIGNITER email | Iam trying to send email using codeigniter is there anyway I can send message in any email for example gmail, yahoo, or outlook .com so, this is what i have:
public function sendmail()
{
$config['protocol'] = 'sendmail';
$config['mailpath'] = '/usr/sbin/sendmail';
$config['charset'] = 'iso-8859-1';
$config['wordwrap'] = TRUE;
$this->load->library('email',$config); // load email library
$this->email->set_newline ("\r\n");
$this->email->from('user@gmail.com', 'sender name');
$this->email->to('test@gmail.com');
$this->email->subject('Your Subject');
$this->email->message('ed wow sir');
if ($this->email->send())
echo "nasend na!";
else
echo $this->email->print_debugger();
}
and it shows error :
Exit status code: 1
Unable to open a socket to Sendmail. Please check settings.
Unable to send email using PHP Sendmail. Your server might not be configured to send mail using this method. | <php><codeigniter><email> | 2016-02-16 09:09:10 | LQ_EDIT |
35,428,646 | What is <String> called? | I am new to Java and saw them several times. The last time within this code example:
List<String> myList = Arrays.asList("element1","element2","element3");
Now I want to know what this `<String>` or the <> signs is doing. Or especially what it is called so that I can search for it. All searches I have done before leading to operators. So can someone tell my how this is called or give me an example? Is the code above the same like this?
String letters = new List(Arrays.asList("element1", "element2", "element3"));
(Not tested, just thinking about) | <java> | 2016-02-16 09:31:46 | LQ_EDIT |
35,429,321 | TRIGGER AFTER INSERT USING THE TABLE INSERTION | I have an issue with a trigger after inserting, here is the trigger I made :
create or replace TRIGGER TRG_OPERATION_CARTE
AFTER INSERT OR UPDATE ON Operation
FOR EACH ROW
DECLARE
solde NUMBER := 0;
ouvert NUMBER := 0;
essai NUMBER := 0;
code NUMBER := 0;
plafondActuel NUMBER := 0;
decouvertAuth NUMBER := 0;
BEGIN
SELECT SUM(montant) INTO plafondActuel FROM Operation WHERE dateoperation >= SYSDATE - 7 AND ncompte = :NEW.ncompte;
SELECT plafond INTO decouvertAuth FROM Client Cl LEFT JOIN Compte Cp ON Cl.nclient = Cp.nclient WHERE Cp.ncompte = :NEW.ncompte;
SELECT solde, ouvert, nbessais, code
INTO solde, ouvert, essai, code
FROM Compte
WHERE Compte.ncompte = :NEW.ncompte;
IF ouvert = 0 THEN
INSERT INTO Incident (message,noperation) values ('Compte bloqué',:NEW.noperation);
ELSE
IF :NEW.codepropose = code THEN
IF (solde + decouvertAuth) > :NEW.montant THEN
IF (plafondActuel + :NEW.montant) > 300 THEN
INSERT INTO Incident (message,noperation) values ('Lopération dépasse le plafond authorisé',:NEW.noperation);
ELSE
INSERT INTO Historique (montant,ncompte) values (:NEW.montant,:NEW.ncompte);
END IF;
ELSE
INSERT INTO Incident (message,noperation) values ('Lopération dépasse le découvert authorisé',:NEW.noperation);
END IF;
ELSE
essai := essai + 1;
UPDATE Compte SET nbessais = essai WHERE Compte.ncompte = :NEW.ncompte;
IF essai >=3 THEN
UPDATE Compte SET ouvert = 0 WHERE Compte.ncompte = :NEW.ncompte;
INSERT INTO Incident (message,noperation) values ('Compte bloqué, 3 tentatives échouées',:NEW.noperation);
END IF;
END IF;
END IF;
END;
I am pretty sure that the algorithm and the Trigger are correct but I have an error :
***Cause: A trigger (or a user defined plsql function that is referenced in this statement) attempted to look at (or modify) a table that was in the middle of being modified by the statement which fired it.**
***Action: Rewrite the trigger (or function) so it does not read that table.**
Here is the code for the tables :
CREATE TABLE Client(
nclient INT NOT NULL,
nom VARCHAR(45) NOT NULL UNIQUE,
plafond NUMERIC(10,2) DEFAULT 0,
CHECK (plafond>=0),
CONSTRAINT PK_Client PRIMARY KEY (nclient)
);
CREATE TABLE Compte(
ncompte INT NOT NULL,
solde NUMERIC(10,2),
ouvert NUMERIC(1) DEFAULT 1,
nbessais INT,
code Numeric(4),
nclient NUMERIC(4),
CONSTRAINT PK_Compte PRIMARY KEY (ncompte),
CONSTRAINT FK_Compte_nclient_Client FOREIGN KEY (nclient) REFERENCES Client(nclient),
CONSTRAINT CK_solde CHECK (solde>=0),
CONSTRAINT CK_ouvert CHECK(ouvert between 0 and 1),
CONSTRAINT CK_code CHECK (code>0)
);
CREATE TABLE Operation(
noperation INT NOT NULL,
dateoperation DATE Default SYSDATE,
codepropose NUMERIC(4),
montant NUMERIC(10,2),
ncompte INT,
CONSTRAINT PK_Operation PRIMARY KEY (noperation),
CONSTRAINT FK_Ope_ncompte_Compte FOREIGN KEY (ncompte) REFERENCES Compte(ncompte),
CONSTRAINT CK_codepropose CHECK (codepropose>=0),
CONSTRAINT CK_montant CHECK (montant>=0)
);
CREATE TABLE Historique(
nhistorique INT NOT NULL,
dateoperation DATE DEFAULT SYSDATE,
montant NUMERIC(10,2),
ncompte INT,
CONSTRAINT PK_Historique PRIMARY KEY (nhistorique)
);
CREATE TABLE Incident(
nincident INT NOT NULL,
message VARCHAR(45),
noperation INT,
CONSTRAINT PK_Incident PRIMARY KEY (nincident),
CONSTRAINT FK_Inc_noperation_Operation FOREIGN KEY (noperation) REFERENCES Operation(noperation)
);
Here are some tests, everything is ok apart from the last insert :
INSERT INTO Client (nom) values ('abderrahmane');
INSERT INTO Client (nom) values ('ben');
Select * FROM Client;
INSERT INTO Compte (solde,nclient) values (200,1);
INSERT INTO Compte (nclient,code) values (2,2403);
INSERT INTO Compte (solde,nclient) values (2300,3);
SELECT * FROM Compte;
INSERT INTO Operation (montant,ncompte) values (200,2);
INSERT INTO Operation (codepropose,ncompte) values (2010,2);
INSERT INTO Operation (ncompte) values (1);
INSERT INTO Operation (codepropose,montant,ncompte) values (2020,20,1);
INSERT INTO Operation (codepropose,montant,ncompte,dateoperation) values (2030,30,2,'01/01/2001');
INSERT INTO Operation (codepropose,montant,ncompte) values (2030,30,3);
SELECT * FROM Operation;
INSERT INTO Historique (montant,ncompte) values (200,2);
INSERT INTO Historique (dateoperation,ncompte) values ('15/04/16',2);
INSERT INTO Historique (ncompte) values (1);
INSERT INTO Historique (dateoperation,montant,ncompte) values ('15/04/16',20,1);
INSERT INTO Historique (dateoperation,montant,ncompte) values ('15/04/16',30,3);
SELECT * FROM Historique;
INSERT INTO Incident (message,noperation) values ('Incident 1',2);
INSERT INTO Incident (message,noperation) values ('Incident 2',8);
INSERT INTO Incident (message,noperation) values ('Incident 3',1);
SELECT * FROM Incident;
UPDATE Compte SET ouvert = 0 WHERE nclient = 2;
INSERT INTO Operation (montant,ncompte,codepropose) values (200,2,2403);
SELECT * FROM Incident; | <sql><oracle><plsql><triggers> | 2016-02-16 10:01:25 | LQ_EDIT |
35,429,375 | iOS ytplayer API not working properly | I have embedded youtube in my application using ytplayer helper library for iOS the main issue I am facing right now is that I have embedded the multiple instances of ytplayer within scrollview and its loosing its not calling the changestate playback properly. the problem occurs when two videos are loaded concurrently. | <ios><youtube-api><ytplayerview> | 2016-02-16 10:03:45 | LQ_EDIT |
35,429,481 | Retrofit 2 void return | <p>In Retrofit 2, service methods representing http methods must return <code>Call</code>. </p>
<p><code>Call</code> is a generic which must take the type representing the return object of the http method. </p>
<p>For example, </p>
<pre><code>@GET("/members/{id}")
Call<Member> getMember(@Path("id") Long id);
</code></pre>
<p>For http methods such as delete, no content is returned. In cases like this, what parameter should be provided to <code>Call</code>?</p>
| <retrofit2> | 2016-02-16 10:08:10 | HQ |
35,430,018 | How to refresh a table view from another view controller iOS? | <p>I have two view controllers. First one has a table view and using the second view controller I'm calling a method on first view controller. In that method I'm trying to adding an item to the objects array and refresh the table view. </p>
<pre><code>[postsArr insertObject:post atIndex:postsArr.count];
dispatch_async(dispatch_get_main_queue(), ^{
[self.newsTableView reloadData];
});
</code></pre>
<p>I'm calling this method in 2nd view controller,</p>
<pre><code>dispatch_async(dispatch_get_main_queue(), ^{
[self.navigationController popViewControllerAnimated:YES];
[self.appContext.creator createWithText:userText completion:^(UserData *userData,NSError *error) {
if (error == nil){
if (userData != nil) {
[self.parent addNew:((UserData*)[userData.list objectAtIndex:0]) withImage:nil];
}
}else{
[self showAlertWith:@"Error" with:@"Error occurred!"];
}
}];
});
</code></pre>
<p>How may I refresh the table view from another view controller?</p>
| <ios><objective-c> | 2016-02-16 10:30:02 | LQ_CLOSE |
35,430,177 | Why redeclaration of variable is allowed inside loop and if condition which are declared out side of loop or if condition already? | <pre><code>#include <stdio.h>
int main()
{
int a=9;
if(a<10){
int a = 20;
++a;
printf("%d\n",a);
}
printf("%d\n",a);
}
</code></pre>
<p>Why redeclaration of a is allowed in loop and if condition here?<br>
Why can't we increment or decrement variable inside loop or if statement which are delclared outside of loop or if statement??</p>
| <c> | 2016-02-16 10:36:50 | LQ_CLOSE |
35,430,584 | How is the git hash calculated? | <p>I'm trying to understand how git calculates the hash of refs. </p>
<pre><code>$ git ls-remote https://github.com/git/git
....
29932f3915935d773dc8d52c292cadd81c81071d refs/tags/v2.4.2
9eabf5b536662000f79978c4d1b6e4eff5c8d785 refs/tags/v2.4.2^{}
....
</code></pre>
<p>Clone the repo locally. Check the <code>refs/tags/v2.4.2^{}</code> ref by sha</p>
<pre><code>$ git cat-file -p 9eabf5b536662000f79978c4d1b6e4eff5c8d785
tree 655a20f99af32926cbf6d8fab092506ddd70e49c
parent df08eb357dd7f432c3dcbe0ef4b3212a38b4aeff
author Junio C Hamano <gitster@pobox.com> 1432673399 -0700
committer Junio C Hamano <gitster@pobox.com> 1432673399 -0700
Git 2.4.2
Signed-off-by: Junio C Hamano <gitster@pobox.com>
</code></pre>
<p>Copy the decompressed content so that we can hash it.(AFAIK git uses the uncompressed version when it's hashing)</p>
<pre><code>git cat-file -p 9eabf5b536662000f79978c4d1b6e4eff5c8d785 > fi
</code></pre>
<p>Let's SHA-1 the content using git's own hash command</p>
<pre><code>git hash-object fi
3cf741bbdbcdeed65e5371912742e854a035e665
</code></pre>
<p>Why the output is not <code>[9e]abf5b536662000f79978c4d1b6e4eff5c8d785</code>? I understand the first two characters (<code>9e</code>) is the length in hex. How should I hash the content of <code>fi</code> so that I can get the git ref <code>abf5b536662000f79978c4d1b6e4eff5c8d785</code> ?</p>
| <git><hash> | 2016-02-16 10:53:19 | HQ |
35,430,906 | Excel PROS please | Is there any excel function that would help in finding different certain letters in 2 columns
For instance,
A B
SSS NNN
BBB HHH
DDD USS
GGG PPP
DDD SSS
DDD USS
DDD NNN
I would like to run a function like:
If any cell that contains any word with S as first letter in column A AND N as a first letter in the column B return "null" else return the result"*** ***"
if(LEFT A=D & B=U) return *** *** the result...
The result is
DDD USS
DDD USS
Thanks in advanced
| <excel> | 2016-02-16 11:08:14 | LQ_EDIT |
35,431,292 | Using the reduce function to return an array | <p>Why is it that when I want to use the push function inside the reduce function to return a new array I get an error. However, when I use the concat method inside the reduce function, it returns a new array with no problem.</p>
<p>All I'm trying to do is pass an array to the reduce function and return the same array.</p>
<pre><code>var store = [0,1,2,3,4];
var stored = store.reduce(function(pV,cV,cI){
console.log("pv: ", pV);
return pV.push(cV);
},[]);
</code></pre>
<p>This returns an error. But when I use concat: </p>
<pre><code>var store = [0,1,2,3,4];
var stored = store.reduce(function(pV,cV,cI){
console.log("pv: ", pV);
return pV.concat(cV);
},[]);
</code></pre>
<p>It returns the same array.</p>
<p>Any ideas why?</p>
| <javascript><arrays><reduce> | 2016-02-16 11:26:12 | HQ |
35,431,684 | Need Regex format and help links | <p>Am new to regex. Can anyone please tell me regex matches for the version number 10.0.10240.0? It will be helpful for me to proceed further.</p>
<p>Thanks </p>
| <c#><regex> | 2016-02-16 11:44:33 | LQ_CLOSE |
35,431,713 | Function in a switch case loop | <p>Is it possible to put a function inside a switch case loop? Because I've tried this just to explore more of this loop. Though I tried other ways but still I've got the problem existed. Can anyone help me?</p>
<pre><code>#include <stdio.h>
int main(void)
{
int choice;
switch(choice);
{
case 1:
{
int GetData()
{
int num;
printf("Enter the amount of change: ");
scanf("%d%*c", &num);
return (num);
}
int getChange (int change,int fifty,int twenty,int ten,int five)
{
int num = change;
fifty = num/50;
num %= 50;
twenty = num/20;
num %= 20;
ten = num/10;
num %= 10;
five = num/5;
num %= 5;
return (fifty, twenty, ten, five);
}
int main()
{
int change, fifty, twenty, ten, five;
change = GetData();
if ((change < 5) || (change > 95) || (change%5 > 0))
{
printf("Amount must be between 5 and 95 and be a multiple
of 5.");
}
else
{
getChange(change, fifty, twenty, ten, five);
printf("Change for %d cents: \n", change);
if (fifty > 1)
printf("%d Fifty cent piece's.\n", fifty);
if (fifty == 1)
printf("%d Fifty cent piece.\n", fifty);
if (twenty > 1)
printf("%d Twenty cent piece's.\n", twenty);
if (twenty == 1)
printf("%d Twenty cent piece.\n", twenty);
if (ten > 1)
printf("%d Ten cent piece's\n", ten);
if (ten == 1)
printf("%d Ten cent piece.\n", ten);
if (five > 1)
printf("%d Five cent piece's\n", five);
if (five == 1)
printf("%d Five cent piece.\n", five);
}
return(0);
}
</code></pre>
| <c><function><loops><switch-statement><case> | 2016-02-16 11:45:42 | LQ_CLOSE |
35,431,775 | C# export data from database into excel. Without any of DLL or open source dlll or any kind of free dll | <p>Please provide way to export data into excel without any DLL or free open source DLL or any kind of DLL.</p>
<p>Help me programmers,</p>
| <c#> | 2016-02-16 11:48:07 | LQ_CLOSE |
35,432,118 | how to view structure of blade template use PHPStorm? | `.php` could view structure of html but `.blade.php` couldn't in PHPStorm.how to use blade and view structure of html at the same time? | <php><laravel><phpstorm><blade> | 2016-02-16 12:03:17 | LQ_EDIT |
35,432,304 | How may Refresh my page when only mysql databases update using php | <p>Actually am developing online ordering system and i need when an order has approved by manager shown automatically on quicken department screen without refreshing a page and notice with beep sound!
please is there any idea? </p>
| <javascript><php><html> | 2016-02-16 12:12:12 | LQ_CLOSE |
35,432,326 | How to get latest offset for a partition for a kafka topic? | <p>I am using the Python high level consumer for Kafka and want to know the latest offsets for each partition of a topic. However I cannot get it to work. </p>
<pre><code>from kafka import TopicPartition
from kafka.consumer import KafkaConsumer
con = KafkaConsumer(bootstrap_servers = brokers)
ps = [TopicPartition(topic, p) for p in con.partitions_for_topic(topic)]
con.assign(ps)
for p in ps:
print "For partition %s highwater is %s"%(p.partition,con.highwater(p))
print "Subscription = %s"%con.subscription()
print "con.seek_to_beginning() = %s"%con.seek_to_beginning()
</code></pre>
<p>But the output I get is </p>
<pre><code>For partition 0 highwater is None
For partition 1 highwater is None
For partition 2 highwater is None
For partition 3 highwater is None
For partition 4 highwater is None
For partition 5 highwater is None
....
For partition 96 highwater is None
For partition 97 highwater is None
For partition 98 highwater is None
For partition 99 highwater is None
Subscription = None
con.seek_to_beginning() = None
con.seek_to_end() = None
</code></pre>
<p>I have an alternate approach using <code>assign</code> but the result is the same</p>
<pre><code>con = KafkaConsumer(bootstrap_servers = brokers)
ps = [TopicPartition(topic, p) for p in con.partitions_for_topic(topic)]
con.assign(ps)
for p in ps:
print "For partition %s highwater is %s"%(p.partition,con.highwater(p))
print "Subscription = %s"%con.subscription()
print "con.seek_to_beginning() = %s"%con.seek_to_beginning()
print "con.seek_to_end() = %s"%con.seek_to_end()
</code></pre>
<p>It seems from some of the documentation that I might get this behaviour if a <code>fetch</code> has not been issued. But I cannot find a way to force that. What am I doing wrong?</p>
<p>Or is there a different/simpler way to get the latest offsets for a topic?</p>
| <python><apache-kafka><kafka-consumer-api><kafka-python> | 2016-02-16 12:13:02 | HQ |
35,432,842 | RealmList of String Type in Android | <p>I'm using Realm for Local storage in Android. I'm getting following response form server.</p>
<pre><code>[{
"ListId": 10,
"Names": ["Name1", "Name2", "Name3", "Name4"]
}]
</code></pre>
<p>Here is my Model</p>
<pre><code> public class Model extends RealmObject {
private int ListId;
private RealmList<String> Names = new RealmList<String>()
public int getListId() {
return ListId;
}
public void setListId(int listId) {
ListId = listId;
}
public RealmList<String> getNames() {
return Names;
}
public void setNames(RealmList<String> names) {
Names = names;
}
}
</code></pre>
<p>And I'm getting this for ArrayList</p>
<p>Type parameter 'java.lang.String' is not within its bound; should extend 'io.realm.RealmObject'.</p>
<p>Thanks.</p>
| <android><realm><realm-list> | 2016-02-16 12:38:00 | HQ |
35,432,985 | Django rest framework override page_size in ViewSet | <p>I am having problem with django rest framework pagination.
I have set pagination in settings like -</p>
<pre><code>'DEFAULT_PAGINATION_CLASS':'rest_framework.pagination.PageNumberPagination',
'PAGE_SIZE': 1
</code></pre>
<p>Below is my viewset. </p>
<pre><code>class HobbyCategoryViewSet(viewsets.ModelViewSet):
serializer_class = HobbyCategorySerializer
queryset = UserHobbyCategory.objects.all()
</code></pre>
<p>I want to set different page size for this viewset. I have tried setting page_size and Paginate_by class variables but list is paginated according to PAGE_SIZE defined in settings. Any idea where I am wrong ?</p>
| <python><django><django-rest-framework> | 2016-02-16 12:44:12 | HQ |
35,433,249 | GraphicsMagick: toBuffer() Stream yields empty buffer | <p>I am trying to read a file into a buffer, resize it and then write it to disk using the following example code:</p>
<pre><code>function processImage(data) {
gm(data, 'test.jpg')
.resize('300x300')
.background('white')
.flatten()
.setFormat('jpg')
.toBuffer(function(err, buffer) {
if (err) {
throw err;
} else {
fs.writeFile('asd.jpg', buffer);
}
});
}
</code></pre>
<p>However, this generates an error <code>Error: Stream yields empty buffer</code>. I have played around, used imageMagick and graphicsMagick, still the same. </p>
<p>If i substitute<br>
<code>toBuffer(...</code><br>
with<br>
<code>write('asd.jpg', function(err) ...</code></p>
<p>it actually writes a proper file.</p>
<p><strong>EDIT</strong> While writing this question I found the solution, see reply</p>
| <node.js><imagemagick><graphicsmagick> | 2016-02-16 12:56:29 | HQ |
35,434,536 | javascript object array Group By and Get values | I want to do a groupBy for the below object array on deptId and I should be able to display the data on page using angular as below
I have an object like this
var arr = [
{deptId: '12345',deptName: 'Marketing', divId: '1231',divName: 'Lead'},
{deptId: '12345',deptName: 'Marketing', divId: '8796',divName: 'Assistants'},
{deptId: '32145',deptName: 'Sales', divId: '1231',divName: 'Lead'},
{deptId: '32145',deptName: 'Sales', divId: '8796',divName: 'Assistants'},
{deptId: '32145',deptName: 'Sales', divId: '8221',divName: 'Associates'}
]
Display on ui as below
Marketing
<ul><li>Lead
<li>Assistants
</ul>
Sales
<ul>
<li>Lead
<li> Assistants
<li> Associates
</ul> | <javascript><angularjs><html><lodash> | 2016-02-16 13:57:57 | LQ_EDIT |
35,435,310 | secant method in Python to solve f(x) = 0 | <p>How can I use the secant method in Python to solve the equation f(x) = 0 given 2 intial guesses, x0 and x1?.</p>
<pre><code>def secant(f,x0,x1,tol):
</code></pre>
<p>I need to use it to find solutions to quadratics and higher factors of x, for example, x^3 -4x^2 + 1 = 0 for a given interval.
This is just a shot in the dark so any links to useful websites will also be appreciated!</p>
| <python><math><methods> | 2016-02-16 14:35:02 | LQ_CLOSE |
35,435,405 | xhttp is not defined when using ajax calls into an iframe | <p>Good day all, I'm developing a php page in which there is an iframe, that opens another php page with a checkbox in it, this second page, when the user click on the checkbox, has to make an ajax call to confirm the "click".</p>
<p>so there is pageA.php, with a iframe in it that points to pageB.php, in this one, there is only a form with a checkbox and a javascript (vanilla javascript), that sould call a third page on click.</p>
<p>this is the javascript I'm using to send the "click":</p>
<pre><code>document.getElementById("checkboxMe").onclick = function() {
xhttp.open("POST", "pageC.php", true);
xhttp.send("foo=bar");
};
</code></pre>
<p>when clicking on the checkbox, this is what I see on the console:</p>
<pre><code>Uncaught ReferenceError: xhttp is not defined
</code></pre>
<p>it never happen something like this, infact I can't find this error easily on google, does anyone has some clues?
maybe is the fact I'm into an iframe?
how could I solve this issue?</p>
<p>thanks in advance ppl.</p>
| <javascript><php><ajax><iframe> | 2016-02-16 14:39:54 | HQ |
35,435,611 | Call 2 functions within onChange event | <p>I'm a bit stuck with my component, I need to call onChange from props so</p>
<pre><code><input type="text" value={this.state.text} onChange={this.props.onChange} />
</code></pre>
<p>but also call another function within the component called <code>handleChange()</code> that updates the state.text, I tried</p>
<pre><code> <input type="text" value={this.state.text} onChange={this.props.onChange; this.handleChange} />
</code></pre>
<p>but this doesn't seem to work.</p>
| <javascript><reactjs> | 2016-02-16 14:49:43 | HQ |
35,435,691 | BigDecimal, precision and scale | <p>I'm using BigDecimal for my numbers in my application, for example, with JPA. I did a bit of researching about the terms 'precision' and 'scale' but I don't understand what are they exactly.</p>
<p>Can anyone explain me the meaning of 'precision' and 'scale' for a BigDecimal value?</p>
<pre><code>@Column(precision = 11, scale = 2)
</code></pre>
<p>Thanks!</p>
| <java><jpa><scale><precision><bigdecimal> | 2016-02-16 14:53:31 | HQ |
35,435,774 | Could not load file or assembly Microsoft.Practices.ServiceLocation, Version=1.3.0.0 | <p>Here is the error I'm getting when I run my application (.NET 4.5):</p>
<pre><code>Server Error in '/' Application.
Could not load file or assembly 'Microsoft.Practices.ServiceLocation, Version=1.3.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' or one of its dependencies. The system cannot find the file specified.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.IO.FileNotFoundException: Could not load file or assembly 'Microsoft.Practices.ServiceLocation, Version=1.3.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' or one of its dependencies. The system cannot find the file specified.
Source Error:
An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.
Assembly Load Trace: The following information can be helpful to determine why the assembly 'Microsoft.Practices.ServiceLocation, Version=1.3.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' could not be loaded.
=== Pre-bind state information ===
LOG: DisplayName = Microsoft.Practices.ServiceLocation, Version=1.3.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35
(Fully-specified)
LOG: Appbase = file:///C:/Users/Austin/Documents/FileStore/FileStore.Web/
LOG: Initial PrivatePath = C:\Users\Austin\Documents\FileStore\FileStore.Web\bin
Calling assembly : Chicago.Security, Version=1.0.5826.21195, Culture=neutral, PublicKeyToken=null.
===
LOG: This bind starts in default load context.
LOG: Using application configuration file: C:\Users\Austin\Documents\FileStore\FileStore.Web\web.config
LOG: Using host configuration file: C:\Users\Austin\Documents\IISExpress\config\aspnet.config
LOG: Using machine configuration file from C:\Windows\Microsoft.NET\Framework\v4.0.30319\config\machine.config.
LOG: Redirect found in application configuration file: 1.3.0.0 redirected to 1.3.0.0.
LOG: Post-policy reference: Microsoft.Practices.ServiceLocation, Version=1.3.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35
LOG: The same bind was seen before, and was failed with hr = 0x80070002.
Stack Trace:
[FileNotFoundException: Could not load file or assembly 'Microsoft.Practices.ServiceLocation, Version=1.3.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' or one of its dependencies. The system cannot find the file specified.]
Chicago.Security.AuthenticationModule.application_AuthenticateRequest(Object sender, EventArgs e) +0
System.Web.SyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +141
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +69
</code></pre>
<p>I installed the nuget package CommonServiceLocator, but I'm still getting this error. The weird thing is that there is an assembly binding redirect in my web.config file, but the assembly does not appear in the reference list for my project and I cannot find it anywhere to add it. I'm still relatively new to ASP.NET, so I can't seem to pin down what the issue is exactly. Another thing I found to try is to set 'Enable 32 bit applications' to true for my application pool in the IIS Manager, but this did not fix my problem. I've been stuck on this for a while, so any help would be appreciated.</p>
| <c#><asp.net><.net><visual-studio-2015><nuget> | 2016-02-16 14:56:49 | HQ |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.