samedi 31 mai 2014

ajax sending data conflict


Vote count:

0




hello i have two forms in my html code and i send data to two different php files but something is wrong,when i submit a button he send data to second php file. hello i have two forms in my html code and i send data to two different php files but something is wrong,when i submit a button he send data to second php file. hello i have two forms in my html code and i send data to two different php files but something is wrong,when i submit a button he send data to second php file.



<form id="comment" method="post" action="comment.php" role="form">
<input type="hidden" name="id" value="<?php echo $rows['id']; ?>">
<textarea name="comment" class="form-control" rows="3"></textarea>
<div style="padding:10px 0 25px 0">
<button type="submit" class="pull-right btn btn-default">Post Comment</button></div>
</form>

<script type="text/javascript">
var frm = $('#comment');
frm.submit(function (ev) {
$.ajax({
type: frm.attr('method'),
url: frm.attr('action'),
data: frm.serialize(),
success: function (data) {
new PNotify({
title: 'Comment posted.',
text: 'Back to tasks list in 3 seconds..',
type: 'success'
});
setTimeout(function(){window.location.reload()}, 3000);
}
});
ev.preventDefault();
});
</script>


<form id="editticket" method="post" action="edit-ticket.php" role="form">
<input type="hidden" name="id" value="<?php echo $id; ?>" >
<div class="form-group">
<label>Change Name</label>
<input name="name" class="form-control" value="<?php echo $rows['name']; ?>" placeholder="">
</div>
<div class="form-group">
<label>Add user</label>
<input name="users" class="form-control" placeholder="write name">
</div>
<button type="submit" onclick="tinyMCE.triggerSave();"class="btn btn-default">Save changes</button>
</form>

<script type="text/javascript">
var frm = $('#editticket');
frm.submit(function (ev) {
$.ajax({
type: frm.attr('method'),
url: frm.attr('action'),
data: frm.serialize(),
success: function (data) {
new PNotify({
title: 'Task edited.',
text: 'Back to tasks list in 3 seconds..',
type: 'success'
});
setTimeout(function(){window.history.back()}, 3000);
}
});
ev.preventDefault();
});
</script>

editticket.php
<?php
include_once 'include/functions.php';
secureSession();
editTicket($mysqli,$id);
?>

comment.php
<?php
include_once 'include/db_connect.php';
include_once 'include/functions.php';
secureSession();
$id = $_POST['id'];
comment($mysqli,$id);
?>


asked 52 secs ago






OSX AVAudioPlayer doesn't play


Vote count:

0




This method is correctly connected to a NSButton, the *url object is correctly initialized with a real resource on the filesystem, the mp3file file is added to the application bundle, when i click the button, i can see the "NSLog(@"playSound: path %@", url);" to log correctly, the url refers to a real file on the disk. I can see from the debugger that the *error object is nil while the *audioPlayer object is correctly initialized. The volume of my mac is turned on :) but no sound is coming out of the speaker when i click the button.


I don't see any reason why this code should not work.


Please help!



- (IBAction)playSound:(id)sender {
NSUserDefaults *standardDefaults = [NSUserDefaults standardUserDefaults];
NSURL *url = [[NSBundle mainBundle] URLForResource:[standardDefaults stringForKey:@"SoundKey"] withExtension:@"mp3"];
NSError *error;
AVAudioPlayer *audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error];
[audioPlayer prepareToPlay];
if ([audioPlayer isPlaying]) {
[audioPlayer pause];
} else {
[audioPlayer play];
}

#if DEBUG

if (error) {
NSLog(@"playSound: error: %@", error);
}
NSLog(@"playSound: path %@", url);

#endif

}


asked 22 secs ago






PHP filter_input were validatio flags are an enum?


Vote count:

0




Looked around but didn't see this anywhere, the basic question is, can I use a filter_input_array were the value of one of my keys is an enum (think mysql enum), protocode would be something like this.



print_r(filter_input_array(INPUT_POST, [
'CanBeFooOrBar' => [
'filter' => FILTER_VALIDATE_ENUM,
'options' => ['foo', 'bar'],
]
]));


If this is possible, what is my filter, and if not, what would be the best way to replicate this behavior?



asked 23 secs ago

ehime

1,884





Ajax, add to database and update div content


Vote count:

0




Okay, so I am trying to use ajax. I've tried several ways of doing this but nothing is working for me. I believe the main problem I have is that ajax won't add to my database, the rest is managable for me.


Here is the relevant ajax-code:



