samedi 28 février 2015

Create a main method to run the below code


I'd like to call the below method and run the code:



public class Test01{
public interface Printable{
public void print();
}
public class PrintRectangle implements Printable{
public void print(){
System.out.println("Rectangle");
}
}




I want e-books related to programming


I am new in programming world! .


I want e-books related to JAVA , and C#.net .


Best Regards,


Abdulaziz.





What is wrong with this program?


Something is wrong with this PRNG, it uses a large (65536 bit) pool of bits from which randomness is extracted in sets of 256 bits, what seems to fail is the bit storage feature (ests,sts,lts,elts) which is meant to store randomness from each stage and mix it back in later. It starts with a seed (l) and in every stage: 1) passes l through the mixing function (m) 2) takes some bits from storage and sends others into storage 3) passes l through the mixing function (m) 4) takes a copy of l, then tweaks the copy (t), mixes it (m) and squeezes bits out of it There are 4 storage lists: 1) ests (extra short term storage) takes blocks of 3840 bits and keeps them for 16 stages. 2) sts (short term storage) takes blocks of 240 bits and keeps them for 256 stages. 3) lts (long term storage) takes blocks of 15 bits and keeps them for 4096 stages. 4) elts (extra long term storage) takes blocks of 1 bit and keeps them for 61440 stages. The mixing function (m) works by running the list through 256 stages each consisting of of 256 steps of rule 30 followed by writing the list in 256 rows and reading it in columns.