function posts(){
var xmlhttp;
if (window.XMLHttpRequest){
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState == 4 && xmlhttp.status == 200){
document.getElementById("threads").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET", sessionStorage.page, true);
xmlhttp.send();


}


function update_post(){ var message = $("#message").val();



var dataString = "content=" + message;

$.ajax({
url: 'post_process.php',
async: true,
data: dataString ,
type: 'post',
success: function() {
posts();
}
});


}


Here is the post_process.php:



<?php
require_once "include/bootstrap.php";

if (isset($_POST['subject'])){
$subject = $con->real_escape_string($_POST["subject"]);
$Qnum = rand();
die ("if 1");
} else {
$subject = $_SESSION['subject'];
$Qnum = $_SESSION['qnum'];
die ("else 1");
}
$message = $con->real_escape_string($_POST["message"]);

if (validateEmpty($message) && validateEmpty($subject)){
send();
die ("if 2");
} else {
die ("Error!");
}

function send(){
global $con, $message, $subject, $Qnum;
die ("i send()");

$con->create_post($_SESSION['username'], $_SESSION['category'], $subject, $message, $Qnum);
}

//header("Location: index.php");


?>


And lastly, here is the html-form:



<div id="post_div">
<form name="threadForm" method="POST" action="" onsubmit="return validate_post();">
<label for="message">Meddelande</label><br>
<textarea id="message" name="message" id="message" maxlength="500">

</textarea><br>
<input type="submit" onclick="update_post()" value="Skicka!" name="post_btn" id="post_btn"><br>
</form>


I've tried putting alert:s in the js-code and die:s in the php-code to see how far it gets and I've concluded that it doesn't call my $.ajax. I've tried using $.post instead with no luck.



asked 47 secs ago






How to uninstall system apps (via adb) without restarting the device?


Vote count:

0




Background


One of my app 's features is to uninstall system apps using adb commands.


The problem


It works fine, but each time I uninstall a system app, it requires the user to restart the device.


Otherwise, there is a trace of the app that appears to the user as if the app wasn't really uninstalled, while it actually was removed and cannot be run.


Another problem that is caused by restarting without real uninstallation, is that the launchers aren't aware of the fact that the app got uninstalled.


What I've tried


There are plenty of places over the Internet (including here) which describe how to uninstall system apps, but none of them handles the need for restarting the device.


In all of the solution I've seen, the steps include:



  1. mount the "/system" to enable writing to it

  2. remove the APK of the app

  3. reverse step 1, by mounting "/system? as read-only.

  4. uninstall the app. This actually isn't needed, since after a reboot the OS already removes all of the traces of the app, because of the previous steps.


Some of the solutions I've seen even include editing the packages list on the "/system" folder, but this also didn't help.


Many of the solution have different commands for step 1 and 3 , but all succeed anyway (after a restart).


I've also tried something that I thought of: copying the APK file somewhere, do the uninstallation using steps 1-3, and then do a silent install of the APK and silent uninstall of it. It didn't work. no idea why.


The question


How do you use ADB to uninstall system apps without the need to restart the OS ?



asked 17 secs ago






Strange location of panels


Vote count:

0




I have a program which is some kind of tests. In this test, I have function AddQuestion that adds one panel with question. To place these panels one by one, I have a variable loc that saves location of next panel. First two Panel's with questions adds correct, but next ones are located wrong(far away at the bottom). What can it be?



public void AddQuestion(int number, Question quest)
{
Panel p = new Panel();
p.Name = "panel" + (number);
p.Size = new Size(550, 400);
p.Location = new Point(40, loc);
p.BackColor = System.Drawing.Color.Bisque;
p.AutoScroll = true;
Panel pict_block = new Panel();
pict_block.Size = new Size(480, 200);
pict_block.Location = new Point(10, 10);
PictureBox pict = new PictureBox();
pict.Image = quest.image;
pict.Size = new Size(240, 180);
pict.SizeMode = PictureBoxSizeMode.StretchImage;
pict.Location = new Point(130, 1);
pict_block.Controls.Add(pict);
p.Controls.Add(pict_block);

Label number_text = new Label(); //номер питання
number_text.Text = "Питання № " + number ;
number_text.Font = new Font("Aria", 8, FontStyle.Bold);
number_text.AutoSize = false;
number_text.Location = new Point(400, 210);
p.Controls.Add(number_text);

Label q_text = new Label(); // текст питання
q_text.Text = quest.question_text;
q_text.Font = new Font("Aria", 9, FontStyle.Bold);
q_text.AutoSize = false;
q_text.Size = new Size(400, 50);
q_text.Location = new Point(5, 220);
p.Controls.Add(q_text);
int iter = q_text.Location.Y + 60;
if (CheckIfMuliple(number))
{
foreach (string key in quest.answers.Keys)
{
CheckBox rb = new CheckBox();
rb.Text = key;
rb.AutoSize = true;
rb.Size = new Size(300, 25);
rb.Location = new Point(q_text.Location.X + 15, iter);
iter += 30;
p.Controls.Add(rb);
}

}
else
{
foreach (string key in quest.answers.Keys)
{
RadioButton rb = new RadioButton();
rb.Text = key;
rb.Size = new Size(300, 25);
rb.AutoSize = true;
rb.Location = new Point(q_text.Location.X + 10, iter);
iter += 30;
p.Controls.Add(rb);
}
}
questions_panel.Controls.Add(p);
loc += 450;

}


asked 21 secs ago






Below code is not working,pls suggest


Vote count:

0




I have a small user control having a textbox and a button in it. I have a label in my page which consuming the usercontrol,on button click event of user control I am finding out the area of user input value and want to display that area in lebel in main page.



public partial class WebUserControl1 : System.Web.UI.UserControl
{
public delegate void myeventhandler(object sender,MyEventArgs e);

public event myeventhandler MyEvent;

protected void Button1_Click(object sender, EventArgs e)
{
int radious= Convert.ToInt32(TextBox1.Text);
double area = 3.14 * radious * radious;
MyEventArgs myeventargs = new MyEventArgs();
myeventargs.Area = area;
MyEvent(this, myeventargs);

}

}
public class MyEventArgs : EventArgs
{
public double Area { set; get; }

}


in the main page I have written the below code:



public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
WebUserControl1 objuc = new WebUserControl1();
objuc.MyEvent += new WebUserControl1.myeventhandler(DisplayArea);

}

public void DisplayArea(object sender,MyEventArgs e)
{
Label1.Text = e.Area.ToString();

}
}

But I am getting a NullReferenceError on line
MyEvent(this, myeventargs);


any help would be appreciated



asked 26 secs ago






Comparing cat output as variable


Vote count:

0




I am trying to make a script were it compares the output of the /results file when it equals 1.



#!/bin/sh

RESULTS=/results
$
while true
do
ping -c 5 1.1.1.1 > /dev/null && echo "1" > /results || echo "0" > /results
if

[ $RESULTS = "1" ];
then
echo "working"
sleep 5
else

echo "not working"
sleep 5
fi

done


asked 13 secs ago






SQL Linq .Take() latest 20 rows from HUGE database, performance-wise


Vote count:

0




I'm using EntityFramework 6 and I make Linq queries from Asp.NET server to a azure sql database.


I need to retrieve the latest 20 rows that satisfy a certain condition


Here's a rough example of my query



using (PostHubDbContext postHubDbContext = new PostHubDbContext())
{
DbGeography location = DbGeography.FromText(string.Format("POINT({1} {0})", latitude, longitude));

IQueryable<Post> postQueryable =
from postDbEntry in postHubDbContext.PostDbEntries
orderby postDbEntry.Id descending
where postDbEntry.OriginDbGeography.Distance(location) < (DistanceConstant)
select new Post(postDbEntry);

postQueryable = postQueryable.Take(20);
IOrderedQueryable<Post> postOrderedQueryable = postQueryable.OrderBy(Post => Post.DatePosted);

return postOrderedQueryable.ToList();
}


The question is, what if I literally have a billion rows in my database. Will that query brutally select millions of rows which meet the condition then get 20 of them ? Or will it be smart and realise that I only want 20 rows hence it will only select 20 rows ?


Basically how do I make this query work efficiently with a database that has a billion rows ?



asked 1 min ago

Dv_MH

161





am i allowed to use member variables in static inner class for fragments?


Vote count:

0




All my static fragments are:



public static class SomeFragment extends Fragment {
int somenum;
String name;
}


are the values of somenum and name shared between different instances because the class is static?



asked 38 secs ago

tipu

1,623





Insert newline on enter key in contenteditable div


Vote count:

0




I am trying to insert a newline character instead of whatever the browser wants to insert when I press enter in a contenteditable div.


My current code looks something like this:



if (e.which === 13) {
e.stopPropagation();
e.preventDefault();

var selection = window.getSelection(),
range = selection.getRangeAt(0),
newline = document.createTextNode('\n');

range.deleteContents();
range.insertNode(newline);
range.setStartAfter(newline);
range.setEndAfter(newline);
range.collapse(false);
selection.removeAllRanges();
selection.addRange(range);
}


This seems to work in Chrome, Firefox and Safari but fails in internet explorer.


My requirement is that it works in the most recent versions of Chrome/FF and similar (a couple versions back wouldn't be a bad idea) and in IE10+.


I have tried a lot of different things but just can't seem to get it to work.


Any help is much appreciated!



asked 1 min ago

Lindrian

1,373





JAX WS: Webserver not returning latest changes


Vote count:

0




I started to learn Restful Web services using Java. I set up my eclipse. Configured Tomcat in it. Below is my latest code



@Path("/v1/status/*")
public class V1_status {

@GET
@Produces(MediaType.TEXT_HTML)
public String returnTitle(){
return("<h1>This is a Text</h1>");
}

@Path("/version")
@GET
@Produces(MediaType.TEXT_HTML)
public String returnVersion(){
return("<h1>This is Version 2</h1>");
}
}


When I am trying to hit my webservice using localhost:8080/com.rahul.webservertest/api/v1/status/version It should return "This is Version 2". However its returning "This is Version 1" which was my old code. Trust me, I republished it after the change and restarted tomcat. Even if I comment out the whole method "returnVersion" and publish and restart, its returning "This is Version 1" when it should say, "Method Not Allowed" or something. What am I doing wrong?



asked 1 min ago

rahul

1,692





Error when trailing return type is replaced by automatic return type


Vote count:

0




I was recently wondering about the rules of applicability of automatic return types (which was marked as a duplicate of a question about the syntax of functions with automatic return types).


It seems that wherever uniformly deducable, the return type can be used by automatic return type functions. Yet while trying to get advantage of this feature, a working snippet that looked like this :



#include <iostream>
using namespace std;

auto f(int *i) -> decltype(i[0]) {
return i[0];
}

int main() {
int ar[] = {1, 2, 4, 5, 6, };
f(ar) = 4;
cout << ar[0];
return 0;
}


turned non-compilable due to automatic return type :



auto f(int *i) {
return i[0];
}


What is the problem here?



asked 39 secs ago






PHP or JQuery analyze each vertical line of pixels by colour


Vote count:

0




I have not tried anything of this yet, simply because I have no idea on how to get started with this.


What I'm trying to do is to create a PHP file that can read each vertical Line of pixels in a 2 Colour Image and return a Percentage of the heighest pixel in a certain Color.


Let me explain some more.


Lets say you have a Image of two colours, Black AND White. Like this ..


enter image description here


How would you start reading this image from left to right and taking the heighest black pixel for each vertical row of pixel from bottom to top?


Can please somone point me in the right direction or provide some part of code that might help me get started with this.


Thanks in advance.



asked 1 min ago






Painting on a JPanel inside a JScrollPane doesn't paint in the right location


Vote count:

0




So I have a JPanel that's inside a JScrollPane. Now I am trying to paint something on the JPanel, but it's always in same spot. I can scroll in all directions but it's not moving. Whatever I paint on the JPanel does not get scrolled.


I already tried:

1. A custom JViewPort

2. switching between Opaque = true and Opaque = false


Also I considered overriding the paintComponent method of the JPanel but that would be really hard to implement in my code.



public class ScrollPanePaint{

public ScrollPanePaint() {
JFrame frame = new JFrame();
final JPanel panel = new JPanel();
panel.setPreferredSize(new Dimension(1000, 1000));
//I tried both true and false
panel.setOpaque(false);
JScrollPane scrollPane = new JScrollPane(panel);
frame.add(scrollPane);
frame.setSize(200, 200);
frame.setVisible(true);
//To redraw the drawing constantly because that wat is happening in my code aswell because
//I am creating an animation by constantly move an image by a little
new Thread(new Runnable(){
public void run(){
Graphics g = panel.getGraphics();
g.setColor(Color.blue);
while(true){
g.fillRect(64, 64, 3 * 64, 3 * 64);
panel.repaint();
}
}
}).start();
}

public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {

@Override
public void run() {
new ScrollPanePaint();
}
});
}


}


The mistake I make is probably very easy to fix, but I just can't figure out how.



asked 22 secs ago






Responsive Canvas in Bootstrap column?


Vote count:

0




I'm new to bootstrap and working on a project to help figure it out. I also don't know much LESS yet.


I have 2 columns: col-xs-3 and col-xs-9. In the 9 column, I have a canvas that I would like to retain a particular aspect ratio. I don't actually care what the aspect ratio is, as long as it's the same everywhere. Specifically, as wide as the column and a proper height for the given width.


I've tried using percentages for width and height, but even if that did work, it'd be less than ideal in a dynamic height column.



asked 1 min ago






Sql query and matching strings/numbers


Vote count:

0




I am working with several tables. An Employee table (tblEmployee), a Managers table (tblManager), and a manager log table (tblLog). In the log table there is about 10 columns. The first column is the manager ID. There is another column that has the first name of an employee to be transferred, and to which dept that employee should go to. Below is a snapshot of that column:



Bob- Dept: 7 Meg- Dept: 5
Bob- Dept: 7 Meg- Dept: 5
Bob- Dept: 7 Meg- Dept: 5
Preston- Dept: 1
Martin- Dept: MANG Sue- Dept: MANG Sarah - DEPT: 8
Martin- Dept: MANG Sue- Dept: MANG Sarah - DEPT: 8
Martin- Dept: MANG Sue- Dept: MANG Sarah - DEPT: 8
Isabel- Dept: 6 Mike- Dept: 5
Isabel- Dept: 6 Mike- Dept: 5
Dan- Dept: MANG
Dan- Dept: MANG