m[x_] := Nest[ Flatten[Transpose[ Partition[Flatten[CellularAutomaton[30, #, {{256, 256}}]], 256]]] &, x, 256] t[x_] := 1 - x s[x_] := Table[Mod[Total[Partition[x, 256][[i]]], 2], {i, 1, 256}] f[list_, store_, a_, b_] := {Join[list[;; a - 1], store[[;; (b - a) + 1]], list[[b + 1 ;;]]], Join[Drop[store, (b - a) + 1], list[[a ;; b]]]} l = Normal[SparseArray[{1}, 65536]]; k = {}; ests = Normal[SparseArray[{}, 61440]]; sts = Normal[SparseArray[{}, 61440]]; lts = Normal[SparseArray[{}, 61440]]; elts = Normal[SparseArray[{}, 61440]]; Do[l = m[l]; {l, ests} = f[l, ests, 61441, 65280]; {l, sts} = f[l, sts, 65281, 65520]; {l, lts} = f[l, lts, 65621, 65535]; {l, elts} = f[l, elts, 65536, 65536]; l = m[l]; AppendTo[k, s[m[t[l]]]], {256}]





Bad sign if nobody can comprehend one's code?


If a coder writes code that nobody other than he can understand, and code reviews always end with the reviewer scratching his head or holding their head in their hands, is this a clear sign that the coder is simply not cut-out for professional programming? Would this be enough to warrant a career change? How important is comprehensible code in this industry?


Consider these C examples, compare:



if (b)
return 42;
else
return 7;


versus:



return (b * 42) | (~(b - 1) * 7);


Is there ever an excuse to employ the latter example? if so, when and why?





Pipeline-like calculations with intermediate files: should I use a build system?


I have seen multiple examples of systems that are organized essentially like a pipeline. Each stage produces some intermediate files which are then consumed by the next stage. Also, these take a long time and contain custom code, shell scripts and everything else imaginable (as opposed to everything neatly written in programming language X).


Question: how does one develop / organize such a thing?


It feels like we could be using a build system, but in our case it's the code of the stages that is changing, not the actual input. So it'd be nice if I could choose what to rerun. E.g. if the project is about mirroring a website and extracting its contents, I don't want to wget everything just because I changed the later processing code a bit... but re-downloading the entire thing is still something we might consider later. Build systems usually do not give such a level of manual control. (Also, they are rarely capable of keeping track of what outputs depend on what units of code specifically.)


The other end is having a shell script with a single parameter specifying the stage to run. It's completely manual, reliable, but not especially convenient.


I was wondering whether this is a class of problem that exists elsewhere, and if yes, what kind of tool / framework do people use to solve it?





Good opensource easy to install website for displaying food


My buddy started his business in the "Food" industry after finishing his cooking school. He asked me if I can help him by creating a website to display his sample dishes. I wanted to help him and create a website but I figured he is better off doing the uploads/updates by himself. I wanted to download an opensource website for him to display his foods. I will be installing the website to my VPS for the time being.


What would be the best opensource site for displaying Products. I was considering Prestashop and removing the shopping feature. I would like it to be simple for him because he only started using computer because of facebook. And I think it would be best for him to have a click upload style to display his dishes.


If this post shouldnt be here/if I should ask google instead, please do close/move this post. Thanks.





My trying to make the program decrement every 1 second. It keeps printing 99. What did I do wrong?



# SimpleGUI program template

# Import the module
import simplegui

# Define global variables (program state)
countdown = 100
# Define "helper" functions
def blast_off():
global countdown
countdown = 100 - 1
print countdown

# Define event handler functions


# Create a frame

# Register event handlers
timer = simplegui.create_timer(1000,blast_off)
# Start frame and timers
timer.start()




Hypothetical : What restrictions will I need to add to Java so that I can remove its GC?


This is a hypothetical, yet very technically precise question I'm trying to ask all the compiler/static analysis programmers.


I'm trying to understand the extent of prohibitive features I would need to add to the language such that it is still a Java program, i.e. it could run inside any JVM with the same semantic meaning (i.e. the GC or no GC doesn't change the semantics), and then also run in my special scenario.


I'm asking this because I've a developer in a large team (>200 people) developing a pretty large web application, and it's all dependency injection based. I've been a C++ developer all my life, and this change (to java) has been surprisingly poor, except for the silver lining of dependency injection stuff and peculiar thing that happens in the codebase I work on.


In this particular codebase, they use the java compiler, and then they have another sort-of compiler that annotates the source code with ownership details of the objects being passed from function to function.



foo(someType a); // @_@_move_semantic_@_@


I've modified the notation (for obvious reasons), but it does it after every commit, a few minutes later. Our application takes a few minutes to compiler by javac.


I then inquired about this and was told that the previous engineering lead developer was this guy who had a vision of removing the GC from their codebase, which never materialized.


I understand what he was doing was "Escape Analysis", but beyond that I'm sure some restrictions need to be added to the code? What would they be?


Special method names? All exits from a function require some reference count call?


I'm looking for a pretty precise or theoretical treatise ... or pointers to some papers or research (I know about the Mercury language, but it's only stack based)





Can someone help with a Swift / Xcode error code [on hold]


I am trying to submit an app to the app store (first time), had both iTunes connect and Xcode open at the same time trying to get profiles and certificates back and forth, and downloaded. At one point I notice


Apple Mach-O Linker Error Linker command failed with exit code 1


in the left pane. What did I do, and how can I fix it. I had the app working on both my iPhone and iPad but now it will not even build. Please help I am looking at lots of work out the window.





C++ ORM - but the other way


After days of searching and studying and making my brain wired I will try to put my thoughts and "questions" here.


I think that there are millions of reasons for using ORM tools like ODB (together with C++).


BUT for me and a some business projects I sometimes want to have a fixed database table layout (which sometimes comes from other people / gets defined by the customer) and I have to "wrap" around them with my C++ classes.


My primary question is: Are there any "ORM" tools that are going the other way than ODB & Co? I mean tools that are automatically generating C++ classes by analyzing the existing database tables' structure(s) and writing header and source files (for the classes)?


I know that this would be (is :-) ) a very simplistic approach because it does not provide any non-simple database driven things like 1-to-many or many-to-many relationships, but in 99% of all cases for me an exact match of database table to C++ class would be perfect.


Does anyone of you have a good recommendation? Or any good advice for doing it this way? Or any hints NOT to do that?





Algorithm or domain for finding cheapest subgraphs that connect vertex pairs


I am currently working on a project inspired by the Ticket to Ride board game. This board game is played on an undirected graph where each vertex represents a city and each edge represents a claimable train line connecting two cities. Players get points by claiming an edge for themselves, scoring points based upon how many cars the route requires to claim. There are also tickets that give bonus points if the player is able to claim a path that connects the two cities. Each player has only 45 cars, so this is a resource allocation problem.


I am trying to write a program that helps agents (humans or AIs) plan which routes to take based upon which tickets that agent needs to complete, which routes the agent has already claimed, and which routes are unavailable due to other players having claimed them. I need an algorithm that finds a set of subgraph(s) such that each ticket has its city in the same subgraph while trying to optimize some criteria (minimum car usage, maximum points per car, etc.). I do not care whether the algorithm gets all the cities in one subgraph, or whether it strings them all out in a line without branching (which would help toward getting the Longest Route bonus); I want something that enables the agent to complete the tickets quickly so he can start working on new ones.


The problem is that I do not have enough familiarity with graph theory to know the name for this type of problem. I have tried searches with text that describes what I am trying to do with no luck. I have also looked in my old textbooks (Introduction to Algorithms and Algorithms in C: Part 5 - Graph Algorithms) to try to find a graph problem domain that seems to relate to my issue; the closest seems to be network flow, but that does not seem to be close enough.


I have tried solving this problem on my own. I wrote an A* that scored each set of subgraphs based upon the estimated minimum distance to a node, but it did not work (as I would have discovered if I had read the Wikipedia article on A* first). I wrote an NSGA-II implementation to try to solve the problem stochastically, but it oddly seems to do worse the closer the initial set of owned edges is to connecting the tickets. In fact, the NSGA-II implementation "freaks out" and finds very strange routes to connect subgraphs when only one route that earlier calls to the algorithm recommended.


Could someone either tell me the name of this domain so I can start doing research, point me to an algorithm, or propose an algorithm that I could try?





Single method with many parameters vs many methods that must be called in order


I have some raw data I need to do many things to (shift it, rotate it, scale it along certain axis, rotate it to a final position) and I am not sure what the best way to do this to maintain code readability. On one hand, I can make a single method with many parameters (10+) to do what I need, but this is a code reading nightmare. On the other hand, I could make multiple methods with 1-3 parameters each, but these methods would need to be called in a very specific order to get the correct result. I have read that it is best for methods to do one thing and do it well, but it seems like having many methods that need to be called in order opens up code for hard-to-find bugs.


Is there a programming paradigm I could use that would minimize bugs and make code easier to read?





Protect memory from a potentially seg faulting function call


How can one safely call a function that might segfault without corrupting the stack or the heap?


These SO questions cover using signal handlers and setjmp.h to regain control.


Coming back to life after Segmentation Violation


Best practices for recovering from a segmentation fault


They neglect the likely memory corruption that occurs prior to a seg fault.


What strategies can be used to isolate the memory space of a function and its caller?


This is just a curiosity question, there's no specific problem I'm trying to solve. Let's just suppose we're programming something that absolutely cannot crash -- pacemaker, Mars orbiter, nuclear launch control, take your pick. We've already thoroughly unit tested all our code and formally proven its correctness. For bureaucratic reasons we have to use C++ and Linux.


I was trying to sketch this out with clone(). My idea was to run the function with as much isolation as possible and pass data back and forth by squirreling it away at the bottom of the child's stack.


Is that reasonable or is there a better way to do this?





raw, weak_ptr, unique_ptr, shared_ptr etc... how to choose them wisely


There is a lot of pointers in C++ but to be honest in 5 years or so in c++ programmation (specifically with the Qt Framework) I only use the old raw pointer :



SomeKindOfObject *someKindOfObject = new SomeKindOfObject();


I know there is a lot of other "smart" pointers :


shared pointer



shared_ptr<SomeKindofObject> Object;


unique pointer:



unique_ptr<SomeKindofObject> Object;


weak pointer



weak_ptr<SomeKindofObject> Object;


But I don't have the slightest idea of what to do with them and what they can offer me in comparison of raw pointers.


For example I have this class header :



#ifndef LIBRARY
#define LIBRARY

class LIBRARY
{
public:
QList<ItemThatWillBeUsedEveryWhere*> listOfUselessThings; //Permanent list that will be updated from time to time where each items can be modified everywhere in the code
private:
QSettings *_reader //temporary reader that will read something to put in the list and be quickly deleted;
QDialog *_dialog; //dialog that will show something (just for the sake of example)

};

#endif


This is clearly not exhaustive but for each of these 3 pointers is it ok to leave them "raw" or should I use something more appropriate ?


And in the second time, if an employer will read the code, will he be strict on what kind of pointers I use or not ?


Thanks PS: I have no idea if I should've put it in Programmes or StackOverflow





How to Enable Suggestions on Visual Studio 2010


I Want to enable the suggestions Like This.... PLEASE HELP !enter image description here





Where is the error in this python3.x code? [on hold]


I'm working on homework for my Concepts of Programming class, and here's my code thus far: http://ift.tt/1vLaOFj Python gives the following error message:



Traceback (most recent call last): File "C:/Users/Corey/Documents/Documents/python/cpFunctionsHW.py", line 14, in print("The area of a square with sides of length 10.3 is ", squareArea(10.3)) File "C:/Users/Corey/Documents/Documents/python/cpFunctionsHW.py", line 13, in squareArea return rectangleArea(length, length) TypeError: 'float' object is not callable



The code successfully executes up to line 11 and says the error is at line 14, but this visualizer: http://ift.tt/1EWGnMf Tells me that the problem is at line 6. Furthermore, altering lines 6 and 7 as such:



rectangleLength = int(input("What is the length of your rectangle? "))


rectangleWidth = int(input("What is the width of your rectangle? "))



gives the following error:



Traceback (most recent call last): File "C:/Users/Corey/Documents/Documents/python/cpFunctionsHW.py", line 14, in print("The area of a square with sides of length 10.3 is ", squareArea(10.3)) File "C:/Users/Corey/Documents/Documents/python/cpFunctionsHW.py", line 13, in >squareArea return rectangleArea(length, length) TypeError: 'int' object is not callable



This has left me utterly baffled, so I'm hoping you guys can help.





Switching To Agile For Mainframe


Our company is discussing whether to change from waterfall to agile for mainframe development. Which agile method would suit best for mainframe development? Has someone experience with the switch, what needs to be arranged/done?





Bewildered: programming for the real world [on hold]


I'm currently working as a iOS developer. Before that I worked as a full stack web developer (JS, Ruby) while also maintaining the servers (linux). When I started out years ago I did a little game programming in C++. I'm verse in C, Objective-C, Swift, Ruby, JS, PHP, Bash, Go, Haskell. I have leaned towards functional programming while learning Haskell for the last couple of years, after have been doing mostly OOP before that.


I would say I have been around the block. But what is slowly creeping up my shoulders is the thought that what does it matter when it's just behind a screen. Apps are cool because you can touch them, interact with them. Websites are cool because content and knowledge is awesome. But it's all behind a screen, and I'd wager you could find equal or better non-digital alternatives, for the most part.


I don't feel content just doing digital stuff because we can. I want to do something that I can feel (either from the effect of it, or itself). Life-changing stuff. I dunno what. Drones? Robots? AI? I dunno. But I don't feel like just keeping at doing insignificant entertainment things that only exists behind a screen.


Anyone feel the same, or do you just think something about this? Looking forward to hearing from you!





Multi layer parallax live wallpaper


I'm just starting android programming, and I'm trying to make a live wallpaper with multiple images and a parallax effect. I load the bitmaps at startup.


This is my code for offset changed:



@Override
public void onOffsetsChanged(float xOffset, float yOffset,
float xStep, float yStep, int xPixels, int yPixels)
{
this.mmPixel= (float) (xPixels * 0.8);
this.mmPixel1= (float) (xPixels * 1);
this.mmPixel2 = (float) (xPixels * 1.2);
this.mmPixel3 = (float) (xPixels * 1.5);
drawFrame();
}


and this is my code for the drawFrame:



void drawFrame()
{
if(!mVisible) return;
final SurfaceHolder holder = getSurfaceHolder();
Canvas c = null;
try
{
c = holder.lockCanvas();
if(c != null)
{
c.drawBitmap(background, mmPixel, 0, paint);
c.drawBitmap(layer1, mmPixel1, 0 , paint);
c.drawBitmap(layer2, mmPixel1, 0, paint);
c.drawBitmap(layer3, mmPixel2, 0, paint);
}
}finally
{
if(c != null) holder.unlockCanvasAndPost(c);
}

mHandler.removeCallbacks(mDrawScene);
if(mVisible)
{
mHandler.postDelayed(mDrawScene, 1000/30);
}
}


The problem that I'm running into is that I encounter serious lag with even 720p images. This is a problem when the phone I'm testing on has a 720p screen, and I want to develop for full HD screens and beyond. Is there any way to make this run faster or more efficiently?





Library design: better to leave potentially destructive feature in with a warning, or cut it out completely?


I recently created a red-black tree in C# to better understand how it works. With it, I implemented an in-order enumerator, however I quickly realized that enumerating a tree can have destructive results.


Consider this code:



RedBlackTree<Person> tree = new RedBlackTree<Person>();
tree.Add(new Person("Randy"));
// add more people
...

foreach(var person in tree)
{
if (person.Name == "Randy")
{
person.Name = "Cheeseburger eater";
}
}


The tree requires the generic parameter to implement IComparable interface, in order to correctly determine ordering of items.


If Person class is compared by name, then, by changing the name during enumeration, we might have broken the ordering. e.g. randyNode.CompareTo(randyNode.Right) < 0 might be false, which breaks the fundamental BST property, that left child is smaller than its parent and right child bigger.


In this case, is it better to remove tree enumeration altogether, or should I keep it in, with a huge warning to not modify the items during enumeration?





can some find error here given code please


I have a form and php processing to store text and image to server my problem is when I submit form and check values are stored as null even if I enter values in input box


php processing:



<?php

$db_username = 'sanoj';
$db_password = '123456';
$file1 = isset($_FILES['files']['name'][0]) ? $_FILES['files']['name'][0] : null;
$file2 = isset($_FILES['files']['name'][1]) ? $_FILES['files']['name'][1] : null;
$file3 = isset($_FILES['files']['name'][2]) ? $_FILES['files']['name'][2] : null;
$file4 = isset($_FILES['files']['name'][3]) ? $_FILES['files']['name'][3] : null;
$file5 = isset($_FILES['files']['name'][4]) ? $_FILES['files']['name'][4] : null;
$newname = md5(rand() * time());
if (isset($_FILES['files'])) {
$uploadedFiles = array();
foreach ($_FILES['files']['tmp_name'] as $key => $tmp_name) {
$errors = array();
$file_name = md5(uniqid("") . time());
$file_size = $_FILES['files']['size'][$key];
$file_tmp = $_FILES['files']['tmp_name'][$key];
$file_type = $_FILES['files']['type'][$key];

if ($file_type == "image/gif") {
$sExt = ".gif";
} elseif ($file_type == "image/jpeg" || $file_type == "image/pjpeg") {
$sExt = ".jpg";
} elseif ($file_type == "image/png" || $file_type == "image/x-png") {
$sExt = ".png";
}
if (!in_array($sExt, array('.gif', '.jpg', '.png'))) {
$errors[] = "Image types alowed are (.gif, .jpg, .png) only!";
}
if ($file_size > 2097152000) {
$errors[] = 'File size must be less than 2 MB';
}
$desired_dir = "user_data/";
if (empty($errors)) {
if (is_dir($desired_dir) == false) {
mkdir("$desired_dir", 0700); // Create directory if it does not exist
}
if (move_uploaded_file($file_tmp, "$desired_dir/" . $file_name . $sExt)) {
$uploadedFiles[$key] = array($file_name . $sExt, 1);
} else {
echo "Couldn't upload file " . $_FILES['files']['name'][$key];
$uploadedFiles[$key] = array($_FILES['files']['name'][$key], 0);
}
} else {

}
}

foreach ($uploadedFiles as $key => $row) {
if (!empty($row[1])) {
$codestr = '$file' . ($key + 1) . ' = $row[0];';
eval($codestr);
} else {
$codestr = '$file' . ($key + 1) . ' = NULL;';
eval($codestr);
}
}
}
$orig_directory = "user_data/"; //Full image folder
$thumb_directory = "thumb/"; //Thumbnail folder

/* Opening the thumbnail directory and looping through all the thumbs: */
$dir_handle = @opendir($orig_directory); //Open Full image dirrectory
if ($dir_handle > 1) { //Check to make sure the folder opened
$allowed_types = array('jpg', 'jpeg', 'gif', 'png');
$file_type = array();
$ext = '';
$title = '';
$i = 0;

while ($file_name = @readdir($dir_handle)) {
/* Skipping the system files: */
if ($file_name == '.' || $file_name == '..')
continue;

$file_type = explode('.', $file_name); //This gets the file name of the images
$ext = strtolower(array_pop($file_type));

/* Using the file name (withouth the extension) as a image title: */
$title = implode('.', $file_type);
$title = htmlspecialchars($title);

/* If the file extension is allowed: */
if (in_array($ext, $allowed_types)) {

/* If you would like to inpute images into a database, do your mysql query here */

/* The code past here is the code at the start of the tutorial */
/* Outputting each image: */

$nw = 100;
$nh = 100;
$source = "$desired_dir{$file_name}";
$stype = explode(".", $source);
$stype = $stype[count($stype) - 1];
$dest = "thumb/{$file_name}";

$size = getimagesize($source);
$w = $size[0];
$h = $size[1];

switch ($stype) {
case 'gif':
$simg = imagecreatefromgif($source);
break;
case 'jpg':
$simg = imagecreatefromjpeg($source);
break;
case 'png':
$simg = imagecreatefrompng($source);
break;
}

$dimg = resizePreservingAspectRatio($simg, $nw, $nh);
imagepng($dimg, $dest);
}
}

/* Closing the directory */
@closedir($dir_handle);
}

try {
#connection
$conn = new PDO('mysql:host=localhost;dbname=3ss', $db_username, $db_password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$data = $conn->prepare('INSERT INTO mobile (mcat, mtype, mtitle, image1, image2, image3, image4, image5, description, mmodel, modelnumber, alsoinclude, mcondition, price, youare, mname, email, phone, ylocation, ystreet) VALUES (:mcat, :mtype, :mtitle, :image1, :image2, :image3, :image4, :image5, :description, :mmodel, :modelnumber, :alsoinclude, :mcondition, :price, :youare, :mname, :email, :phone, :ylocation, :ystreet)');
$mcat = filter_input(INPUT_POST, 'mtype', FILTER_SANITIZE_STRING, FILTER_FLAG_ENCODE_AMP);
$mtype = filter_input(INPUT_POST, 'mtype', FILTER_SANITIZE_STRING, FILTER_FLAG_ENCODE_AMP);
$mtitle = filter_input(INPUT_POST, 'mtitle', FILTER_SANITIZE_STRING, FILTER_FLAG_ENCODE_AMP);
$description = filter_input(INPUT_POST, 'description', FILTER_SANITIZE_STRING, FILTER_FLAG_ENCODE_AMP);
$mmodel = filter_input(INPUT_POST, 'mmodel', FILTER_SANITIZE_STRING, FILTER_FLAG_ENCODE_AMP);
$modelnumber = filter_input(INPUT_POST, 'modelnumber', FILTER_SANITIZE_STRING, FILTER_FLAG_ENCODE_AMP);
$alsoinclude = filter_input(INPUT_POST, 'alsoinclude', FILTER_SANITIZE_STRING, FILTER_FLAG_ENCODE_AMP);
$mcondition = filter_input(INPUT_POST, 'mcondition', FILTER_SANITIZE_STRING, FILTER_FLAG_ENCODE_AMP);
$price = filter_input(INPUT_POST, 'price', FILTER_SANITIZE_STRING, FILTER_FLAG_ENCODE_AMP);
$youare = filter_input(INPUT_POST, 'youare', FILTER_SANITIZE_STRING, FILTER_FLAG_ENCODE_AMP);
$mname = filter_input(INPUT_POST, 'mname', FILTER_SANITIZE_STRING, FILTER_FLAG_ENCODE_AMP);
$email = filter_input(INPUT_POST, 'email', FILTER_SANITIZE_STRING, FILTER_FLAG_ENCODE_AMP);
$phone = filter_input(INPUT_POST, 'phone', FILTER_SANITIZE_STRING, FILTER_FLAG_ENCODE_AMP);
$ylocation = filter_input(INPUT_POST, 'ylocation', FILTER_SANITIZE_STRING, FILTER_FLAG_ENCODE_AMP);
$ystreet = filter_input(INPUT_POST, 'ystreet', FILTER_SANITIZE_STRING, FILTER_FLAG_ENCODE_AMP);
$data->execute(array(
':mcat' => $mcat,
':mtype' => $mtype,
':mtitle' => $mtitle,
'image1' => $file1,
'image2' => $file2,
'image3' => $file3,
'image4' => $file4,
'image5' => $file5,
':description' => $description,
':mmodel' => $mmodel,
':modelnumber' => $modelnumber,
':alsoinclude' => $alsoinclude,
':mcondition' => $mcondition,
':price' => $price,
':youare' => $youare,
':mname' => $mname,
':email' => $email,
':phone' => $phone,
':ylocation' => $ylocation,
':ystreet' => $ystreet
));
#exception handiling
} catch (PDOException $e) {
echo $e->getMessage();
}

function resizePreservingAspectRatio($img, $targetWidth, $targetHeight) {
$srcWidth = imagesx($img);
$srcHeight = imagesy($img);

// Determine new width / height preserving aspect ratio
$srcRatio = $srcWidth / $srcHeight;
$targetRatio = $targetWidth / $targetHeight;
if (($srcWidth <= $targetWidth) && ($srcHeight <= $targetHeight)) {
$imgTargetWidth = $srcWidth;
$imgTargetHeight = $srcHeight;
} else if ($targetRatio > $srcRatio) {
$imgTargetWidth = (int) ($targetHeight * $srcRatio);
$imgTargetHeight = $targetHeight;
} else {
$imgTargetWidth = $targetWidth;
$imgTargetHeight = (int) ($targetWidth / $srcRatio);
}

// Creating new image with desired size
$targetImg = imagecreatetruecolor($targetWidth, $targetHeight);

// Add transparency if your reduced image does not fit with the new size
$targetTransparent = imagecolorallocate($targetImg, 255, 0, 255);
imagefill($targetImg, 0, 0, $targetTransparent);
imagecolortransparent($targetImg, $targetTransparent);

// Copies image, centered to the new one (if it does not fit to it)
imagecopyresampled($targetImg, $img, 0, 0, 0, 0, $targetWidth, $targetHeight, $srcWidth, $srcHeight);

return $targetImg;
}

?>


form:



<form class="form-horizontal" method="post" action="process/mobile/mobileprocessing.php" enctype="multipart/form-data">
<fieldset>

<!-- Multiple Radios (inline) -->
<div class="form-group">
<label class="col-md-4 control-label" for="type">Type Of Ad&nbsp;&nbsp;&#10002;</label>
<div class="col-md-4">
<label class="radio-inline" for="type-0">
<input type="hidden" value="mobile" name="mcat">
<input type="radio" name="mtype" id="type-0" value="sell" >
I Want To Sell
</label>
<label class="radio-inline" for="type-1">
<input type="radio" name="mtype" id="type-1" value="buy" >
I Want To Buy
</label>
</div>
</div><br>
<div class="form-group">
<label class="col-md-4 control-label" for="textinput">Title For Your Ad&nbsp;&nbsp;<r>*</r>&nbsp;&#10002;</label>
<div class="col-md-4">
<input id="textinput" name="mtitle" type="text" placeholder="&#10002;&nbsp;&nbsp;1 Year Old Sony Xperia Neo v in Market Road at Rs.10000" class="form-control input-md">
<span class="help-block">A title more than 60 characters have 2X more sell!.</span>
</div>
</div><br>

<div id="uploa">
<div class="dis1234 lift">
<input type="file" name="files[]" multiple id="files" class="hidde fileInpu"/>
</div>
<output id="list"></output>
<div class="dis1234 rite">
<span>Don't Upload Internet Images</span>
</div>
</div><br>

<div class="form-group">
<label class="col-md-4 control-label" for="textarea">Description&nbsp;<r>*</r>&nbsp;&#10002;</label>
<div class="col-md-4">
<textarea class="form-control" id="textarea" name="description" placeholder="Description About Your Ad"></textarea>
</div>
</div><br>

<!-- Select Multiple -->
<div class="form-group">
<label class="col-md-4 control-label" for="selectbasic">Select Brand&nbsp;<r>*</r>&nbsp;&#10002;</label>
<div class="col-md-4">
<select id="dropone" name="mmodel" class="form-control">
<option>Select a Mobile Brand</option>
<option value="vodafone">Vodafone</option>
<option value="lg">LG</option>
<option value="o2">O2</option>
<option value="htc">HTC</option>
<option value="samsung">Samsung</option>
<option value="nokia">Nokia</option>
<option value="fly">FLY</option>
<option value="alcatel">Alcatel</option>
<option value="zen">Zen</option>
<option value="palm">Palm</option>
<option value="viva">Viva</option>
<option value="intex">Intex</option>
<option value="karbonn">Karbonn</option>
<option value="lava">Lava</option>
<option value="tataindicom">Tata Indicom</option>
<option value="rocker">Rocker</option>
<option value="lemon">Lemon</option>
<option value="wynncom">Wynncom</option>
<option value="virginmobile">Virgin Mobile</option>
<option value="gfive">G-Five</option>
<option value="geepee">Gee Pee</option>
<option value="inq">INQ</option>
<option value="iball">Iball</option>
<option value="airfone">AirFone</option>
<option value="acer">Acer</option>
<option value="byond">Byond</option>
<option value="beetel">Beetel</option>
<option value="sagem">Sagem</option>
<option value="toshiba">Toshiba</option>
<option value="benq">BenQ</option>
<option value="pantech">Pantech</option>
<option value="videocon">Videocon</option>
<option value="spice">Spice</option>
<option value="zte">ZTE</option>
<option value="blackberry">BlackBerry</option>
<option value="maxx">Maxx</option>
<option value="appleiphone">Apple iPhone</option>
<option value="micromax">Micromax</option>
<option value="sonyericsson">Sony Ericsson</option>
<option value="hp">HP</option>
<option value="motorola">Motorola</option>
<option value="dell">Dell</option>
<option value="imate">I-Mate</option>
<option value="other">Other</option>
</select>
</div>
</div><br>
<div class="form-group">
<label class="col-md-4 control-label" for="textinput">Mobile Model&nbsp;<r>*</r>&nbsp;&#10002;</label>
<div class="col-md-4">
<input id="textinput" name="modelnumber" type="text" placeholder="Xperia Neo v" class="form-control input-md">
</div>
</div><br>
<div class="form-group">
<label class="col-md-4 control-label" for="textinput">Also Includes&nbsp;&nbsp;&#10002;</label>
<div class="col-md-4">
<input id="textinput" name="alsoinclude" type="text" placeholder="Case, Headset, Charger" class="form-control input-md">
</div>
</div><br>


<!-- Multiple Radios (inline) -->
<div class="form-group">
<label class="col-md-4 control-label" for="radios">Condition&nbsp;<r>*</r>&nbsp;&#10002;</label>
<div class="col-md-4">
<label class="radio-inline" for="radios-0">
<input type="radio" name="mcondition" id="radios-0" value="new" >
New
</label>
<label class="radio-inline" for="radios-1">
<input type="radio" name="mcondition" id="radios-1" value="old">
Old
</label>
</div>
</div><br>

<!-- Text input-->
<div class="form-group">
<label class="col-md-4 control-label" for="textinput">Price&nbsp;&nbsp;&#10002;</label>
<div class="col-md-2">
<input id="textinput" name="price" type="text" placeholder="&#8377;" class="form-control input-md">
</div>
</div>
<hr>
<h3>
<center>Seller Information</center>
</h3>
<hr>
<div class="form-group">
<label class="col-md-4 control-label" for="selectbasic">You Are&nbsp;<r>*</r>&nbsp;&#10002;</label>
<div class="col-md-4">
<select id="dropone" name="youare" class="form-control">
<option>Select Bellow</option>
<option value="Individual">Individual</option>
<option value="Dealer">Dealer</option>
</select>
</div>
</div><br>
<!-- Text input-->
<div class="form-group">
<label class="col-md-4 control-label" for="textinput">Name&nbsp;<r>*</r>&nbsp;&#10002;</label>
<div class="col-md-4">
<input id="textinput" name="mname" type="text" placeholder="Sanoj Lawrence" class="form-control input-md">
</div>
</div><br>

<!-- Text input-->
<div class="form-group">
<label class="col-md-4 control-label" for="textinput">Email&nbsp;<r>*</r>&nbsp;&#10002;</label>
<div class="col-md-4">
<input id="textinput" name="email" type="text" placeholder="&#10002;Mail@mail.com" class="form-control input-md">
<span class="help-block">Your mail id will not be shared</span>
</div>
</div><br>

<!-- Text input-->
<div class="form-group">
<label class="col-md-4 control-label" for="textinput">Phone Number&nbsp;&nbsp;&#10002;</label>
<div class="col-md-4">
<input id="textinput" name="phone" type="text" placeholder="&#9742;&nbsp;&nbsp;Phone Number" class="form-control input-md">
</div>
</div><br>
<div class="form-group">
<label class="col-md-4 control-label" for="textinput">Your Loaction&nbsp;&nbsp;&#10002;</label>
<div class="col-md-4">
<input id="textinput" name="ylocation" type="text" placeholder="Enter Your Loacation (Town or Village Name)" class="form-control input-md">
</div>
</div><br>
<div class="form-group">
<label class="col-md-4 control-label" for="textinput">Your Street&nbsp;&nbsp;&#10002;</label>
<div class="col-md-4">
<input id="textinput" name="ystreet" type="text" placeholder="Enter Your Street (Street or Area)" class="form-control input-md">
</div>
</div><br>
<center>
<input type="submit" class="btn btn-success"></center>
</fieldset>
</form>


SQL:



create table `mobile`(
`id` int(9) NOT NULL auto_increment,
`mcat` varchar(255) NULL default '',
`mtype` varchar(255) NULL default '',
`mtitle` varchar(255) NULL default '',
`image1` varchar(255) NULL default '',
`image2` varchar(255) NULL default '',
`image3` varchar(255) NULL default '',
`image4` varchar(255) NULL default '',
`image5` varchar(255) NULL default '',
`description` varchar(255) NULL default '',
`mmodel` varchar(255) NULL default '',
`modelnumber` varchar(255) NULL default '',
`alsoinclude` varchar(255) NULL default '',
`mcondition` varchar(255) NULL default '',
`price` varchar(255) NULL default '',
`youare` varchar(255) NULL default '',
`mname` varchar(255) NULL default '',
`email` varchar(255) NULL default '',
`phone` varchar(255) NULL default '',
`ylocation` varchar(255) NULL default '',
`ystreet` varchar(255) NULL default '',
`ipnu` varchar(255) NULL default '',
PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=1 ;




dynamic programming with memoization


I’ve a problem with a programming exercise. I hope you can help me. In this exercise I need to find out what the maximum profit is of taking pictures from several items in a park. For taking pictures I only have 50 minutes. Each item which you photograph has its own price. You can only photograph each item once. The exercise looks like this directed weighted graph:


Directed graph


The profit of taking pictures of items is shown right.


For this problem I’m going to use dynamic programming memoization, but I don’t know how to start. I’ve seen code from the knacksack problem, but I’m still stuck.


If you have any tips I would be really thankful!


This is the only code I have. The array for the names:



N[0] = ‘a’;
N[1] = ‘b’
N[2] = ‘c’


I got this array for the weights:



W[0][0] = 100
W[0][1] = 17
W[0][2] = 40
W[1][0] = 60
W[1][1] = 100
W[1][2] = 103
W[2][0] = 23
W[2][1] = 29
W[2][2] = 100


To get from the start to a, b or c it also cost time. I got the following array for that:



SW[0] = 12
SW[1] = 19
SW[2] = 10




Searching for a master's thesis topic #OpenCL #GPGPU [on hold]


I'm student of computer science, About 1 - 1,5 year ago I started learning about GPGPU, OpenCL, parallel programming etc. I like it, I'm interested in it, I want to do this.


Recently I defended my Bachelor's degree thesis. Basically I adjust algorithm in a way to execute it in parallel and implement it (console application, C++11, Boost). I used OpenCL (with C++ wrapper) to perform calculations on GPU. The results were quite good.


Now I'm searching for a master's thesis topic related to OpenCL, GPGPU, mobile computations, etc. Unfortunately I cant get any interesting proposition from lecturers I know and I don't to limit myself with thesis that is not about what I really like or like the most, so I'm looking outside my university.


Perhaps someone could give me some suggestions about topic or where to find someone who might help me.


Thanks a lot in advance & Best Regards.





Create the fields in class level then instantiate inside methods or create and instantiated inside methods


I'm a newbie in software development. Just wondering which code is better and why should I continue which pattern should I follow.


First Snippet:



Class TestClass
{
private Object1 field = null;
private Object2 field2 = null;

public void TestMethod1()
{
field = new Object1();
field2 = new Object2();
}

public void TestMethod2()
{
field = new Object1();
field2 = new Object2();
}
}


As you can see, I created fields in Class level and instantiate them inside the method.


Second Snippet:



Class TestClass
{

public void TestMethod1()
{
Object1 field = new Object1();
Object2 field2 = new Object2();
}

public void TestMethod2()
{
Object1 field = new Object1();
Object2 field2 = new Object2();
}
}


Here I created and instantiated the fields.


These fields are being used over and over in many methods in a class.





Styleguide when coding in a static language


I am currently a junior engineer and keen on learning best practices and expanding my experience. My question concerns any static programming language such as Java, C#, C++ etc.


When I am writing code, I like making it easy to read. In my opinion, reading code should be like reading a book. It should be fluent and elegant. Then, even if I do not need to use them, I like prepending this, superbase keywords whenever I can. Ditto for current class name when I want to use constants or static variables/methods.


Consequently, another developer can quickly have a long shot. He knows this method or var is in the current class or in mother class without needed to move to declaration. You may say to me it is really easy to do that with recent IDE. However, I know a bunch of guys who are still working with Vim, Emacs or other editors without these fancy features.


When explaining it, I like comparing my practices to a drama book. We have all read at least one of them, such as Macbeth from Shakespeare. Who has never felt frustrated to go back at the beginning of the book to know who is that character and what part he has in the plot? You did that so many times, right?


My question can be associated to literate programming practices. However, I assumed Donald Knuth's recommandations are more about commenting and adding macros to your code.


So I would like to know your opinions and feedbacks about these practices. Am I doing too much? Should I keep it simpler? Am I breaking OOP rules?


Here is a code sample:



class Bar {
protected int _motherVar;

public aBarMethod() { }
}

class Foo extends Bar {
private static List<String> _strings;

private int _myPrivateVar;

public void aMethod() {
super.aBarMethod();

this._myPrivateVar++;
super._motherVar -= 2;
}

public static String anotherMethod() {
String outcome = "";

for (String s : Foo._strings) {
outcome += s;
}

return outcome;
}
}




How to avoid violating one definition rule in this case?


We have an existing Mutex C++ class. It has a debug feature to track the owner thread id. So it has a member variable to store this, but because the original developer doesn't want to waste memory, this member is wrapped by a macro in a header file.


This header file has been included in multiple projects, some binaries are developed by other departments, so for those libraries we cannot control the compile flag switch, and we do not want this strong coupling.



// mutex.h
class Mutex
{
......
private:
#ifdef _DEBUG
int owner_thread_id_;
#end
......
}


Recently we were bitten by this code, because of memory corruption caused by violating the one definition rule.


So how can we implement it with following two requirements:



  1. Don't waste memory because it is a utility class and wide used.

  2. Don't violating the one definition rule.





Where can I learn about Dates/Timestamps?


Where can I learn about dates and timestamps? My goal is to learn enough to be confident on making/using any date/timestamp. The general information seems to be very fragmented when going to JavaScript MDN docs or googling date/timestamp.


It seems UTC is the thing to really read up on?


I would also like to use the industry best practice for storing timestamps and in general understand what i'm doing with timestamps .


I'm mainly working with JavaScript on the client and server and am using MongoDB as a database but any general knowledge would be preferable.





MVC like design with interfaces: How to handle basic objects?


I have an (android) application and decided that the presentation layer will get data only through strict interfaces from the controller. I am at the point where some basic objects need to be passed to the presentation layer, but the objects itself must be in strict read-only mode, because all changes will be handled by the controller.


To make a simple example, imagine a ToDo-App, where the screen needs to display a list of todo items.


The Todo-Item has the fields "title" and "content" with respective getters and setters. Even if I pass an unmodifiable list, the objects in it can be changed. I can think of these alternatives:



  1. put controller and data in one package and make the setters protected.

  2. add an interface to the todo item containing only the getters and passing these objects.

  3. add an interface only to the controller and put all getters there.


for 1)



public class TodoItem {
private String title; private String content;
public String getTitle() ...
protected String setTitle(..) ...
}


for 2)



public interface ITodoItem {
public String getTitle();
}

public class TodoItem implements ITodoItem {
private String title; private String content;

@Override
public String getTitle() ...

public String setTitle(..) ...
}


I wonder now what is the more common, smarter etc. option (or are there more?) and what are the arguments?


Alternative 1) for my feeling depends to much on the fact, that the items have to be in the same package making it to difficult to expand the program.


Alternative 2) looks odd to me, because all tiny objects would now become an interface with the getter methods. However, I am using it and technically I am satisfied.


Alternative 3) gets messy quick because one controller would then contain all the getters of the tiny objects. This does not comply to "let the object do the work".