As you can see, there are duplicate rows. The manager who is recommending Bob and Meg be transferred has 3 rows for his ID. That is because he has 3 employees in the table, a row for each employee. I am working on extracting just the employees that are being transferred to management (MANG) or another dept(#1-8). I have a query written that gets all of the information I need, but it gets every employee in the log table, it currently does not filter out the extra ones. So say I am returning 150 rows, there are actually only 100 employee tranfers and 50 other employees who are in the log table for a different reason.


I was trying to come up with a query that takes the first name of the employee and checks if it is in the column, then takes the employees future dept number (from tblEmployee) and checks that it matches the number in the log column. I have looked at PARTINDEX and REGEXs but I am not skilled enough to come up with a solution that can achieve the desired result



asked 35 secs ago






How to mock results of Enumerable.Any() extension using moq


Vote count:

0




I'm using mongo driver, and trying to fake results of any to test whether Insert or Update was called based on results.


Here's piece of code I think relevant:



_context = _collection.AsQueryable();
if (_context.Any(s => s.Id == id))
{
...


after that I'm calling either _collection.Update() or _collection.Insert().


Here's what I tried so far with the unit test:



var collectionMock = new Mock<MongoCollection<Storage>>();
var queriableMock = new Mock<IQueryable<Storage>>();
queriableMock.Setup(q => Enumerable.Any(q)).Returns(() => false);

...
collectionMock.Setup(c => c.AsQueryable()).Returns(() => queriableMock.Object);
collectionMock.Setup(c => c.Save(It.IsAny<Storage>()));


I'm getting exception



"Expression references a method that does not belong to the mocked object: q => q.Any()"




asked 33 secs ago






Initialize a single row, multiple column array in vb.net


Vote count:

0




I think this should be obvious, but this is a special case with no real answer that I have been able to find. I wish to declare and initialize a (0,n) Array and have no idea what the proper syntax might be. Something like:



Public Shared A(,) = {{,"One"},{,"Two"},{,"Three"}}


is the closest I have come, but that is not legal. Any help will be appreciated.



asked 37 secs ago






Retrieve listbox item back from database?


Vote count:

0




How to retrieve listbox item(s) back from database to listBoxT?


My javascript code.....................................................................................................................................



function multiAdd(){
var from = document.getElementById('listBoxF'),
to = document.getElementById('listBoxT');
for(var i = from.length - 1; i >= 0; i--){
if(from.options[i].selected){
to.add(from.options[i]);
from.remove(i);
}
}
multiHidden();
}
function multiAddAll(){
var from = document.getElementById('listBoxF'),
to = document.getElementById('listBoxT');
for(var i = from.length - 1; i >= 0; i--){
to.add(from.options[i]);
from.remove(i);
}
multiHidden();
}
function multiRemove(){
var from = document.getElementById('listBoxT'),
to = document.getElementById('listBoxF');
for (var i = from.length - 1; i >= 0; i--){
if(from.options[i].selected){
to.add(from.options[i]);
from.remove(i);
}
}
multiHidden();
}
function multiRemoveAll(){
var from = document.getElementById('listBoxT'),
to = document.getElementById('listBoxF');
for(var i = from.length - 1; i >= 0; i--){
to.add(from.options[i]);
from.remove(i);
}
multiHidden();
}
function multiHidden(){
var from = document.getElementById('listBoxT'),
to = document.getElementById('listBoxH');
to.value = new Array();
for(var i = from.length - 1; i >= 0; i--){
to.value += from.options[i].value + '|';
}
}

</script>


My Html Code



<form action="" method="POST">
<input type="hidden" name="listBoxH" id="listBoxH">

<select multiple size="8" name="listBoxF" id="listBoxF" style="width:350px">
<option value="Afghanistan"></option>
<option value="Aland Islands"></option>
<option value="Albania">Albania</option>
<option value="Algeria">Algeria</option>
<option value="American Samoa">American Samoa</option>
<option value="Andorra">Andorra</option>
</select>
<div style="text-align:center">
<input type="button" id="listBoxAdd" onclick="multiAdd()" value="Add">
<input type="button" id="listBoxAddAll" onclick="multiAddAll()" value="Add All">
<input type="button" id="listBoxRemove" onclick="multiRemove()" value="Remove">
<input type="button" id="listBoxRemoveAll" onclick="multiRemoveAll()" value="Remove All">
</div>
<select multiple size="8" name="listBoxT" id="listBoxT" style="width:350px"></select>

<input type="submit" name="submit" value="Submit">


asked 57 secs ago






Create working copies of only one (of many) branch in SVN


Vote count:

0




I am new to SVN so perhaps this is an easy question. I swear I have searched out a similar question but perhaps the only search terms I can think of are just too general.


In any case, my team puts release candidates into branches so that the trunk is always the development repository. However there is also a substantial amount of side projects that live as sibling branches to the candidates (and releases). Often these side projects have a copy of the platform which makes them large.


How can I get the latest release candidate without downloading all of the sibling branches? This will be more and more essential to do as releases come out because they too have the entire platform code in them and eventually it will be too much for a hard drive to store each release separately.


I am using Tortoise as a client for SVN but I can try command line SVN if there are additional options I could use.



asked 50 secs ago

MAB

20





Bug with importing project into eclips


Vote count:

0




I found this in error log when try to import an existing project Exception occurred while saving project preferences: /App/.settings/org.eclipse.jdt.core.prefs. How can i fix this ?



asked 39 secs ago






Loading react components with require causes an error when they lookup their parent


Vote count:

0




I am trying to dynamically load a react component from a file and insert it to my AppComponent. I simply load the file with require. This is the Setup I have:



MyFancyApp = ->

api = {}
DynView = undefined

AppView = React.createClass
render: ->
DynView {}

loadModules = ->
new Promise (resolve) ->
require (["src/secretView"]), (SecretView) ->
DynView = SecretView
resolve()

renderApp = ->
new Promise (resolve) ->
React.renderComponent (AppView {}), document.body, resolve

api.start = ->
loadModules().then renderApp

api


The secretView file looks as follows:



React.createClass
render: ->
React.DOM.input {}


When rendering the view, it will throw a "TypeError: Cannot read property 'firstChild' of undefined". This happens in react's findComponentRoot function on the call to findDeepestCachedAncestor.


The really strange thing happens, when I try the same code, but with the react component defined right there instead of dynamically loaded.



MyFancyApp = ->

api = {}

DynView = React.createClass
render: ->
React.DOM.input {}

AppView = React.createClass
render: ->
DynView {}

renderApp = ->
new Promise (resolve) ->
React.renderComponent (AppView {}), document.body, resolve

api.start = ->
renderApp()

api


That works!


The code for the two components is 1:1 the same and they also look the same when I inspect them in chrome. The error seems to happen when there is a reference up the component tree (or to some cached objects?). I have had similiar errors trying to render a custom component, that was using the 'ref' attribute. That caused react to throw an error on the 'addComponentAsRefTo' function, which also seemed to be caused by react trying to look up the tree.


So what possible differences are there between a component loaded via require and one defined right in place?


Thanks a lot



asked 3 mins ago

sra

404





Byte Stream data of an uploaded file


Vote count:

0




I am uploading an image file through an html page. I need to retrieve the image file from the page itself for use in my desktop based utility. Is there any way to retrieve the byte array data of the image file from the html page itself ? Thanks in advance.



asked 20 mins ago






How to get a list of the Value of a number as the sum of 4 numbers in Prolog


Vote count:

0




I'm having trouble making this predicate work. The idea is to use diabolic([A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P]) to obtain all the possible magic squares in that list.


At first I thought about using permutation/2 but it's hella slow for a list of 16 numbers.


Then I found an example here which uses an external library (clpfd) and has awesome performance, but I'm trying to solve it without any external library... so I tried something like this:



sum([X,Y,Z,W]) :-
A = [1..16],
member(X,A),
member(Y,A),
member(Z,A),
member(W,A),
X \== Y,
X \== Z,
X \== W,
Y \== Z,
Y \== W,
Z \== W,
34 is (X+Y+Z+W).


What I'm trying to do there is getting all the possible lists of different numbers which sum is 34 so I can then check which combination makes a magic square (in hopes of making it faster that using normal permutation.


Still, I'm getting an error about some Operator Expected in member(X,[1..16]), so maybe i'm doing something wrong. I'm pretty new to Prolog so I was hoping to get some help from you guys.


Thanks in advance.



asked 1 min ago






i want to automate the image updates in openstack glance which lib file should i be looking for


Vote count:

0




i am just starting out with openstack ,i would like to start my development with glance . I would want to modify some glance library files , my idea is to resize the images based on some criteria can someone help me in finding out which library file should i be modifying.


Thanks for help



asked 1 min ago






PointLatLng in GMap.NET


Vote count:

0




I am having 2 lists: latitude and longitude.



List<double> latitude = new List<double>();
List<double> longitude = new List<double>();


As the name, each element in these lists is a double value represents for latitude (in latitude list) and longitude (in longitude list).


Is there anyway that I can create another List called PointLatLng that each element is a pairs of one latitude and one longitude from the corresponding list?


For example: PointLatLng[0] = (latitude[0], longitude[0])


Knowing that GMap.NET has the method public PointLatLng(double lat, double lng)



asked 23 secs ago






incompatible block pointer types


Vote count:

0




I have this on MyClass:



typedef void (^myBlockType)();


then



- (id)initWithBlock:(myBlockType)block;


when I use that class I do



MyClass *obj = [[MyClass alloc] initWIthBlock:^{

// do stuff
}];


I have an error incompetible block pointer types sending int(^)(void) to parameter of type myBlockType aka void(^)()


What is wrong?



asked 36 secs ago






I don't know how to use real path in php


Vote count:

0




I'm trying to use this code but it gives me an error :



// root path defined("ROOT_PATH")
|| define("ROOT_PATH", realpath(dirname(__ FILE__) . DS."..".DS));


this is the error:


Parse error: syntax error, unexpected 'FILE__' (T_STRING) in /opt/lampp/htdocs/op/inc/config.php on line 20



asked 13 secs ago






CoffeeScript working strangely with Rails 4


Vote count:

0




I cannot get CoffeeScript working with Rails. This is the first time I'm using CoffeeScript and I'm also fairly new with Rails too, so I don't know how to make this simple CoffeeScript function to work in the right way. Below is my people.js.coffee file at app/assets/javascript directory.



myFunction = ->
alert "test"


The alert “test” message only shows up when I load the page (app/views/people.html.erb and _form.html.erb partial); not when I click the below button in the form:



<%= submit_tag "Test CoffeeScript", :type => 'button',
:id => 'coffeeScript', :onclick => 'myFunction()' %>


I don't know why this strange behaviour is happening. Why :onclick is not working? The generated source code for the button should be ok:



<input id="coffeeScript" name="commit" onclick="myFunction()"
type="button" value="Test CoffeeScript" />


Below is my application.js file at app/assets/javascript.



...
//
//= require jquery
//= require jquery_ujs
//= require turbolinks
//= require_tree .


My Ruby version is 2.1.0 Here are some values when I ran bundle show command:



  • coffee-rails (4.0.1)

  • coffee-script (2.2.0)

  • coffee-script-source (1.7.0)

  • jbuilder (1.5.3)

  • jquery-rails (3.1.0)

  • rails (4.0.2)

  • railties (4.0.2)

  • sass (3.2.19)

  • sass-rails (4.0.3)

  • sprockets (2.11.0)

  • sprockets-rails (2.0.1)

  • turbolinks (2.2.2)


My JavaScript files are working ok; I tried similar type of function in JavaScript and it was ok.



asked 29 secs ago

jyrkim

121





Joomla 2.5 jroute trouble with localhost


Vote count:

0




I wrote a component and i have trouble using jroute for building links


Example : In my default tmpl in admin part,


if use $link = ''.JRoute::_( 'index.php?option=' . $option . '&task=tournoi.edit&id=' . $row->tournois_id );


or $link = JRoute::_( 'index.php?option=' . $option . '&task=tournoi.edit&id=' . $row->tournois_id );


i get



http://joomla_new/administrator/index.php?option=com_tournois&task=generatereport&tid=1" where localhost is missing.


if i just add space like this : $link = ' '.JRoute::_( 'index.php?option=' . $option . '&task=tournoi.edit&id=' . $row->tournois_id );


i get



http://localhost/%20/Joomla_new/administrator/index.php?option=com_tournois&task=tournoi.edit&id=1


Anyone has an idea ?


Thanks !



asked 39 secs ago






Using a keyword as member name in F#


Vote count:

0




Does F# allow defining a member with the name of a keyword?



type Fruit =
val type : string


in C# this is possible using @:



class Fruit
{
string @type;
}


asked 31 secs ago

citykid

1,702





how to get privileges for local infile command in mysql


Vote count:

0




My script was working fine on localhost. However, when I uploaded it to my site, it turned out that I had no privileges for local infile variable. When I look it in PhpMyadmin, it shows "off" and I cannot edit it unlike localhost phpMyadmin. I tried to set this variable by SQL query as well as by PHP, but both times, it gave error that I was lacking SUPER privilege.


I searched the issue and found that one way of doing it is to have SUPER privilege. However, when I create a user in cpanel and assign it to a database, the cpanel gives me a list of privileges, but no option of SUPER privilege.


I really want to use this command. Please tell me what to do.



asked 52 secs ago






Can't install Bluecloth 2.2.0 gem in windows 7


Vote count:

0




When Running bundle install i am getting below error.


Note: I also tried gem install bluecloth --platform=ruby but same problem.



Gem::Installer::ExtensionBuildError: ERROR: Failed to build gem native extension.

C:/Ruby200/bin/ruby.exe extconf.rb
checking for srand()... yes
checking for random()... no
checking for rand()... yes
checking for bzero() in string.h,strings.h... no
checking for strcasecmp()... yes
checking for strncasecmp()... yes
checking for mkdio.h... yes
checking for ruby/encoding.h... yes
creating extconf.h
creating Makefile

make "DESTDIR="
generating bluecloth_ext-i386-mingw32.def
compiling bluecloth.c
In file included from c:\devkit\mingw\bin\../lib/gcc/i686-w64- mingw32/4.7.2/../../../../i686-w64-mingw32/include/windows.h:59:0,
from c:\devkit\mingw\bin\../lib/gcc/i686-w64-mingw32/4.7.2/../../../../i686-w64-mingw32/include/winsock2.h:23,
from c:/Ruby200/include/ruby-2.0.0/ruby/win32.h:40,
from c:/Ruby200/include/ruby-2.0.0/ruby/defines.h:153,
from c:/Ruby200/include/ruby-2.0.0/ruby/ruby.h:70,
from c:/Ruby200/include/ruby-2.0.0/ruby.h:33,
from bluecloth.h:14,
from bluecloth.c:25:
c:\devkit\mingw\bin\../lib/gcc/i686-w64-mingw32/4.7.2/../../../../i686-w64-mingw32/include/windef.h:113:23: error: duplicate 'unsigned'
c:\devkit\mingw\bin\../lib/gcc/i686-w64-mingw32/4.7.2/../../../../i686-w64-mingw32/include/windef.h:113:23: error: two or more data types in declaration specifiers
c:\devkit\mingw\bin\../lib/gcc/i686-w64-mingw32/4.7.2/../../../../i686-w64-mingw32/include/windef.h:114:24: error: duplicate 'unsigned'
c:\devkit\mingw\bin\../lib/gcc/i686-w64-mingw32/4.7.2/../../../../i686-w64- mingw32/include/windef.h:115:23: error: duplicate 'unsigned'
make: *** [bluecloth.o] Error 1


Gem files will remain installed in C:/Ruby200/lib/ruby/gems/2.0.0/gems/bluecloth-2.2.0 for inspection.
Results logged to C:/Ruby200/lib/ruby/gems/2.0.0/gems/bluecloth-2.2.0/ext/gem_make.out
An error occurred while installing bluecloth (2.2.0), and Bundler cannot


continue.


Make sure that gem install bluecloth -v '2.2.0' succeeds before bundling.


Process finished with exit code 5


....................................................................


Gemfile



source 'http://rubygems.org'
ruby "2.0.0"

## Bundle rails:
gem 'rails', '4.0.4'
gem 'pg'
gem 'uglifier', '>= 1.3.0'
gem 'sass-rails', '~> 4.0.0'

gem 'actionpack-page_caching'
gem "activemerchant", '~> 1.29.3'#, :lib => 'active_merchant'
gem "american_date"

# Use https if you are pushing to HEROKU
## NOTE: run the test before upgrading to the tagged version. It has had several deprecation warnings.
gem 'authlogic', github: 'binarylogic/authlogic', ref: 'e4b2990d6282f3f7b50249b4f639631aef68b939'
#gem 'authlogic', "~> 3.3.0"

gem "asset_sync"
gem 'awesome_nested_set', '~> 3.0.0.rc.1'

gem 'aws-sdk'
gem 'bluecloth', '~> 2.2.0'
gem 'cancan', '~> 1.6.8'
gem 'chronic'
# Use https if you are pushing to HEROKU
gem 'compass-rails', git: 'http://ift.tt/1wFWv21'
#gem 'compass-rails', git: 'git://github.com/Compass/compass-rails.git'


gem 'dynamic_form'
gem 'jbuilder'
gem "friendly_id", '~> 5.0.1'#, :git => "git@github.com:FriendlyId/friendly_id.git", :branch => 'rails4'
gem "jquery-rails"
gem 'jquery-ui-rails'
gem 'json', '~> 1.8.0'

#gem "nifty-generators", :git => 'git://github.com/drhenner/nifty-generators.git'
gem 'nokogiri', '~> 1.6.0'
gem 'paperclip', '~> 3.0'
gem 'prawn', '~> 0.12.0'

gem "rails3-generators", "~> 1.0.0"
#git: "http://ift.tt/1wFWsU1"
gem "rails_config"
gem 'rmagick', :require => 'RMagick'

gem 'rake', '~> 10.1'

# gem 'resque', require: 'resque/server'

gem 'state_machine', '~> 1.2.0'
#gem 'sunspot_solr', '~> 2.0.0'
#gem 'sunspot_rails', '~> 2.0.0'
gem 'will_paginate', '~> 3.0.4'
gem 'zurb-foundation', '~> 4.3.2'

group :production do
#gem 'mysql2', '~> 0.3.12'
gem 'rails_12factor'
end

group :development do
#gem 'sqlite3'

gem 'railroady'
#gem 'awesome_print'
#gem 'annotate', :git => 'git://github.com/ctran/annotate_models.git'
gem "autotest-rails-pure"
gem "better_errors", '~> 0.9.0'
gem "binding_of_caller", '~> 0.7.2'
gem 'debugger'#, '~> 1.6.1'
gem "rails-erd"

# YARD AND REDCLOTH are for generating yardocs
gem 'yard'
gem 'RedCloth'
end
group :test, :development do
gem 'capybara', "~> 1.1"#, :git => 'git://github.com/jnicklas/capybara.git'
gem 'launchy'
gem 'database_cleaner', "~> 1.2"
end

group :test do
gem 'factory_girl', "~> 3.3.0"
gem 'factory_girl_rails', "~> 3.3.0"
gem 'mocha', '~> 0.13.3', :require => false
gem 'rspec-rails-mocha'
gem 'rspec-rails', '~> 2.12.2'

gem 'email_spec'
gem "faker"

end


asked 35 secs ago






Custom view that show text and wrapping content


Vote count:

0




I have a custom view that write text and I wish to know how to deal with height wrap content.


Questions:


1) When to calculate the height of the text? In the OnMeasure?


2) What if the text height will be too large to fit in any view, in the onDraw() should I keep drawing the whole text lines? will that be inefficient to have lots of text be drawn though it wont appear any way?


3) Considering point 2 what if this custom view is put in a ScrollView? how efficient will that be? or should I handle scrolling manually in my view?



asked 33 secs ago






Django Project Model Layout (how should this be done?)


Vote count:

0




So my project has several divisions: - sales division - security division - explorer division


now obviously they have fields that are common, for example name, gender etc. after reading some forums, i think i can do this either:



  1. Create a main app which contains all field and reference them from other apps.

    • I think the advantage here is that, for example sales app would only need the main app to work.



  2. Create a single app which contains different classes.

    • This would be easy but I don't know how to separate them because the sales division should only access sales and not security.



  3. Create an app for each

    • It would make them independent and would work separately but fields would be repeated and would not have any relationships.




Thoughts are VERY welcome.



asked 1 min ago






Silverstripe 3, ProductCatalog - friendly URL and Sub Categories


Vote count:

0




I am creating a product catalog using this Silverstripe Module:


http://ift.tt/1pGDXKk Which is based on this module http://ift.tt/1pGDYxY


I have an issue that friendly URLs are appearing as: http://ift.tt/1pGDXKm1 or http://ift.tt/1rtblbZ1/1 as apposed to their title or url segment. http://ift.tt/1rtblbZmy-category/my-product


I've tried changing the code from Product.php to



//Return the link to view this category
public function Link() {
$Action = 'show/' . $this->ID . '/' . $this->URLSegment;
return $Action;
}