What are your experiences and thoughts on this?





Sets of pair parameters


I have the following class, this class like many rely one parameters coming in as a pair. Originally for convenience, I set them as params Object[] values and check if there is an even number of them if (values % 2 == 0).


Example Code:



using RVD = System.Web.Routing.RouteValueDictionary;

/// <summary>
/// Allows for quick building of similar RVDs.
/// </summary>
public class RVDBuilder
{
public RVD Template { get; protected set; }

public RVDBuilder(RVD template)
{
this.Template = template;
}
public RVDBuilder(params Object[] routeValues)
{
if (routeValues.Length % 2 != 0)
{
throw new Exception("parameters must come in pairs of two!");
}
}
}


I can see two point of views here:



  • This adds great convience for the programmer: i.e. new RVDBuilder("Key1", 1, "Key2", "2", ...);

  • This is not as safe as it could be: i.e. new RVDBuilder(Tuple.Create("Key1", 1), ...);


I was hoping to get input on this subject/topic.



  • Should I force the programmer to use a 'pair' class? (How would this affect coupling?)

  • Should I make it safer even though It'll be an easy fix/catch if an error is made?

  • Is throwing an exception the best way to handle it or should I just truncate?

  • Would adding an event so the programmer can choose how to handle the situation be good practice?


Overall though, how do I identify and decide on a method for handling this situation? I know overall it depends on the setting of the project, but there's not really a mood/convention set for it on this subject. Are there any general rule-of-thumbs?