from



//Return the link to view this category
public function Link() {
$Action = 'show/' . $this->ID . '/' . $this->CategoryID;
return $Action;
}


Which works, but not for the category titles and is the url has spaces it generates %20 instead of _.


It seems like a simple change which I can't work out..




I also want to be able to have sub-categories. So everything in a category can be divided into say their "Size". At present All products are divided just once. Products > Categories I would like Products > Categories > Sub-Categories can any one help me achieve this? thanks



asked 20 secs ago






how to Uploading photos with comment Instagram via our own iOS app?


Vote count:

0




is it possible to Uploading photos with comment Instagram via our own iOS app ???


my codding is :



NSURL *fileURL = [NSURL fileURLWithPath:[self photoFilePath]];
documentInteractionController = [UIDocumentInteractionController interactionControllerWithURL:fileURL];
documentInteractionController.UTI = @"com.instagram.exclusivegram";
documentInteractionController.delegate = delegate;
documentInteractionController.annotation = [NSDictionary dictionaryWithObject:caption forKey:@"InstagramCaption"];
[documentInteractionController presentOpenInMenuFromRect:CGRectZero inView:view animated:YES];


If it's possible then plz give me solution...


thanx.....



asked 1 min ago






how to refresh page and keep pnotify


Vote count:

0




I made a POST form and i send data via ajax.and I use PNotify for alert the problem is how i refresh the page and keep the notify box.Or how I redirect the user after submit button to another page and notify box to remain? i try to put location.reload() in succes: function but not work...the notify is not displayed.



<script type="text/javascript">
var frm = $('#editticket');
frm.submit(function (ev) {
$.ajax({
type: frm.attr('method'),
url: frm.attr('action'),
data: frm.serialize(),
success: function (data) {
new PNotify({
text: 'Task edited.',
type: 'info',
hide: false
});
}
});

ev.preventDefault();
});
</script>


asked 20 secs ago






JAVA: How to remove duplicate values in a print array?


Vote count:

1




I have two methods, one method responsible for taking user input values (just numbers), for example:


The user inputs:



Enter a number: 76
Enter a number: 45
Enter a number: 45
Enter a number: 34
Enter a number: 32
Enter a number: 32
Enter a number: 32
Enter a number: 6
Enter a number: 7
Enter a number: 8
... etc


I then have another method with an array in it to display the output of what was just entered.



You entered: 76, 45, 45, 34, 32, 32, 32, 6, 7 ,8... etc


I want just each number to be shown once, example:



You entered: 76, 45, 34, 32, 6, 7 ,8... etc


How do I do this?



asked 52 secs ago


2 Answers



Vote count:

0




Use a Set. Those will only contain unique values.



answered 22 secs ago



Vote count:

0




Convert the array you have into a set which will get rid of duplicates and print.


E.g.



Integer[] values = {1, 2, 3, 3, 3, 4, 5, 5, 5};

Set<Integer> valueSet = new HashSet<Integer>(Arrays.asList(values));

for(int value : valueSet) {
System.out.println(value);
}


Hope it helps.



answered 10 secs ago





-[UITableView _configureCellForDisplay:forIndexPath:], /SourceCache/UIKit_Sim/UIKit-2935.137/'


Vote count:

0




I am using storyboard and I had provide different cell identifier to all prototype cells.But still got this error.I found some results on stack overflow but they did not work for me.Any Help will be appreciated Thanks..



asked 20 secs ago






How do I print the values of hashsets that are saved in a file in ruby


Vote count:

0




well I have file(named ter.txt) that contains the hashsets below as content ;



{"qty"=>"gfg", "unit"=>"gfg", "item"=>"xcv", "cost"=>"0.0", "salestax"=>"0.0"}
{"qty"=>"gdf", "unit"=>"g", "item"=>"gg", "cost"=>"0.0", "salestax"=>"0.0"}


i want to print the values of the above hashsets.I tried doing the following but i got an error of undefined local variable or method 'item'



file = File.open('ter.txt', 'r').map { |line| line.split("\n")[0] }


file.each do |hash|
p hash
p " #{hash[item]}"
end


asked 1 min ago






Recent Questions - Stack Overflow

Do you have to read books?


Vote count:

-1




I've been reading books for programming in C and C++ over the course of two years, but I've always stopped because everything I read makes sense for a while, but then as I get more in-depth with the book(s), I loose the ability to understand what is being said because everything is written very complex and not easy to understand. Right now I'm reading "Programming in C by Kochan" which indeed is a good book, but I don't feel I achieve a full understanding of the language by reading it.


Today, I looked up on the internet to find out what people had to say about this problem and I inquired that most programmers doesn't read books, they just program. That stroke my mind, I couldn't believe that they just programmed to learn. I was wondering if it is absolutely true that you have to read a book? Personally I find watching lectures or courses on programming a lot easier, but will it work the same way? I'm wondering if any of you SO users have had the same problem, were you don't feel like you achieve anything by reading a book or that you don't understand it completely and give up? Is watching videos a good way to learn? When I watch programming videos it feels like I'm being tutored like I would be in class.


Give me some opinions, I've been so crazy about learning to program, I've been going on and off for 3 years but I've never held on to it because it's simply confusing at times.


Regards, Oliver



asked 1 min ago






lex parser to programs written in pascal


Vote count:

0




I have a problem with writing Pascal analyzer using Lex, which after parsing should print to stdout information about the correct / incorrect code structure and a summary containing the number of rows of the program, the number of variables used, the number used in an if, while, repeat, etc.


I do not know how to go about it.



asked 49 secs ago






Convert Assembly To Dynamic Assembly in VB.net


Vote count:

0




Please help me, I want to convert an assembly to dynamic assembly.


I have tried but did not find any answer. Tell me please



asked 1 min ago






tcltk block input while processing in r


Vote count:

0




RGTK2 block user input while processing its explain how to block user input using RGTK2 but I dont know how to add that code to my GUI code, im using tcltk. What I want same like in RGTK2 block user input while processing but using tcltk2


I use this code to run button "filter cluster" and the command function is filter (function to do something)



tkpack(tkbutton(f4, text='Filter Cluster', command=filter), side='left',padx= 5, pady = 20)


asked 10 secs ago






RGtk2 - opening graphics files fails


Vote count:

0




I am working through the JSS article 'RGtk2: A graphical user interface for R' and I am trying to read in a graphics file using approximately the script from the article:



image<-gdkPixbuf(filename= imagefile("D:/My pictures/Business images/ja_logo.gif"))[[1]]
window$set(icon=image, title="Hello world 1.0" )


However, desipte trying out a variety of graphics files in different locations I invariably receive the following:



> image<-gdkPixbuf(filename= imagefile("D:/My pictures/Business images/Call centre.jpg")) [[1]]
Warning message:
In gdkPixbufNewFromFile(filename, .errwarn) :
Failed to open file '': Invalid argument


I have tried using files in the working directory and those with complete paths, but am getting nowhere. Am I missing something embarrassingly obvious or is there a problem with the package?



asked 8 secs ago