(Sorry if this isn't quite the right StackExchange for this question. It involves code, but I figured since it's purely for example to help better explain my design question it fit best here).





MySQL on delete cascade some levels


How can I use on delete cascade or on update cascade for more than one level? consider:



Table1
|
|--Table2
|
|--Table3


Table3 has a foreign key which references Table2 and Table2 has a foreign key references to Table1, I wanna delete some row from Table1, MySQL shows error cannot delete parent row (the row in table2). How can do what I want??





which is better practice for an IT student : focus on one only programming languages for all his projects or jump form one to an other


The problem that I read too many topics on stackoverflow and other websites that makes me confused about opinion that compares different programming languages , and every time I feel people or company's are most interested by a programming language I switch to it because in our academic projects we are free to choose any language we want :


Question 1 : now most of the companies for example those who are in the web development field for they're back end dev choose one between many languages available and hire people experienced in writing code in this language , The question is there any chance for some one who don't have a good experience in this language but a shallow idea about it and about several other programming languages to get hired by these company or startups .


Question 2 : for my programming skills which is best, stick with one or at least two programming languages ( two because i'm interested by web dev field and the JavaScript will be there what ever the back end technologies ) and get deep understanding to it or stay switching from one to anther until i have my degree and let the company I'll work with take this choice for me .


Thanks in advance for your feedback





Estimating run time of algorithm


For instance if i have an algorithm that is O(N^2) and it will run for 10 seconds for a problem size of 1000. Now if i were to double the problem size to 2000 i want to know the approximate run time in seconds. I know the answer for it but i want to understand the logic on how to get to the answer. So here is what i am thinking.



N = 1000 , Therefore 1000^2 = 10 seconds
N = 2000, Therefore (2*1000)^2, // stuck here


Now i am not sure i mean i know it will be 40 seconds because 2 to the power of 2 is 4 and then you multiply the 10 seconds by 4 and get 40 seconds but not entirely sure if this is right thinking. Was wondering if someone can break it down in simple terms?





What are appropriate terms to define program functionality and program parts?


Let's consider one program, for example windows notepad. This program has the following functionalities: open file,save file... One more example - I and team want to add new functionality to this progam.


In these examples I used term "functionality" to describe what program can do and "parts" of it. What are other terms to define this meaning?





Sharing data between bounded contexts


I'm developing a tournament management system that uses a mixture of CQRS/ES/DDD and basic CRUD. I've defined 2 bounded contexts so far: TeamManagement and TournamentManagement.


The TeamManagement bounded context does not use DDD and exposes basic CRUD operations to manage teams and their respective players. TournamentManagement BC is DDD based and contains all the logic related to creating schedules, entering scorecards, and assigning points based on the game result.


The thing I'm confused about is how would the TournamentManagement bounded context access the team and player data? Should I expose a service or do I duplicate data in both bounded contexts using events?





Need to store Multiple Images (path) into MySQL after upload


I am trying to build my own little eCommerce CMS, and i want the expert opinion on how to handle multiple uploaded files (images).


For Example:


A user adds a new item, fills the necessary form data and selects (nth) number of images and submits. I want to know how should i handle those images data into MySQL.


one thought i have in mind is that i create a separate table item_images Where i assign an ID or something like Item Code which inputs by the user and that Item Code will be the Identification for all the images?


PS: I dont want to upload Images directly to the Database, Just the paths/links.


Please advice.





Java write to text file from multiple threads


I have a thread which read and insert new lines in same file. I must synchronized that file so that no other thread is not accessing the file at the same time. Here is how i will synchronize a file record because while other threads write. Which approach to use in this case?



ReentrantLock



Or



producer-consumer pattern



My example code



public class ThreadManager extends Thread {

public void run() {
try {
BufferedReader br = null;
String line;
String fileNme = "threadLog.txt";
ArrayList<String> fileLines = new ArrayList<String>();
int numLine = 0;

File outFile = new File("$$$$$$$$.tmp");

// input
FileInputStream fis = null;
PrintWriter out = null;

//From here is a critical section

fis = new FileInputStream(fileNme);


// output
FileOutputStream fos = new FileOutputStream(outFile);
out = new PrintWriter(fos);
BufferedReader in = new BufferedReader(new InputStreamReader(fis));

try {
while ((line = in.readLine()) != null) {
fileLines.add(line);
}
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}

if (!fileLines.isEmpty()) {
int middleLine = (int) Math.round(fileLines.size() / 2);
fileLines.add(middleLine, Thread.currentThread().getName());

for (int i = 0; i < fileLines.size(); i++) {
out.println(fileLines.get(i));
}

out.flush();
out.close();
try {
in.close();
new File(fileNme).delete();
outFile.renameTo(new File(fileNme));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

//end critical section
}




Can I use only Delphi to create cross-platform apps?


I'm an Android developer working for a small start-up that wants to create a mobile app for iOs, Android and Windows phones. The start up is small and cannot afford to hire that many developers. As a way around this problem I thought it would be great to try and kill a number of birds with one stone. I'm also considering using Phonegap.





Am I Designing software or Architecting software?


A large part of my job responsibility involves taking a user story, developing a Technical Spec for it, mentoring a junior developer with writing and testing the code against the tech spec, while developing code against a tech spec written by someone more senior than me


In which circumstances would my work be considered software design vs software architecture?





Improving Haskell code performance of this particular piece of code


I've used BangPatterns, Lazy ByteString. Don't know what else to do to improve performance of this code. Any ideas and suggestions?



-- Find the sum of all the multiples of 3 or 5 below N
-- Input Format
-- First line contains T that denotes the number of test cases. This is followed by T lines, each containing an integer, N.

{-# LANGUAGE BangPatterns #-}
{-# OPTIONS_GHC -O2 -optc-O2 #-}
import qualified Data.ByteString.Lazy as L
import Control.Monad (mapM_)

readInt :: L.ByteString -> Int
readInt !s = L.foldl' (\x c -> 10 * x + fromIntegral c - 48) 0 s

main :: IO ()
main = do
-- don't need the number of inputs, since it is read lazily.
-- split input by lines
(_:ls) <- L.split 10 `fmap` L.getContents
-- length ls <= 10^5
mapM_ (print . f . readInt) ls

-- n <= 10^9
f :: Int -> Int
f n = go 0 0
where
go !i !a | i == n = a
go !i !a | i `mod` 3 == 0
|| i `mod` 5 == 0 = go (i+1) (a+i)
go !i !a = go (i+1) a




Visiting specific cells of an array


I am trying to figure out an algorithm to loop through an array visiting all the cells from (a,b) to (c,d), (from 0 to `). How could i do this efficiently ? I can't seem to be able to find a pretty way to do this. Any ideas ?


enter image description here





Constructor-only subclasses: Is this an anti-pattern?


I was having a discussion with a co-worker, and we ended up having conflicting intuitions about the purpose of subclassing. My intuition is that if a primary function of a subclass is to express a limited range of possible values of its parent, then it probably shouldn't be a subclass. He argued for the opposite intuition: that subclassing represents an object's being more "specific", and therefore a subclass relationship is more appropriate.


To put my intuition more concretely, I think that if I have a subclass that extends a parent class but the only code that subclass overrides is a constructor (yes, I know constructors don't generally "override", bear with me), then what was really needed was a helper method.


For example, consider this somewhat real-life class:



public class DataHelperBuilder
{
public string DatabaseEngine { get; set; }
public string ConnectionString { get; set; }

public DataHelperBuilder(string databaseEngine, string connectionString)
{
DatabaseEngine = databaseEngine;
ConnectionString = connectionString;
}

// Other optional "DataHelper" configuration settings omitted

public DataHelper CreateDataHelper()
{
Type dataHelperType = DatabaseEngineTypeHelper.GetType(DatabaseEngine);
DataHelper dh = (DataHelper)Activator.CreateInstance(dataHelperType);
dh.SetConnectionString(ConnectionString);

// Omitted some code that applies decorators to the returned object
// based on omitted configuration settings

return dh;
}
}


His claim is that it would be entirely appropriate to have a subclass like this:



public class SystemDataHelperBuilder
{
public SystemDataHelperBuilder()
: base(Configuration.GetSystemDatabaseEngine(),
Configuration.GetSystemConnectionString())
{
}
}


So, the question:



  1. Among people who talk about design patterns, which of these intuitions is correct? Is subclassing as described above an anti-pattern?

  2. If it is an anti-pattern, what is its name?


I apologize if this turns out to have been an easily googleable answer; my searches on google mostly returned information about the telescoping constructor anti-pattern and not really what I was looking for.





Two dimensional matrix-like data type using lists and/or mutable lists


I am trying to think of an implementation of a two dimensional matrix-like data type.

Normally I would take an array of arrays but I'm bound to a relatively low language level which only provides lists and mutable lists.

So of cause I could take a list of mutable lists and, in search of an item in row n and column m, get the m-th mutable list and go throught it until position n. But isn't there a better solution than going through the whole list?





Adding permanent objects to a vector


I'm relatively new to C++ (coming from Java) and I've got a little problem regarding lifetime of objects. My situation is like this: I'm having a class A in which I'm trying to add elements to an vector in class B. This vector itself shall hold objects (not pointers) of class C. However, since the objects are created in class As function, the are supposed to be deleted after the end of this function. So when I try to access these objects it gives me weird results. I'm currently passing the created objects as call by reference (using references instead of pointers). My question is, what can I do / use to have the vectors elements not deleted but saved for later use?





Manage content for multiple websites and mobile apps


I need to manage content (pages, key/value list, assets and more) in one webbased system for multiple websites and mobile apps.


My idea is to create a web api, secured with tokens for apps and sites and some kind of OAuth authentication, also with JSON web tokens. I want to create it with ASP.net Web Api, Entity Framework and Identify.


My idea is to split up the cms into a single page application, probably in AngularJS, and the Web API. So first create the domain model, how do we need to structure all the content/data and store this. After that create the api. And when that is finished, I need to create a SPA-cms webapplication for the end users.


Every website or app can use the api to read and write data over https and with a secret token, and every other party is free to choose whatever technique or programming language they want to use.


What do you all think about this idea? Can it be a architechture/technique to use for a long time? And do you think this architecture can be used for high traffic websites?


Thanks!





Which version of Java should I use for a desktop application to reach the most users?


Am I correct to assume that most end users are using an older version than Java 8? Since I do not want to force people to upgrade in order to use my application, should I plan it to use Java 7 or even 6 from the start, even if that means that I can't apply the benefits of the newer versions for myself as a developer?





Running Labview VI/app/exe on an embedded board


I want to run my LabVIEW app on an embedded board but apparently LabVIEW is only supported by x86 Architecture. Is that even possible?


If yes then can anybody recommend me an embedded board with a processor of x86 Architecture ? My requirements are :




  1. It should be low cost <100$




  2. It can be interfaced with an NI DAQ 6008/9







Is there a good guide to port Linux software to Mac OS X?


What is the best guide for porting Linux software to Mac OS X? I'm searching for a step by step guide that goes thru all you need to change in your source code to make it compile and run on OS X Darwin.





Advice me - getting started with programming


This is a question I am asking to get help from the community here, it's not a technical question rather than seeking an advice from experts in the domain.


It's been few years for me now getting into the development world, I began with C#, but all my knowledge about it is just simple stuff, like define a class, handling button event to insert data into table, get data from table display it in grid. All my work is related to SharePoint so I don't have to deal so much with C#.


Now I feel I am not that good developer, and my work in SharePoint requires GREAT understanding of JavaScript, C#, MVC, SharePoint itself, and Windows Azure.


I am currently working in a company, and am doing only SharePoint with them, I don't know if I can become a guru in all the technologies I have previously mentioned, should I study a book about each? Should I watch videos? Should I quit from the company and stay for few months learning all these technologies as I find working in my current company is just a waste of time as most of the stuff am doing are like "donkey work". How do you manage to learn new things and be super @ them? I haven't known any friend who's good with these ones, so I don't have someone to advice me on how to study, how to become too good in a short time, how should I plan for it? Each time I say: OK I'll study this JavaScript book for 2 months. Then this CSS book for 1 month, then go to bootstrap. then C# then MVC, at the end SharePoint, but my plans don't work. Any help?





Specific knowlege and skills for making android apps


I know this question has probably been posted already but i couldn't find a sufficient answer. I'm interested in learning how to make android apps, i already know how to code in java and i know oop. Now i wanna know where to move on, do i just start an online course for making android apps? or do i learn more advanced topic in java (like networking, gui etc...) and if i do need to more advanced topics first if someone can tell exactly what i need to learn it would much appreciated. thank you :)





How to design a solution that needs dynamism using Inheritance


I have below code/classes/interfaces:




  1. An Interface:



    public interface Animal<A extends Animal<A>>{
    void fight(A otherAnimal);
    }



2.Tiger class which is implementing Animal



public class Tiger implements Animal{
@Override
public void fight(Tiger otherAnimal) {
System.out.println("Tiger Fights");
}
}


3. I have a Lion class which also implements Animal



Public class Lion implements Animal{
@Override
public void fight(Lion otherAnimal) {
System.out.println("Lion Fights");
}




  1. I have a test class which is going to call fight:



    public class TestClass{
    public static void main(String[] args){
    Animal tiger = new Tiger();
    Animal lion = new Lion();
    tiger.fight(lion);
    }
    }



Now when I run the test class the obvious output is "Tiger Fights".


How should I redesign so that when I call fight on tiger with anything other than tiger should call their respective classes.


So in the example above it should invoke lion's fight even if the fight is called on object of tiger.


I need output as "lion fights" even if I am invoking an object of tiger. Meaning actually I want developer to have freedom to pass any type of object to to any class. My expectation is based on type of object the respective overridden method has to be called.


I need this dynamism because there can be N number of different animals (cat, dog, wolf etc) which might get added in near future.


Is it possible to design in such a way that My Animal interface will decide which class to call depending of type of object passed?





vendredi 27 février 2015

Boundry Traversal in Binary tree


How to perform boundry traversal in binary tree using only single traversal of the tree??


i am doing it in this way.. Not a single traversal


void printBoundary (struct node* root) { if (root) { printf("%d ",root->data);



// Print the left boundary in top-down manner.
if( root->left)
printBoundaryLeft(root->left);
else
printBoundaryLeft(root->right);

// Print all leaf nodes
printLeaves(root->left);
printLeaves(root->right);

// Print the right boundary in bottom-up manner
if( root->right)
printBoundaryRight(root->right);
else
printBoundaryRight(root->left);
}


}





PHPUnit > Best approach to mock container objects? (e.g. $item->id)


I'm using PHPUnit test doubles to mock models, libraries etc. But when I want to return an array perhaps of container objects, how best to do so. Here is what I'm currently doing:



/**
* This is just a mock of the response from http client
*/
class Container {
public $values;

public function __construct($values) {
$this->values = $values;
}

public function __get($name) {
return (isset($values[$name])) ? $values[$name] : null;
}

public function __set($name, $value) {
$values[$name] = $value;
}
}


.. then in my test* methods I may do something like:



$userMock = new Container(array('id' => 2, 'name'=>'Tom'));
$this->mock
->method('find') // called within BaseController
->with(2)
->willReturn( $userMock );


So I don't know if I can use PHPUnit tets doubles or Mockery to create such classes, can I? It seems simpler to just do this way, is this a good approach though?





Are gdb debugger and g++ compiler (by command line interface) used in industry while developing c++ application software in unix


Is gdb debugger with command line interface used in industry while developing application software(c++) in unix? If not which IDE will industry usually use while developing application software(c++) in unix?I wanted the IDE's which are used in industry not those which are available. Also please tell me if g++ compiler and makefile used in industry?





Methods accounting for all input to method


This is more of a conceptual question. Let's say that you had the following enum



public enum FooEnum {
ALPHA,
BETA,
GAMMA,
DELTA;
}


And let's say you have the following method:



public void doSomething(FooEnum value) {
if (value == FooEnum.ALPHA) {
// print something to the console
}
// other values ignored
}


Now, this example seems a little bit odd to me, as we're completely disregarding every other value of FooEnum. Think of it not restricted to just enums, but let's say something like



public class Person {

public void doSomething(String s) {
if (s.equals("asdf") {
System.out.println("something");
}
// disregard all other values
}
}


To me it seems like we should be at least doing something about other values we don't care about. I've often done input validation before hand to get something like



public void doSomething(String s) {
if (s == null) {
throw new IllegalArgumentException();
}
// do stuff
}


but what happens in this example



public void doSomething(FooEnum value) {
if (value == null) {
throw new IllegalArgumentException();
}
if (value == FooEnum.ALPHA) {
// do something ALPHA specific
}
// ignore other logically grouped values in FooEnum
}


What is the (or are some) suggested ways to avoid/refactor this? The primary way I could think of is to either log that it was intentionally ignored. What other patterns could be used.





how to insert a column values dynamically [on hold]


I have an array that contains some values.Taking these values ,I tried inserting into a column of a table dynamically,But could not succeed yet.I am using mvc technology in .Net.





how to decide when to use database replication vs. custom REST applications vs. message brokers (pub / sub)


We have a distributed solution that's currently under design. There are a few points of integration where some application needs data from someone else and vice versa. We could solve by either writing REST interfaces and provide CRUD features so that apps can share data between themselves. Or we can use something like nanomsg or zeroMQ to send messages back and forth.


We also have H/A requirements where we want to do master to master replication across primary and secondary db servers to ensure that if one goes down, the other one can kick in.


Here's the question. Some on the team feel that we should choose one method of sharing data like master to master replication... and just use it across the board to "share" data. It's true that we can do that, but I think each case should be analyzed and treated separately depending on specific criteria such as:



  1. are the databases in question identical? if they are, then master to master is appropriate such as in our High Availability scenario.

  2. in the case of disparate systems, how much data are we shuttling back and forth? if it's a lot of data... maybe a message bus is better. just send a notification to say "there's a change... here's the change id. Go get it".

  3. How often does data change? Does this matter? I *think both a REST api and a message bus will be able to handle many transactions.


I'm not sure what else to consider. It feels like creating a message bus solution would be a lot more work than a REST api into each database. But I could be wrong. What other things should we take into consideration?


Thanks.





What are the different fields in software/web application development for freelancers?


For example c# or java is not a field.


data warehousing and machine learning are.


I'm on my way to become a junior c#/asp.net developer. I'm more interested in backend development and work as a freelancer full time n down the years run a small customized development shop.


What areas/fields/specializations/niches are there which I can focus on?


Would be greatful if someone can point out what fields are available for a c#/asp.net backend programmer who wants to freelance to focus on.


Language is not the issue. I need to select the field and can learn whatever language is needed for it for the required project.


What i know is c#/.net or asp.net or things like web application development are too vast and include varies fields.


I just want to know the individual ones to focus on.


Thanks everyone.





PHP only showing records by id?


I am having trouble with this PHP code and I am not sure how to title it! I have a car showcase and I am wanting the Database to display the cars depending on their ID e.g 1 Ferrari Enzo, 2 Porsche GT3RS. Here is my code:



<?php
include_once("php_includes/db_conx.php");
$sql = "SELECT carid, make, model FROM stock WHERE carid IN(1,2,3)";
$query = mysqli_query($db_conx, $sql);
echo mysqli_error($db_conx);
$stock = mysqli_fetch_assoc($query);
$stock['carid'];
$stock['model'];
$stock['make'];
?>


These are the cars.



<div class="view view-first">
<img src="http://ift.tt/1MYEcgN" />
<div class="mask">
<?php if ($stock["carid"] =='1') {
echo $stock['make'];
} else { echo $stock['make'];


} ?>



</section>
<section class="right-column"> <div class="view view-first">
<img src="http://ift.tt/1MYEdBm" />
<div class="mask">
<?php if ($stock["carid"] == '2') {
echo $stock['make'];
} else { echo "car does not exist";
} ?>

</div>


Sorry if I get this wrong, new here xD





SQL - Algorithm for finding availability of a resource


I'm having trouble creating a mysql compatible algorithm for this.


Background


App with mysql, perl and JS. It's a booking system where each booking is comprised of a start, end and qty. Start and end are timestamps.


Schema simplified to a single table:



| bookings
|-------------------
| id | pkey
| start | timestamp
| end | timestamp
| qty | int


Question


In SQL, how do you check how many resources are booked at once for a given timeRange? Code with explanation or an algorithm that is SQL compatible both work.


So, for the following schedule:



09:00 ----- <-|
09:30 | | | A maximum of 12 are booked at once during this range
10:00 |x7 | |
10:30 ----- ----- ----- |
11:00 | | | | |
11:30 |x2 | |x10| <-|
12:00 | | | |
12:30 ----- -----


I should get 12 since the x2 and x10 bookings don't overlap with the x7 booking, so there are never more than 12 items booked at once between 9:00 and 11:30.


Progress



--It's been heavily shrunk to show just the relevant part, so it might have some errors
SELECT coalesce(max(qtyOverlap.sum),0) booked
FROM (
SELECT coalesce(sum(b2.qty),0) sum
FROM booking b1
LEFT JOIN (
SELECT b.qty, b.tStart, b.tEnd FROM booking b
) b2
ON b1.tStart < b2.tEnd AND
b1.tEnd > b2.tStart AND
b2.tStart < '2015-02-19 16:30:00' AND
b2.tEnd > '2015-02-19 06:00:00'
WHERE
b1.tStart < '2015-02-19 16:30:00' AND
b1.tEnd > '2015-02-19 06:00:00'
GROUP BY b1.id
) qtyOverlap
GROUP BY qtyOverlap.itemId


Which is this algorithm:



Max of
For each booking that overlaps given timeRange
return sum of
each booking that overlaps this booking and given timeRange


In the schedule above this would be:



max([7],[2+10],[10+2]) = 12


But given a schedule like:



09:00 ----- <-|
09:30 | | | A maximum of 17 are booked at once during this range, not 19
10:00 |x7 | |
10:30 | | ----- |
11:00 ----- | | |
11:30 ----- |x10| <-|
12:00 |x2 | | |
12:30 ----- -----


This gives:



max([7+10],[2+10],[10+7+2]) = 19


Which is wrong.


The only way I can think of to fix this is to use recursion (which isn't mysql compatible afaik).


It would look something like (in working JS code)



function getOverlaps(bookings,range) {
return bookings.filter(function(booking){
return isOverLapping(booking,range);
});
}
function isOverLapping(a, b) {
return (a.start < b.end && a.end > b.start);
}
function maxSum(booking, overlaps) { // main recursive function
var currentMax = 0;
var filteredOverlaps = getOverlaps(overlaps,booking);
for (var i = 0; i < filteredOverlaps.length; i++) {
currentMax = Math.max(
maxSum(filteredOverlaps[i], removeElement(filteredOverlaps,i)),
currentMax
);
}
return currentMax + booking.qty;
}
function removeElement(array,i){
var clone = array.slice(0)
clone.splice(i,1);
return clone;
}
var maxBooked = maxSum(timeRange, getOverlaps(bookings,timeRange));


Visual JSFiddle demo


Any way to do this in SQL? (any reasonable way, that is)


Update I just tried to use a stored procedure recursion emulation method as documented here. But part way through implementing it, I tried it with the demo data and decided the performance was far too terrible. Actually, it just needed indexing. Now it's just 'kinda' bad.





What kind of programming pattern is appropriate for programming an algorithm with rules and exceptions?


I'm interested in coming up with an algorithm to solve a guessing game. The player is attempting to guess a sequence of 4 unique numbers from 1 to 9. After a guess, they are told how many numbers of their guess are correct and in the correct position and how many are correct and in the wrong position.


The approach I'm taking is to have a starting collection of all of the possible guesses and a collection of all the possible numbers. The collection of guesses is used to give the player an idea of all valid guesses remaining. The collection of numbers stores information about each digit:



  • whether it is definitely present or definitely not, and

  • which position it is definitely in or definitely not in.


Then, as the player is given more clues, I remove all guesses that must be invalid and update assumptions about the digits. The idea is that, after a certain number of guesses, the algorithm should continue to improve their odds of choosing the correct sequence.


I want to accomplish the process of striking items off of the list and making assumptions about the digits by creating rules. Whenever a rule's conditions are met, the number collection and/or guess collection should update. Rules should include:



  • if the current guess has no numbers in the correct position, all numbers in the sequence are definitely not in their current position,

  • if 4 of the numbers in the sequence are present, then all guesses without all 4 of these numbers are invalid,

  • if two guesses have 8 unique numbers between them and the sum of present numbers is only 3, then the 9th digit not guessed is definitely present,

  • etc.


I like the idea that I, as the developer, can continue to add rules as I discover patterns that I have not noticed (or have not been able to formalize) without much hassle. The problem lies in implementation.


Is there a programming pattern that allows me to make an extendable set of rules to test for and react to?





popup pictures in a Front end javascript website


I am looking for some help to solve a problem that I am having...


I am playing around with a template I found online and I am trying to use another JavaScript script on the template to change the behavior of the pictures, where once click it displays a modal popup with a picture. The script for that is called fancybox (there are many others that do the same thing as well, tried them as well, same results) However, once I apply the fancybox class to the picture tags, it ruins the sizing of the pictures and layouts.. all pictures start to overlap one another and take up the whole screen.. Moreover, I have also included the js and css links within the website, that is not the problem so do not ask about it please.. Thanks


The location where the template and scirpt can be found are: http://ift.tt/1sTID04 http://fancybox.net/


Moreover, here is the code where I apply the fancybox class tag on



<a href="img/item01.jpg" class="item, fancybox">
<img class="item__image" src="img/item01.jpg" alt="item01"/>
<h2 class="item__title">Magnificence</h2>
</a>

<a href="img/item02.jpg" class="item, fancybox">
<img class="item__image" src="img/item02.jpg" alt="item02"/>
<h2 class="item__title">Electrifying</h2>
</a>

<!-- ... -->


Any help, would greatly be appreciated. Thanks in advance..





Why structs and classes are separate concepts in C#?


While programming in C#, I stumbled upon a strange language design decision that I just can't understand.


So, C# (and the CLR) has two aggregate data types: struct (value-type, stored on the stack, no inheritance) and class (reference-type, stored on the heap, has inheritance).


This setup sounds nice at first, but then you stumble upon a method taking an aggregate type as a parameter, and to figure out if it is actually of a value type or of a reference type, you have to find its type's declaration. It can get really confusing at times.


The generally accepted solution to the problem seems to be declaring all structs as "immutable" (setting their fields to readonly) to prevent possible mistakes, limiting structs' usefulness.


C++, for example, employs a much more usable model: it allows you to create an object instance either on the stack or on the heap and pass it by value or by reference (or by pointer). I keep hearing that C# was inspired by C++, and I just can't understand why didn't it take on this one technique. Combining class and struct into one construct with two different allocation options (heap and stack) and passing them around as values or (explicitly) as references via the ref and out keywords seems like a nice thing.


The question is, why did class and struct become separate concepts in C# and the CLR instead of one aggregate type with two allocation options?





Using and referencing external executable's in a solution


I have an application written in AS3 which I need to be able to start up from my C# application. I have a prototype that does this just fine but my question is in relation to how I would arrange my solution to accommodate for this.


The way I had it in the prototype was using a post build script to copy the AS3 program directory into the output directory (Release or Debug), I then referenced it using Path.Combine as below:



private const string AS3_APP = Path.Combine(Path.GetDirectoryName(Assembly.GetEntryAssembly().Location), "ApplicationDir", "AS3App.exe");


For something that's going into full development with long term support (probably a few years supporting this project, minimum) I'm wondering if there's a cleaner way of doing this. Something that is quite obvious to other working on the project but also isn't overly brittle.


The current thinking is that we will have a requirement to compile this AS3 application and then bring it into the solution; however as it is basically a Program Files folder, it'll be on the .gitignore. We will then use a post build script as I have done already which will copy the AS3 application into the output directory, but this feels quite hidden and awkward.


Are there any easier ways to do this in C# or any better ideas?