Same xml load on multiple button click in Android


Vote count:

0




I have multiple button in Main Activity, and on every button click same xml is loaded like "test.xml" with dynamic data. The "test.xml" which I loaded on every click contain five more buttons and for every click of "test.xml" buttons I again want to load same xml,i.e, "test.xml" with different data. How I acheive this task.


Please help me for the same.


Any help is appreciated. Thanks in advance.



asked 59 secs ago






CKEditor's autogrow event not firing


Vote count:

0




I am using CKEditor 4.4.1 built using the builder on the website with the autogrow plugin in inline mode.


CKEDITOR.disableAutoInline is set to true. CKEDITOR.config.autoGrow_onStartup is also set to true.


I then proceed to inline a contenteditable like so:



var editor = Y.one('...'); //Get the contenteditable using YUI.

var ckEditor = CKEDITOR.inline(editor.getDOMNode());

ckEditor.on('instanceReady', function(e){
console.log(e);
}, this);

ckEditor.on('autogrow', function(e){
console.log(e);
});


I can confirm that the autogrow works properly and the inlined contenteditable expands when required. The instanceReady event also fires.


However, the autogrow event never fires when the contenteditable expands or shrinks.


What could be causing this problem?



asked 19 secs ago

F21

7,045





vendredi 30 mai 2014

Accessing the Omniauth Builder created in an initializer to create an access token


Vote count:

0




I'm writing a little app for Coinbase and I'm making an initializer that I've thrown in omniauth.rb



Rails.application.config.middleware.use OmniAuth::Builder do
provider :coinbase, ENV["COINBASE_CLIENT_ID"], ENV["COINBASE_CLIENT_SECRET"], scope: "sell send transfers user"
end


I want to be able to access this anywhere in my app so that I can create an access_token for the user. Based on their docs and the research I've done into Omniauth, I'm not quite sure how to do this.


Should I throw an instance variable and an = in front of the code posted above? Is that a correct solution? Also, how do I go about getting an access_token after initializing this?


Thanks!



asked 30 secs ago






Does not show shortest path - networkx QGIS


Vote count:

0




I used the following commands (in qgis console) to get the shortest path with astar algorithm. But the result shows just '[]' every time. Why was that? Please help me to find a solution to this problem.



>>> import networkx as nx
>>> G = nx.read_shp(str(iface.mapCanvas().currentLayer().source()))
>>> route = nx.shortest_path(G, G.nodes()[1], G.nodes()[10])
[]
>>> route = nx.shortest_path(G, G.nodes()[20], G.nodes()[30])
[]


asked 2 mins ago

Dil

6





Why is Console.WriteLine speeding up my application?


Vote count:

0




Ok so this is kind of weird. I have an algorithm to find the highest possible numerical palindrome that is a multiple of two factors who each have K digits.


The method I'm using to find the highest valid palindrome is to look at the highest possible palindrome for the number set (i.e. if k=3, the highest possible is 999999, then 998899, etc). Then I check if that palindrome has two factors with K digits.


For debugging, I thought it would be a good idea to print to the console each of the palindromes I was checking (to make sure I was getting them all. To my surprise, adding



Console.WriteLine(palindrome.ToString());


to each iteration of finding a palindrome dropped my runtime a whopping 10 seconds from ~24 to ~14.


To verify, I ran the program several times, then commented out the Console command and ran that several times, and every time it was shorter with the Console command.


This just seems weird, any ideas?


Here's the source if anyone wants to take a whack at it:



static double GetHighestPalindromeBench(int k)
{
//Because the result of k == 1 is a known quantity, and results in aberrant behavior in the algorithm, handle as separate case
if (k == 1)
{
return 9;
}


/////////////////////////////////////
//These variables will be used in HasKDigitFactors(), no need to reprocess them each time the function is called
double kTotalSpace = 10;

for (int i = 1; i < k; i++)
{
kTotalSpace *= 10;
}

double digitConstant = kTotalSpace; //digitConstant is used in HasKDigits() to determine if a factor has the right number of digits

double kFloor = kTotalSpace / 10; //kFloor is the lowest number that has k digits (e.g. k = 5, kFloor = 10000)

double digitConstantFloor = kFloor - digitConstant; //also used in HasKDigits()

kTotalSpace--; //kTotalSpace is the highest number that has k digits (e.g. k = 5, kTotalSpace = 99999)

/////////////////////////////////////////


double totalSpace = 10;

double halfSpace = 10;

int reversionConstant = k;

for (int i = 1; i < k * 2; i++)
{
totalSpace *= 10;
}

double floor = totalSpace / 100;

totalSpace--;


for (int i = 1; i < k; i++)
{
halfSpace *= 10;
}

double halfSpaceFloor = halfSpace / 10; //10000

double halfSpaceStart = halfSpace - 1; //99999

for (double i = halfSpaceStart; i > halfSpaceFloor; i--)
{
double value = i;
double palindrome = i;
//First generate the full palindrome
for (int j = 0; j < reversionConstant; j++)
{
int digit = (int)value % 10;

palindrome = palindrome * 10 + digit;

value = value / 10;
}

Console.WriteLine(palindrome.ToString());
//palindrome should be ready
//Now we check the factors of the palindrome to see if they match k
//We only need to check possible factors between our k floor and ceiling, other factors do not solve
if (HasKDigitFactors(palindrome, kTotalSpace, digitConstant, kFloor, digitConstantFloor))
{
return palindrome;
}
}


return 0;
}

static bool HasKDigitFactors(double palindrome, double totalSpace, double digitConstant, double floor, double digitConstantFloor)
{
for (double i = floor; i <= totalSpace; i++)
{
if (palindrome % i == 0)
{
double factor = palindrome / i;
if (HasKDigits(factor, digitConstant, digitConstantFloor))
{
return true;
}
}
}
return false;
}

static bool HasKDigits(double value, double digitConstant, double digitConstantFloor)
{
//if (Math.Floor(Math.Log10(value) + 1) == k)
//{
// return true;
//}
if (value - digitConstant > digitConstantFloor && value - digitConstant < 0)
{
return true;
}

return false;
}


Note that I have the Math.Floor operation in HasKDigits commented out. This all started when I was trying to determine if my digit check operation was faster than the Math.Floor operation. Thanks!


EDIT: Function call


I'm using StopWatch to measure processing time. I also used a physical stopwatch to verify the results of StopWatch.



Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
double palindrome = GetHighestPalindromeBench(6);
stopWatch.Stop();

TimeSpan ts = stopWatch.Elapsed;

string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}:{3:00}", ts.Hours, ts.Minutes, ts.Seconds, ts.Milliseconds / 10);

Console.WriteLine();
Console.WriteLine(palindrome.ToString());
Console.WriteLine();
Console.WriteLine(elapsedTime);





asked 14 mins ago