dimanche 30 novembre 2014

Enumerating array in reverse order using size_t index


Let's say we need to print int array with size N in reverse order:



// Wrong, i is unsigned and always >= 0:
for(size_t i = N-1; i >= 0; --i){cout << data[i];}

// Correct, but uses int instead of size_t:
for(int i = N-1; i >= 0; --i){cout << data[i];}

// Correct, but I don't like this:
size_t counter = N-1;
for(size_t i = 0; i < N; ++i){cout << data[counter--];}


Is there elegant way to do such enumeration without additional variable and using size_t index?





Intermediate results as variables or only base values?


I have a object which has a few base variables (integers as example) and one intermediate variable for further processing. The intermediate variable can be calculated from the base vars. Now the question: Should I always repeat the calculation of the intermediate var from the base vars or should I save the value and only change it if the base vars change? (I need access to every var in pseudo random order.)


Two examples in C++-Code.


Caching the result:



class Test
{
private:
int a;
int b;
int c;

int x;

void calcX ()
{
// Just an example for a calculation for x.
x = ((a + 10) * (b / (c*c + 1)));
}

public:
void setA (int var)
{
a = var;
calcX();
}
void setB (int var)
{
b = var;
calcX();
}
void setC (int var)
{
c = var;
calcX();
}

// Every var has a get methode.
}


Always recalculating the result:



class Test
{
private:
int a;
int b;
int c;

int x;

public:
// Var a, b and c have get and set methodes.

int getX ()
{
return ((a + 10) * (b / (c*c + 1)));
}
}


So, which way is considered better? I really don't know. We should not save the intermediate value because it would be redundant, but then again we should not recalculate the value again and again.





What does 'name' attribute signify in any java.awt component?


With the below program, am trying to find the names assigned to all the components part of the GUI.



public class AWTCounter extends Frame implements ActionListener{
private Label lblCount; //Declare component Label
private TextField tfCount; //Declare component TextField
private Button btnCount; //Declare component Button



public AWTCounter(){
this.setLayout(new FlowLayout());

lblCount = new Label("Counter"); // construct Label
this.add(lblCount); // "super" Frame adds label

tfCount = new TextField("0", 10); // construct TextField
tfCount.setEditable(false); // set to read-only
this.add(tfCount); // 'super" Frame adds tfCount

btnCount = new Button("Count"); // construct button
this.add(btnCount); // "super" Frame adds button


btnCount.addActionListener(this);
// Clicking Button source fires ActionEvent
// btnCount registers this instance as ActionEvent listener

setTitle("AWT Counter"); // "super" Frame sets title
setSize(250, 100); // "super" Frame sets initial window size

System.out.println(this);
System.out.println(lblCount);
System.out.println(tfCount);
System.out.println(btnCount);

this.setVisible(true); // "super" Frame shows

System.out.println(this);
System.out.println(lblCount);
System.out.println(tfCount);
System.out.println(btnCount);

}
. . . . . .
}


here is the output on console:



AWTCounter[frame0,0,0,250x100,invalid,hidden,layout=java.awt.FlowLayout,title=AWT Counter,resizable,normal]
java.awt.Label[label0,0,0,0x0,invalid,align=left,text=Counter]
java.awt.TextField[textfield0,0,0,0x0,invalid,text=0,selection=0-0]
java.awt.Button[button0,0,0,0x0,invalid,label=Count]
AWTCounter[frame0,0,0,250x100,layout=java.awt.FlowLayout,title=AWT Counter,resizable,normal]
java.awt.Label[label0,20,35,58x23,align=left,text=Counter]
java.awt.TextField[textfield0,83,35,94x23,text=0,selection=0-0]
java.awt.Button[button0,182,35,47x23,label=Count]


Based on the above output, I see some dynamic names like button0/label0/frame0/...


My question:


Is label0, attribute member value of class Label? If yes, what is the attribute member name of class Label?


Note: I am Java beginner





Why 'JRootPane' is-a 'JComponent' in javax.swing?


As per below code, I see that, setLayout() is being called on a JRootPane object instead of JFrame top level container in javx.swing world unlike java.awt, because it is told that swing's JFrame is light-weight container compared to AWT's Frame.



public class TestGetContentPane extends JFrame {
public TestGetContentPane() {
Container cp = this.getContentPane(); // cp points to 'JRootPane' object
cp.setLayout(new FlowLayout());
cp.add(new JLabel("Hello, world!"));
cp.add(new JButton("Button"));
......
}
.......
}


Any JComponent will be part of the layout set in Content-pane JRootPane which in-turn is a member JFrame or JDialog top-level containers. So, JRootPane looks like a container but not component.



/**
* @see #getRootPane
* @see #setRootPane
*/
protected JRootPane rootPane; //member of JFrame or JDialog


Interestingly, below code says that, JRootPane is-a JComponent.



public class JRootPane extends JComponent implements Accessible {}


My question is,


1) What exactly do they mean, when they say JFrame is light-weight container unlike AWT Frame?


2) Why JRootPane is-a JComponent? I feel, JRootPane should be along the class hierarchy where JFrame & JDialog sit under Container





Can concurrent code (threads, distributed computing, etc.) be directly ported to single-threaded, non-networked platforms?


Take an arbitrary "perfect" multi-threaded program, on an arbitrary multi-threaded platform, using an arbitrary programming language.


Assuming that this "perfect" multi-threaded program:



  • is flawless in terms of race conditions

  • handles shared memory perfectly

  • may/may not use a locking mechanism (thread suspension or mutexes fall into this category)

  • has no unforeseen bugs (100% bug free)

  • uses no complicated language/system specific constructs that cannot be translated to another system


and assuming that this arbitrary platform



  • is/isn't POSIX compliant

  • uses a familiar threading model

  • doesn't turn the locking mechanism into a whirlwind of voodoo spaghetti code (arguably)


and assuming this arbitrary language



  • doesn't use any domain-specific threading constructs (such as Java's synchronized keyword)

  • is platform agnostic at the very core (such as C and variants)

  • can be cross-compiled to many different architectures/platforms (isn't limited to the platform its on)


can the code inherently be implemented in such a way that it runs as expected on a single-threaded platform?


For instance, in lieu of threads the single-threaded platform uses a co-routine-like model to simulate threads. Is there a fundamental design flaw with such concepts that would inhibit the ability to run the program in this thread-absent environment?




More concretely, are there any specific, mainstream platforms/architectures that wouldn't allow such a scenario to occur?





Should I choose to C++ or java for an interview?


I have been coding in c# for three years. However, I am considering to apply for Google, and I need to pick C++ or Java for the interview.


I learned C++ 12 years ago in my first Bachelor's year. I loved the language at the time but never did any serious project with that.


I used Java for my Master's course projects, and later worked in some Java-based company for a short time, so I am pretty comfortable with it but don't know various details and tricks of the language.


A Noogler friend suggested C++, and her reason was that the interviews are likely to be altra good at Java, and may ask language-specific questions that you don't know. During the past couple of weeks, I started reading "Thinking in C++" and learning C++ Standard Library, created a couple of small projects on Visual Studio and stuff. But I am not exactly comfortable with the language. Like I try to code the "Cracking the Coding Interview" questions and with each questions I have to spend hours(!!) to just get to build my C++ code!


I need your ideas on what to do, to continue the path with C++, or to switch to Java (and the past couple of weeks will be sort of wasted time)





Is there an alternative to instanceof when filtering a Java stream by class?


I have an unexpected situation in a project in which all types extending one class are packed into a Java collection; but only a specific extension of that class contains an additional method. Let's call it "also()"; and let me be clear that no other extension has it. Right before performing one task on every item in that collection, I need to call also() on every item that implements it.


The easiest way forward is this:



stuff.stream().filter(item -> item instanceof SpecificItem)
.forEach(item -> ((SpecificItem)item).also()));
stuff.stream().forEach(item -> item.method());


It works fine, but I'm not comfortable with the "instanceof" in there. That's generally a marker of bad code smell. It is very possible that I will refactor this class just to get rid of it. Before I do something that dramatic, though, I thought I would check with the community and see if someone with more experience with either Streams or Collections had a simpler solution.


As an example (certainly nonexclusive), is it possible to get a view of a collection that filters entries by class?





What argument passing mechanism does python use, and where is this officially documented?


As far as I am aware, python is generally referred to as 'call-by-sharing', but does it implement this with call-by-value (like Java) or call-by-reference? or something else? I would appreciate if this could be answered with official python documentation (in which I can't seem to find the answer) as opposed to anything subjective.





PowerBuilder6.5: Could not find the definition for user defined function [on hold]


I am looking into the application code developed by a former colleague.


I want to view the function definition called using OLE custom control object as below



w_station.ole_cbm.object.CalFee(ldt_entry_date,ldt_entry_time,datetime(today(),Now()))


I am looking for the definition of CalFee Function, but I ended up finding nothing.


I checked for the global function declaration, local function declaration everything, but could not find the function declaration/definition. I don't have any clue where I could find the function declaration. Even I tried playing with the function name, but I am not getting any compilation error. May be because Power Builder accepts the property and function call during compile time and throws error only during run time.


So Later I tried to build the .exe file, and ended up with the error calling DLL library for external function call for some other function.


Also checked events and function defined for the OLE Custom Control.


Precisely I want to know the place where the user defined functions definition is being stored in powerbuilder.





Algorithm Analysis: In practice, do coefficients of higher order terms matter?


Consider an^2 + bn + c. I understand that for large n, bn and c become insignificant.


I also understand that for large n, the differences between 2n^2 and n^2 are pretty insignificant compared to the differences between, say n^2 and n*log(n).


However, there is still an order of 2 difference between 2n^2 and n^2. Does this matter in practice? Or do people just think about algorithms without coefficients? Why?





Open source solution for social mobile chat app?


Any good open source solution to build mobile apps for people chatting ?





How would one implement communication between an input device and a PC?


I'm trying to get started on a side project using a mobile device (tablet or smartphone) as an input device to a PC. In its most simplest form, I envision using the mobile device touchscreen to control cursor movement and clicks on the PC. So far I'm targeting Windows machines and either Android or iOS devices (using Xamarin).


The plan so far is to use Xamarin to build the mobile app while a SignalR middleware resides on the PC as a TCP IP server in order to facilitate communication between device and PC. Up to this point, everything's rosy and I know what I'm doing.


My problem is in regard to what to do between the middleware and the PC. I have no experience with this portion of the problem, so I've been doing research and looking into various things like HID, 1394 virtual devices, custom device drivers, etc. All of these topics are currently beyond my comprehension and I can't figure out which of these (if any) are the correct approach.


Can anyone provide some insight into how to bridge the gap between receiving data via TCP IP and translating that into a keypress/mouse interaction in windows?





Is there a way to handle shared javascript assets in Spring?


I'm familiar with MVC web frameworks and lately very familiar with Symfony2.


I want to start learning Spring, and the first practical problem I would like to try to solve is handling the reuse of javascript libraries.


It's been a while, but in Symfony2 my solution was to create a bundle with a Twig (template engine) extension which handled adding JS files (such as javascript frameworks) once even if aggregated content (from multiple bundles) had multiple statements requesting for the same js file. I believe I also used Assetic.


So, in the Spring world, is there a preferred way or built-in mechanism to deal with shared javascipt assets (or any other for that matter, e.g. images)?





Why do we have to tell printf() the type of data in C?


Let's consider this C code:



#include <stdio.h>

main()
{
int x=5;
printf("x is ");
printf("%d",5);
}


In this, when we wrote int x=5; we told the computer that x is an integer. The computer must remember that x is an integer. But when we output the value of x in printf() we have to again tell the computer that x is an integer. Why is that?


Why does the computer forget that x was an integer?





Incorporating web designer's into a rails app


I have a designer who has great knowledge of HTML, CSS and JavaScript (Not jQuery or AJAX though).


He gives me his designs in those files and I have to incorporate it into my apps.


The site is not static so I have trouble incorporating it.


When the site was static I used to save the HTMLs in my app/views directory and the other CSS, JS, fonts in the public/... dir. The files are directly linked from the HTML is read just fine.


But now, I have to replace HTML tags with .erb ones <% --rails-- %> when some dynamic action needs to be performed. Even this seems harder than it sounds


Anyone developer experienced with this? How did you solve your problem?


OR should I ditch this designer and get a designer who has good knowledge of rails?





Cleaner C# without unneeded indents


In OO languages, at least C#, everything has to be in a class. Sometimes, everything is in a namespace as well.


Just about literally all the code in one class is going to be automatically indented by a tab stop or two, which is seriously pretty pointless if it doesn't help with code readability.


The issue with just removing the indent on every single line is that the one/two lines that had the "class ..." and the "}" become out of place.


What seems like a clean and readable way to remove the extra indents in front of every single line without making the class declarations be weird?


This might be opinion-based but I don't know.





How to call an internal incorrect behaviour that does not manifest itself as a bug?


To put this in context, I have the following scenario. I am writing a Common Lisp program that works with strings and lists of characters.


In a certain function foo, the value of a variable suff is a list of characters. Further on in the code, I forgot that suff was a list and treated it as a string, calling



(subseq suff 0 1)


I did not notice the mistake, because subseq works both on strings and lists:



CL-USER> (subseq "abc" 0 1)
"a"

CL-USER> (subseq '(#\a #\b #\c) 0 1)
(#\a)


So in the subsequent code I assumed I was working with strings while in fact I was moving around lists of characters.


These wrongly-typed results were finally formatted by the program's output function using (concatenate 'string .... I was lucky, because concatenate happily produces a string when given lists of characters as arguments.


I only discovered this mistake when adding more tests (yes, I know, TDD, but that's another topic) and testing foo directly.


Since my program was running properly - at the time my output function was the only piece of code that was using the corrupted data - I cannot say that the program as a whole contained a bug even though function foo, taken separately, was buggy.


Is there a special name to describe such an incorrect internal behaviour that does not manifest externally as a bug?





What is your coding interview checklist?


Imagine that you have a coding interview in next 1 week. What would be in your checklist in terms of preparations ?


What are some of the algorithms you would implement to refresh your memory ?


Please also suggest the books that you might read or go through.





Unexpected value using random number generator as a function in C++


C++ beginner here with a problem using a functions. Please help!


I am trying to make a random number generator function that I can call from within int main to cout a randomly generated float between 0.0 and 1.0 to my screen. When I create the generator in int main and cout it runs fine and returns a float just the way I want, but when I put the same code in a function and call it in int main I get some mix of letters and numbers that makes no sense.


I understand that I could just use the code in the way it works and ignore it but at this point I really want to know why it's not working the way I'm trying to make it work. I've looked all over for the answer and feel as if I'm missing some really basic knowledge about the way functions work in C++.


Why is the code that works perfectly fine in int main returning gobbledygook when called from a function?


Random number generator in function (returns nonsense):



#include <iostream>
#include <random>
#include <ctime>

using namespace std;

float roll();

int main(){
cout<<roll<<endl;

system("PAUSE");
return 0;
}


float roll(){
default_random_engine generator;
uniform_real_distribution<float> distribution(0.0f,1.0f);
return distribution(generator);
}


Random number generator in int main (this one returns a float):



#include <iostream>
#include <random>
#include <ctime>

using namespace std;

int main()
{
default_random_engine generator;
uniform_real_distribution<float> distribution(0.0f,1.0f);
float roll = distribution(generator);

cout<<roll<<endl;

system("PAUSE");
return 0;
}




Which are the projects which could fail if we execute in an Agile way? [on hold]


Agile is a very popular and accepted way of project execution. Which are the types of projects not suitable for Agile mode of execution





How does the graphics in a GUI framework work?


I have an understanding of how event-driven a gui system is. But I want to know the graphics aspect of it. That is, how the different elements like buttons are generated ( from the OS perspective if possible). May be I am not finding the right words when googling but need your help with this.





Specific empty children classes


Is having empty children classes, just to specify, a bad practice?


Lets suppose I've a generic Product class. There are electrical, electronic and mechanical products. I need to represent all them and must be able to differ each one in some operations. I've two options:




  • add a member named "type" in Product class to specify whether it's a electrical, electronic or mechanical product.




  • create children classes of Product, one for each kind of product: ElectricalProduct, ElectronicProduct and MechanicalProduct. As these classes don't differ from each other in methods or members - already defined in parent class - they would be all empty.




I consider second option a better approach, but is it the right way? I've never seen such thing on any application or library.


What do you thing? Any suggestion?





How should I approach to a large c++ project including different classes in differnt files and CUDA kernels in some of them?


I am very rusty right now in c++ because of my research experience. But it is time to realize my theories though efficient implementation.


I have 3 basic questions for the case;



  1. What is the best platform to develop c++ project? Eclipse, Sublime+Terminal or what

  2. Do I need to compile all the code for any single change in the code? What is the recommended work-flow?

  3. What are resources you suggest for such people like me?


Thanks





Can't Seem to get htaccess rewriting to function


My task is very simply. I want to rewrite http://mysite.org/users/?profile=user to http://mysite.org/users/user


My htaccess file, which is in the root directory of my website, has the following code:



RewriteEngine on
RewriteRule ^users/([a-zA-Z0-9_-]+)$ users/?profile=$1


I have tried many alternatives, checked Stackoverflow and all previous htaccess-related posts on websites, but am stumped at why this would not be functioning at all properly. I simply get a 404 error by going to http://mysite.org/users/user but http://mysite.org/users/profile=user does work. I am stumped.





Do the implementations of the Node interface in Web API violate Liskov Substitution Principle?


MDN article on Node interface states that



interfaces [that inherit from Node interface] may return null in particular cases where the methods and properties are not relevant. They may throw an exception - for example when adding children to a node type for which no children can exist.



To me it seems like a strengthening of preconditions in a subtype - a violation of LSP.


Do these implementations actually violate LSP, or is my understanding incorrect?





Why there aren't "Code Overviews" for open-source projects?


There are very complex open source projects out there, and to some of them I think I could make some contributions, and I wish I could, but the barrier to entry is too high for a single reason: for changing one line of code at a big project you have to understand all of it.


You don't need to read all the code (even if you read, it won't be sufficient) and understand all every single line does and why, because the code probably is modularized and compartimentized, so there are abstractions in place, but even then you need to get an overview of the project so you can know where are the modules, where does one module interface with other, what exactly each module do and why, and in which directories and files are each of these things happening.


I'm calling this code overview, as the name of a section that open source projects could have in the website or documentation explaining their code to outsiders. I think it would benefit potential contributors, as they would be able to identify places where they could build, the actual primary coders involved, as they would be able to, while writing everything, reorganize their minds, and would help users, as they would be help to understand and better report bugs they experience and maybe even become contributors.


But still I have never seen one of these "code overviews". Why? Are there things like these and I'm missing them? Things that do the same job as I am describing? Or is this a completely useless idea, as everybody, except for me, can understand projects with thousands lines of code easily?





Is hadoop suitable for java/j2ee developer?


I am from java/j2ee background and having 3 years exposures in hibernate,spring,struts.


Can i start learning Hadoop-big data which is modern technology in the software world?


Is I fit for Hadoop?


if yes what are the benefits over java/j2ee?





What is the best online c++ tutorial for experienced programmers?


I'm an experienced C# programmer.


I wanna learn C++ but i don't want a tutorial which explains me what a variable is !!!


It's very important that it doesn't teach me 1000 years ago C++ versions. Only C++ 11/14 !


I didn't spent a $ on learning C# and now i'm master in C#. So i want the tutorial to be free.


Thank you.





education - Masters degree in 3d graphics/animation or not?


Next year i will graduate a Computer Science bachelor degree(maybe in the best university of Russia). I have some skills in 3d computer graphics, 3d animation, computer vision. And now i want to know, what should I do, if I want to have a job in a big company like Pixar, Weta Digital or DreamWorks? I am not familiar with USA universities, but I would like you to advice me some good graduate programs(and the approximate price for all years of the program). Or maybe is it not enough to get a good job? Or maybe should I better work these several years? What is the best way?


Sorry if my question is not appropriate for this section of stackexchange.


I would be grateful for any advices!





add large amount of data in SQLite android


I am new to android and maybe its a silly question but i am not getting it. See i am designing a game in which we give scores to some persons. So i want to store the names of the persons in a database while installation and then their scores set to 0 initially which will be updated according to what the users select. Here i am not able to figure out that how should i enter the data as it will be around 100 names and their scores. Using INSERT INTO() statement will make it like 100 statements. So is there any short method like can we do it through strings or something. Just guessing though. Any help would be appreciated.





How does a web developer showcase their work in a portfolio compared to a designer?


I'm a web developer and I have a portfolio, however, my portfolio is like that of a web designer, with thumbnails of the sites I've worked on a brief description. There is no mention of the specific details of the code I wrote code snippets etc. How should I showcase my work as a developer.





wierd problems in javascript program


I was trying to make a javascript program that makes us play tic-tac-toe. But wherever i click,it shows "Invalid Move".


Code:


Game


var droid = new Android(); var turn =1; function convert(event) { var et = event.target.src; if(et == "imgb.png") { if(turn == 1) { et = "imgx.png"; turn = 2; } else { et = "imgo.png"; turn = 1; } } else alert(" Invalid Move"); }






Implementing Facebook Flux's Dispatcher


I am getting into Facebook's Flux architecture, which is a client-side MVC variant based on React.js.


It features a dispatcher, a single object that mandates unidirectional data-flow, as opposed to the two-way binding which is common in other MV* libraries, AngularJS being a notable example.


The details and explanations provided on that page are clear to me - have been reading it through in the last couple of days, letting it all sink in.


However, the dispatcher example provided is quite lacking (they acknowledge this themselves: "A problem arises if we create circular dependencies... We'll need a more robust dispatcher that flags these circular dependencies... and this is not easily accomplished with promises. In the future we hope to cover how to build a more robust dispatcher and how to initialize, update, and save the state of the application with persistent data, like a web service API.").


This is what I've come here for. I am looking for some articles, examples, or libraries (javascript) that fall into that description of a dispatcher with extended ability to manage data in states, persistency, and resolve handle circular dependencies.





Algorithm for sport tournament bracket tree


I would like to develop a library that:



  • receive n players in input

  • response with the tournaments brackets in output.


I would ask you what kind of algorithm I have to use to choose the correct tree that have to be generated for each input. I am interested on single elimination tournaments.


Thank you





Should I accept empty collections in my methods that iterate over them?


I have a method where all logic is performed inside a foreach loop that iterates over the method's parameter:



public IEnumerable<TransformedNode> TransformNodes(IEnumerable<Node> nodes)
{
foreach(var node in nodes)
{
// yadda yadda yadda
yield return transformedNode;
}
}


In this case, sending in an empty collection results in an empty collection, but I'm wondering if that's unwise.


My logic here is that if somebody is calling this method, then they intend to pass data in, and would only pass an empty collection to my method in erroneous circumstances.


Should I catch this behaviour and throw an exception for it, or is it best practice to return the empty collection?





SQL developer question


Use IF and WHILE to insert 100,000 records into the following table. Place your Database script here that generates the following result.



CREATE TABLE [dbo].[cs110](
[ID] int NOT NULL IDENTITY (1, 1),
[lastname] [varchar](50) NOT NULL,
[firstname] [varchar](50) NOT NULL,
[number] int NOT NULL
)
GO
SELECT * FROM [dbo].[cs110]

a) Run the above script to create a table, so you can add records.

b) Insert your last name, first name and number. The number MUST increment by 100 on every additional 100 record. For example, look below.
First 100 records (1 - 100) Insert 100
Next 100 records (101 - 200) Insert 200
Next 100 records (201 - 300) Insert 300
Next 100 records (301 - 400) Insert 400
...
Continue until you have inserted 100,000 records




Database design for polymorphic data


I have an application that needs to log communications with users over several different mediums: Email, SMS, Voice, Website Announcements, etc.. in a traditional database.


I have been wrestling with a choice between 3 approaches to modeling these different types of data:




  1. Store them all together in a single table (ie, comm_message) with discriminator field of some sort to indicate the type of communications (eg, message_type). This means that some fields in the table won't be used for each type--and it means that the same message may be duplicated in several different rows in the table (if the message is sent via more than one medium).




  2. Have a message table (comm_message) and then transports table (comm_transports) with the various different mediums of communication. A many-to-many relationship between messages and transports would mean one row for each message in the message table--but that row might have several different transports. If additional specific information is needed for a particular transport, it could be in it's own table (ie comm_sms, comm_email, etc..) that is linked off the many-to-many table. Ie, a "has-a" approach.




  3. Create a base message table (comm_message) and then another table for each medium with fields specific to it (inheritance). My ORM (LLBLGen) would facilitate this approach by using shared PKs for the different tables. In this approach there would be a row in the base table (comm_message), plus rows in each of the related tables for each transport (comm_email, comm_sms, etc..) but there would be no many-to-many relationship. Rather the records across different tables would share the same PK (1-1). This would be more of an "is-a" approach.




Context: This is a medium sized application (around 100 tables) that I'll be maintaining for many years--so I'd like to get this "right". I'll even need to present all the communications info together in the UI in a grid, reports, etc..


I'm looking for advice/ pros and cons to each approach.





ASP Custom Storage Provider [on hold]


I'm trying to make my own Storage Provider for my Products


I would like to do the following in my seeding (for example)



var store = new ProductStore<Product>(_db);
var manager = new ProductManager<Product>(store);

if (!_db.Products.Any(r => r.Title == "product title")){
var product = new Product {
Title = "product title",
Description = "product description"
};

manager.Create(product);
}


Any examples or Links to tutorial, so I can understand what needs to be added, and why. Would help me so much!





conio.h's kbhit equivalent for mac


What is a way to get conio.h's kbhit() functionality on mac os?


Is there an equivalent function in the curses library, if so, what is it?





Why 'JButton' is-a 'Container' in javax.swing?


As per the class hierarchy in java.awt.*, class Button & class Label is-a class Component, and Component is not a Container, which make sense to me.


As per the redesign of class hierarchy in javax.swing.*, class JButton is-a class JComponent in-turn class JComponent is-a class Container,


So, What does it mean to say that, class JButton or class JRadioButton is-a class Container? How could one think of using button or radiobutton be used as container in GUI programming?


Note: I am java beginner.





samedi 29 novembre 2014

What is a good conio.h alternative for mac?


What is a good alternative library to conio.h for the mac that has functions similar kbhit() and getch()?





I have two applications... use NoSQL or RDBMS?


I have two applications in the making: one is a budget management tool; the other is a article based places/restaurant guide.


The budget management tool works where users create accounts (e.g. bank account) and create transactions of purchases. The accounts are associated with the user by one (user) to many (accounts) relationship. The same goes for accounts and transaction, one (user) to any (accounts). For this reason I'm wondering if relational database is better here.


The other application users submit travel articles. Users can have many articles which they own. However, each article may or may not have additional meta data associated with it. Examples would be: address, tags, map location. These would be optional fields. Each article other users may add comments also. As the schema is a little looser for this application would I be correct in suggesting NoSQL would be suited here? Otherwise I would need to have may tables for the many-to-many associates (e.g. one article can have many tags, and vice versa)


However, for the budget application I will probably also adopt tags. Is it normal to use a relational database for the strictly relational stuff (user->account->transactions) as well as a NoSQL database for the meta type stuff (e.g. tags - I'd still need to include in their foreign keys though of the relational database tables huh?)


Anyway would appreciate any advice on these matters as I'm still trying to figure out when to use one over the other.





Query on usage of 'Window()' default constructor in java


I had been through this query before asking this question.


In class Window we have constructor with default direct access level package private but not private as shown below:



Window() throws HeadlessException {
GraphicsEnvironment.checkHeadless();
init((GraphicsConfiguration)null);
}


With class dummy inheriting class Window,



import java.awt.*;

public class dummy extends Window{
dummy() {

}
}


I see this error: Implicit super constructor Window() is not visible. Must explicitly invoke another constructor


I designed non-public class with zero-arg constructor having default direct access level package private and the subclass constructor invokes zero-arg Superclass constructor without any error.


I would like to understand,


Why does the compiler show this error despite the direct access level to the constructor Window(){} is package private?


Note: I am using jdk 1.6





How to test android apps that depend on telecom provider connection?


I am planning to write an app that needs phone number and contact list. Is there any way that I can test my app without buying a telecom provider connection for my android phone. Without a sim the phone doesn't have a phone number and I am wondering if mock phone number is only way to get pass this.





problem with downloading images using URLDownloadToFile in vc++


the following function is taking a list of urls of images as parameter in the form of vector and the function i have used to download files is "URLDownloadToFile" but not a single time the images are downloaded.


always same results "Unknown error" so any help will be appreciable . thank you in advance #



void fun::update(vector<std::string>& list_url)
{

vector<std::string> res ;

HRESULT hr;
for(std::size_t i=0;i< list_url.size();i++)
{
res.push_back(list_url[i].substr( list_url[i].find_last_of("/") + 1 ));


LPCTSTR Url = (LPCTSTR)list_url[i].c_str();
LPCTSTR File =(LPCTSTR)res[i].c_str();


hr = URLDownloadToFile(0, Url,File , 0, 0);


switch (hr)
{
case S_OK:
cout << "Successful download\n";
break;
case E_OUTOFMEMORY:
cout << "Out of memory error\n";
break;
case INET_E_DOWNLOAD_FAILURE:
cout << "Cannot access server data\n";
break;
default:
cout << "Unknown error\n";
break;
}
}

}


the function " URLDownloadToFile(0, Url,File , 0, 0)" is responsible for downloading files





what is the difference between inclusion and inheritance


the question is self explanatory, I just want to know when to use the inclusion and when to use inheritance, and which one serves for re-usability.


in other words, which one meets the Object Oriented programming principles the most?





Should I avoid using 'break' during a coding interview?


I have an upcoming internship interview with Microsoft and, although I rarely use break in my own code, it does simplify things a lot of times and bring me to a solution faster when coding on the whiteboard.


To anyone familiar with the interview process, would it reflect badly on my coding style? I'm not asking about whether breaks are bad or not in general, but should I try to go for Boolean checks instead during the interview?





Eclipse Default System Browser opens notepad


Bit of an odd problem with eclipse on my desktop, it works fine using the same project and setup under my laptop so I think it's not related to eclipse but rather something with the system.


When running an application using the default system web browser, eclipse opens notepad with a message saying that the filename, directory name or volume label syntax is incorrect. I'm not sure why it opens notepad in the first place.


Other programs using my default web browser work fine (the browser in question is chrome).


Note however that using the internal browser works fine, and I can just open the project in chrome by surfing to my localhost.





What algorithm-family or problem-space description fits? Industrial process feeding ingredients to process


Our process continuously feeds (normally <= 8) ingredients from a choice of hundreds, using 3 feeders only. So if ingredient count X is > 3, 3 through X are stirred together in a batch process and the resulting "premix" gets put in its own feeder. 6 is a hard limit for the number of ingredients a premix can have. It is possible to need to make 2 or even 3 premixes so that 2 or all 3 feeders feed premix. Unlikely but possible. This process is for experiments where we try 2 to 15 different recipes where we vary the ingredients and/or the weight-proportions. Hopefully this image conveys the situation. spreadsheet snip A person is deciding what ingredients get their own feeder, what goes in the premix, what experimental runs have enough in common to share a big premix, and what order to do the runs in to minimize changes. I'd like to make Excel and VBA make all those decisions for her. I can code it up once I get my mind around the problem. I can even derive a symbolic system to describe it, but I'm sure someone smarter than me already has. However I don't know what family of problems this is from. Not knapsack, imho. Can you point me in the right direction?





Web Components and Performance


I am having trouble learning about what impact web components and shadow dom will have on the browser, specifically related to repaint. I remember reading at one point that the shadom dom nodes have encapsulated repaints which greatly enhances performance but I cannot find any articles about this so it seems like speculation. Can anyone tell me how web components and performance are related? Thanks





What is the difference between user requirements and system requirements?


From what I've read I believe user requirements are just the system requirements given in lay mans terms, is this correct? Could someone please provide an example that clearly shows the differences between the two?





Exposition of Data Representation


I would like to know how the data representation is exposed in slide 7 of information hiding:




  • Modifying an exposed data representation propagates to all code which directly accesses that representation



    • Perhaps the best example of the impact this can have is the Year 2000 problem

    • Legacy software for applications as diverse as nuclear power station control, air traffic control, finance, and the military were coded using exposed data representations

    • To ensure the software will work correctly come 2000 every single place that uses the date representation needed to be changed to store years using 4 digits rather than 2

    • The cost of this conversion has been estimated in billions of dollars!




  • Exposed data representation leads to change propagation ... affects maintenance costs ... big trouble




I would also really like to know whether information hiding means 'hiding the data using visibility identifiers(public,private)' or whether it means 'hiding data representation'.What actually does data representation mean?Could anyone help me.





Totalising and condensing data values from multiple arrays into a single array


My fledgling programming skills have hit a wall. I could get this working, but the code stinks and I'm convinced there must be a more efficient way I just don't know it yet.


I have a web service that accepts the name of a data property as a parameter. Part of the method for handling the request is to go away and get me a load of data for the specified data property. In my case, it says go and get me the current year's target and actual for the 'electricity usage' property in the database.


In my code this is just like:



var data = rSvc.getDashboardPayload(worklocation, property, year);


The is then delivered as a JSON payload that just says (snipped example):



0: {
month: 1
monthName: "Jan"
currentYearTarget: 100
currentYearActual: 90
}


However, a change has come up that we need to produce a chart that is actually just a total of 4 measures in the database. For example: "Hazardous Waste" is the total of non-metallic waste, plus the total of metallic waste, plus the total of incinerated waste... and so on. You get the picture.


So in my code I can get a payload for each measure like this:



var shwl = rSvc.getDashboardPayload(worklocation, propName, year);
var shwi = rSvc.getDashboardPayload(worklocation, propName, year);
var shmwr = rSvc.getDashboardPayload(worklocation, propName, year);
var shnmwr = rSvc.getDashboardPayload(worklocation, propName, year);


Then I can create a new list that will be my output:



var merged = new List<WLDChartsPayload>(12);


Then I can loop through 12 months and go and total up each measure in turn.



for (short i = 1; i < 13; i++)
{
var m = new WLDChartsPayload();

m.currentYearActual = shwl.Where(x => x.currentYearActual.HasValue && x.month == i).FirstOrDefault().currentYearActual;
m.currentYearActual += shwi.Where(x => x.currentYearActual.HasValue && x.month == i).FirstOrDefault().currentYearActual;
m.currentYearActual += shmwr.Where(x => x.currentYearActual.HasValue && x.month == i).FirstOrDefault().currentYearActual;
m.currentYearActual += shnmwr.Where(x => x.currentYearActual.HasValue && x.month == i).FirstOrDefault().currentYearActual;

m.currentYearTarget = shwl.Where(x => x.currentYearTarget.HasValue && x.month == i).FirstOrDefault().currentYearTarget;
m.currentYearTarget += shwi.Where(x => x.currentYearTarget.HasValue && x.month == i).FirstOrDefault().currentYearTarget;
m.currentYearTarget += shmwr.Where(x => x.currentYearTarget.HasValue && x.month == i).FirstOrDefault().currentYearTarget;
m.currentYearTarget += shnmwr.Where(x => x.currentYearTarget.HasValue && x.month == i).FirstOrDefault().currentYearTarget;

merged.Add(m);
}


Then I return the merged list.


But this just feels wrong. I have 10 data points in the payload. The code is getting longer and more repetitive.


But, question is, how else can I "totalise and condense" the values from all four of my arrays into a single array?





Unique_ptr to hold memory for custom VM


I work for a company that use a custom DSL and my job is to port the VM to C++.


I'm trying to do this in compliance with the C++11 standard so i use auto when appropriate, the new for syntax, etc. But I'm having problem trying to "port" a part of the code that uses raw pointers to the new smart pointers.


On this DSL every object is derived from a base class called MObject, for example Numbers are handled by this class:



class MNumber : public MObject {
...
}


The class responsible for handling the VM memory looks like this:



class Mallocator {
...
std::vector<MObject*> memory; //where all objects go...


And to, for example, place a new MNumber in memory this is the function you call:



MNumber* Mallocator::newMNumber(double a) {
MNumber* number = new MNumber {a};
memory.push_back(number);
INCRMEM(number); //updates memory usage and some other stuff
return number;


}


User defined variables are stored on a map like this: std::map<std::string, MObject*> And steps executed by the VM to create a new user defined variable are more or less like this:



//storing a value on the VM stack
MNumber* number = allocator->newMNumber(...); //allocate the object
stack.push_back(number); //put a reference to the allocated value on the stack

//retrieving object from the stack and creating the variable
string var_name = codeobj->getVarName(instr.arg); //get the name of the variable from user code
value = stack.back(); // get the pointer to the allocated object from the stack
curr_frame->env->setVar(var_name, value); //associate the name to the object in the current scope


It makes sense to me that the Mallocator object should hold ownership of every allocated MObject and the stack and the variables map should hold a "reference" to the allocated memory, since they only read the values. After searching the web for a few days and watching the Herb Sutter talk "Back to the Basics! Essentials of Modern C++ Style" i collected a few ideas:



  • On the newMNumber create a unique_ptr and use the .get() method to return a raw pointer. Wouldn't this defeat the purpose of using smart pointers?

  • On the newMNumber return a unique_ptr<MNumber>& and adapt the stack and map variables to work with unique_ptr<MObject>&

  • Use shared_ptr. I don't think shared_ptr is the solution because the ownership is not shared

  • Leave it the way it is and manage the pointers life-cycle myself (i'm already doing this anyway)


So my questions are: what is the right way to tackle this problem? Is my design correct? What other options i have?


PS1: Mallocator is a singleton and it is the sole responsible for allocating the objects and deleting objects from memory the rest of the VM only works with the pointers returned by Mallocator.


PS2: The language has more Objects than just numbers but since i can't share the whole code i've used MNumber as an example.


PS3: Some objects, like strings and integers, are cached so, for example, the function (not shown here) newMNumber(int a) only allow one object per integer to exist.


Thanks.





Help with Game of Life emulator written in python


I have wrote a python script (the features are far from perfect) that will show the next generation in a 5x5 grid of cells if the rules of John Conway's Game of Life. It is used in a linux command line. A 0 represents a dead cell and a 1 represents a live cell. This is the code:


cGrid = [[0, 1, 0, 0, 0], [0, 0, 1, 0, 0], [1, 1, 1, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]


nextGrid = [[], [], [], [], []]


for row in cGrid: for cell in row: neighbours = 0 nCell = 0



rIndex = cGrid.index(row)
cIndex = row.index(cell)

if cGrid[rIndex][cIndex-1] == 1:
neighbours += 1
if cGrid[rIndex][cIndex+1] == 1:
neighbours += 1

if row != 0:
if cGrid[rIndex-1][cIndex-1] == 1:
neighbours += 1
if cGrid[rIndex-1][cIndex] == 1:
neighbours += 1
if cGrid[rIndex-1][cIndex+1] == 1:
neighbours += 1
if row != 4:
if cGrid[rIndex+1][cIndex-1] == 1:
neighbours += 1
if cGrid[rIndex+1][cIndex] == 1:
neighbours += 1
if cGrid[rIndex+1][cIndex+1] == 1:
neighbours += 1

if cell == 0 and neighbours == 3:
nCell = 1

if cell == 1 and neighbours == 2:
nCell = 1
if cell == 1 and neighbours == 3:
nCell = 1
if cell == 1 and neighbours >= 4:
nCell = 0

nextGrid[rIndex].append(nCell)

neighbours = 0
nCell = 0


print(nextGrid[0]) print(nextGrid[1]) print(nextGrid[2]) print(nextGrid[3]) print(nextGrid[4])


The output should look like this: [0, 0, 0, 0, 0] [1, 0, 1, 0, 0] [0, 1, 1, 0, 0] [0, 1, 0, 0, 0] [0, 0, 0, 0, 0]


But it looks like this: [0, 0, 0, 0, 0] [1, 1, 1, 1, 1] [0, 0, 0, 0, 0] [0, 0, 0, 0, 0, 0, 0, 0, 0, 0] []


I haven't got a clue why it doesn't work, so any help would be appreciated.





OutOfMemoryError Java Heap Space due to initializing instance variables in constructer?


For a game I am making I have an Explosion class. Here is the first part:



public class Explosion extends Rectangle {
private static final int FRAMES = 40;
public static Texture expStrip;
private static TextureRegion[] expFrames;
private static Animation expAnimation;

public TextureRegion currentFrame;
public float stateTime;

public Explosion() {
super();
stateTime = 0;
//width = 32;
//height = 32;
}


The code runs as is and I can instantiate as many explosions as I need, but when I uncomment the initializations for width and height in the constructer (the width and height variables are inherited from the superclass Rectangle), the first time an explosion is created i get an OutOfMemoryError - Java Heap Space. I understand you can increase the heap size, but I am new to java and wish to understand what heap space is. From this article http://javaeesupportpatterns.blogspot.com/2011/08/java-heap-space-hotspot-vm.html I understand that heap space is used to store my primary class instances. So why does setting the width and height causes this error? Wouldn't the error more likely be caused by creating too many Explosion instances?





Why shouldn't a method throw multiple types of checked exceptions?


We use SonarQube to analyse our Java code and it has this rule (set to critical):



Public methods should throw at most one checked exception


Using checked exceptions forces method callers to deal with errors, either by propagating them or by handling them. This makes those exceptions fully part of the API of the method.


To keep the complexity for callers reasonable, methods should not throw more than one kind of checked exception."



Another bit in Sonar has this:



Public methods should throw at most one checked exception


Using checked exceptions forces method callers to deal with errors, either by propagating them or by handling them. This makes those exceptions fully part of the API of the method.


To keep the complexity for callers reasonable, methods should not throw more than one kind of checked exception.


The following code:



public void delete() throws IOException, SQLException { // Non-Compliant
/* ... */
}


should be refactored into:



public void delete() throws SomeApplicationLevelException { // Compliant
/* ... */
}


Overriding methods are not checked by this rule and are allowed to throw several checked exceptions.



I've never come across this rule/recommendation in my readings on exception handling and have tried to find some standards, discussions etc. on the topic. The only thing I've found is this from CodeRach: How many exceptions should a method throw at most?


Is this a well accepted standard?





Is there an alternative to instanceof when filtering a Java stream by class?


I have an unexpected situation in a project in which all types extending one class are packed into a Java collection; but only an extension of that class implements a method. Let's call it "also()". Right before performing one task on every item in that collection, I need to call also() on every item that implements it.


The easiest way forward is this:



stuff.stream().filter(item -> item instanceof SpecificItem)
.forEach(item -> ((SpecificItem)item).also()));
stuff.stream().forEach(item -> item.method());


It works fine, but I'm not comfortable with the "instanceof" in there. That's generally a marker of bad code smell. It is very possible that I will refactor this class just to get rid of it. Before I do something that dramatic, though, I thought I would check with the community and see if someone with more experience with either Streams or Collections had a simpler solution.


As an example (certainly nonexclusive), is it possible to get a view of a collection that filters entries by class?





Neural network converges to 0.5 for XoR


I'm coding a neural network in C for an OCR project. Before testing with character recognition, I'm making it learn the XoR operation. Although, the results I'n getting always converges to 0.5 instead of 1 or 0 for all input combinations.


I'm using a learning rate of 0.35 and the activation function is the standard sigmoid function (1/(1+exp(-x)). The network has 2 inputs, 1 bias neurone, 1 hidden layer with 2 neurones and 1 output neurone.


The algorithm for learning the operations looks like this:



initialise network with random weights
while networks doesn't know all operations with 5% precision do:
compute output for all combinations
run the retropropagation algorithm for all combinations
endwhile


I've tried to change the learning rate and the activation function, but none of that solved the issue. Why does the network keeps converging to 0.5 and how can I solve that?





Is there any license which prohibits usage for hiring purposes?


I develop code review tool which analyzes the code and gives it passed grade and output details of code review.


I want to prohibit to use this software for recruiting/hiring purposes. I don't want to be responsible for someone doesn't going to be hired because of my software. I don't want to prohibit for development usage, but I do want to prohibit it for hiring purpose only.


Is there any free existing licenses that prohibit usage of project for hiring purposes? If no, can I modify MIT license for this purpose?


Thank you for attention!





want to build an anti-plagarism software. need help [on hold]


This is a student asking for help! We are trying to figure out how a anti-plagiarism system works. We would like to know if there is a specific algorithm used by all anti-plagarism softwares or if there are different ones for each webpage.



  • Do i need a specific algorithm ?

  • Any place to find it online?

  • Basically how are this free softwares online build?


Your answers will help us develop a sample software for our project at the university. Thank you very much for your help in advance!





Should an event listener be called if attached after the event has already fired?


Should an event listener be called if it is attached after the event has already been emitted? What if the event will only be emitted once?


The first example that comes to mind is the ready event in jQuery. The following snippet, when evaluated after the page has loaded, will still call the callback:



$(document).ready(function () {
console.log("Works.");
});


The alternative to this behaviour could be a flag that is set when the page is loaded, forcing the consumer of the API to check to see if the event has already happened and act accordingly:



if ($.pageHasLoaded) {
console.log("Works.");
} else {
$(document).ready(function () {
console.log("Works.");
});
}


While the above example is in the context of a web page loading where anything and everything (usually) needs to happen after the page has completely loaded, the same arguments could be made for any single component in an application, which has singleton events (load, start, end, etc).





How to create sale returns?


i am new in programming .. i am coding a program for Clothing shop .. first i have tables in my db from them sales order , sales returns , ledger account . so i will ask my question after this example . if i made a sales order with 3 items each item with 100 l.e. so the total order will be 300 l.e. ,the system will save this order in the sales order and the 300 with the day date in the ledger account . the next day the client come and want to return an item with 100 . so the system will save this invoice in the sales return table and in the account ledger with 100. till here all of this is o.k. . my problem is in if i opened the same sales order i will find the 3 items again .. i thought that if i opened the sales order again i will find 2 items only , without the returned item . so how can i fix it or there is another way for the sales returns .. ?





It appears it's an issue with javascript redirect that is being used, and some browsers not supporting that


We have an issue with the redirect javascript that opens links to websites on our directories. For example, if you go to http://www.paontheweb.com/search/?query=wood+stoves&limit=10 and then click AES Hearthplace it opens a blank window (will not complete the redirect) in Chrome and Firefox. Works fine on I.E. and Safari. Pasting in our redirect.php to see if anyone can help. Lost our programmer years ago. PS we took out the email notification thing years back so I'm sure that is not needed. Just don't know exactly what to remove. Any help would be appreciated.


"; print "window.location = 'http://www.paontheweb.com' "; print ""; } $id = $_GET['id']; $referer = $_SERVER['HTTP_REFERER']; $referer = explode("?",$referer); $GET = explode("&",$referer[1]); $cat = $GET[0]; $loc = $GET[1]; $cat = explode("=",$cat); $loc = explode("=",$loc); $catID = $cat[1]; $locID = $loc[1]; $backlink = $_SERVER['HTTP_REFERER']; if (!isset($ad)) { $ad = false; } $host="localhost"; $Sqluser="paonthew_web"; $Sqlpass="paonthe#@"; $Sqldb="paonthew_data"; $db = mysql_connect($host,$Sqluser,$Sqlpass) or die("The DataBase is Down!"); mysql_select_db($Sqldb,$db) or die("I Can't connect to database!"); function validateEmail($email) { $email=strtolower($email); $regexp ="[0-9a-z]([-_.]?[0-9a-z])*@[0-9a-z]([-.]?[0-9a-z])*\\.[a-z]{2,3}"; if(ereg($regexp,$email)) { return true; } else { return false; } } if ($r==1) { $ip = $_SERVER['REMOTE_ADDR']; $date = date("m/d/Y h:i:s A"); $q = "INSERT INTO return_hits (companyID,date,ip) VALUES ('$id','$date','$ip')"; $r = mysql_query($q); header ("Location:http://www.PAontheweb.com"); } else if ($sponsor=="true") { $query = "SELECT * FROM sponsors WHERE id='$id'"; $result=mysql_query($query); while ($rows=mysql_fetch_array($result)) { $clicks=$rows['clicks']; $address = $rows['web']; $email = $rows['email']; $mail = $rows['mail']; $company = $rows['Company']; } if ($email!="") { if ($mail != "1") { if (validateEmail($email)) { $subject = "PAontheweb.com // Email Notification for ".$company; $from = "PAontheweb.com [noreply@PAontheweb.com]"; $message = "This message is from PAontheweb.com to inform you that you had a visitor at ".$address; $message.= " from your sponsored link in the PAontheweb.com online website directory.



"; $message .= "Please note: You will receive this message every time your site is visited using PAontheweb.com to show you the value of your sponsored link.



"; $message .= "Add your events to the new PAontheweb.com events calendar or look for something to do this weekend.



"; if ($type!="1") { $message .= "Consider upgrading your membership for more qualified traffic by visiting http://www.PAontheweb.com/advertising.



"; } $message .= "To stop these notifications, reply to this email with 'Remove' in the subject line.





"; $message .= "Thanks,

The PAontheweb.com Team"; // mail($email,$subject,$message,"From: " . $from . "\n"."MIME-Version: 1.0\n"."Content-type: text/html; charset=iso-8859-1"); } else { echo $email; } } } $newclicks=$clicks+1; if ($id!="") { $ip = $_SERVER['REMOTE_ADDR']; $date = date("m/d/Y h:i:s A"); $q = "INSERT INTO hits (companyID,company,date,ip) VALUES ('$id','$company','$date','$ip')"; $r =mysql_query($q); } $query="UPDATE sponsors SET clicks='$newclicks' WHERE id = '$id'"; $result=mysql_query($query); header ("Location:$address"); } else { $query = "SELECT * FROM directory WHERE id='$id'"; $result=mysql_query($query); $rows=mysql_fetch_array($result); $id = $rows['id']; $hits=$rows['hits']; $company = $rows['company']; $address=$rows['web']; $type = $rows['type']; $email = $rows['email']; $child = $rows['child']; $mail = $rows['mail']; if ($id!="") { $ip = $_SERVER['REMOTE_ADDR']; $date = date("m/d/Y h:i:s A"); $q = "INSERT INTO hits (companyID,company,date,ip,location,catagory) VALUES ('$id','$company','$date','$ip','$locID','$catID')"; $r =mysql_query($q); } if ($type=="1") { $typeName = "Exclusive"; } else if ($type == "2") { $typeName = "Premium"; } else if ($type == "3") { $typeName = "Standard"; } else if ($type == "4") { $typeName = "Free"; } if ($email!="") { if ($mail != "1") { if (validateEmail($email)) { $subject = "PAontheweb.com // Email Notification for ".$company; $from = "PAontheweb.com [forms@PAontheweb.com]"; $message = "This message is from PAontheweb.com to inform you that you had a visitor at ".$address; $message.= " from your ".$typeName." listing in the PAontheweb.com online website directory.



"; $message .= "Please note: You will receive this message every time your site is visited using PAontheweb.com to show you the value of your ".$typeName." listing.



"; $message .= "Add your events to the new PAontheweb.com events calendar or look for something to do this weekend.



"; if ($type!="1") { $message .= "Consider upgrading your membership for more qualified traffic by visiting http://www.PAontheweb.com/advertising.



"; } $message .= "To stop these notifications, reply to this email with 'Remove' in the subject line.





"; $message .= "Thanks,

The PAontheweb.com Team"; //mail($email,$subject,$message,"From: " . $from . "\n"."MIME-Version: 1.0\n"."Content-type: text/html; charset=iso-8859-1"); } else { echo $email; } } } if ($child!='') { $query = "SELECT * FROM directory WHERE company LIKE '%$company%' AND web LIKE '$address%' AND child'true'"; $result=mysql_query($query); while ($rows=mysql_fetch_array($result)) { $id2 = $rows['id']; $hits=$rows['hits']; $newhits=$hits+1; $query="UPDATE directory SET hits='$newhits' WHERE id = '$id2'"; $result=mysql_query($query); } } else { $newhits=$hits+1; $query="UPDATE directory SET hits='$newhits' WHERE id = '$id'"; $result=mysql_query($query); } if ($type != '') { print ""; print "window.location = '{$address}' "; print ""; } else { $company=stripslashes($company); ?> " name="topFrame" scrolling="NO" noresize > " name="mainFrame"> _qoptions={ qacct:"p-e46O2_29tW__g" };



Why do we have to tell printf() the type of data in "C" language?


Let's consider this "C" code:



#include< stdio.h >


main()

{

int x=5;

printf("x is ");

printf("%d",5);

}



In this, when we wrote "int x=5;" we told the computer that "x" is an integer. The computer must remember that "x" is an integer, but when we output the value of "x" in "printf()" we have to again tell the computer that x is an integer, why?


Why the computer forgets that x was an integer.


Thank you.





Overloaded function C++


Overloaded function C++

I don't understand How to create the overloaded function ?

like in this question:

Write a program that mimics a calculator. The program should take as input two integers and an arithmetic operation (+, -, *, or /) to be performed. It should then output the numbers, the operator, and the result. Create four overloaded function for each operator. Note: For division, if the denominator is zero, output an appropriate message. (Hint: use switch)





Conceptually, an iterator points between elements. Does the position reference point to the element to the left or to the element to the right?


Conceptually, an iterator points between elements. Does the position reference point to the element to the left or to the element to the right?





Scalaz: Why use Scala if you're just going to make it as much like Haskell as possible?


Scalaz is a library that provides mathematical abstractions like Functors, Monads, and Monoids for Scala. Pardon my coarse comparison, but that sounds like "Haskell Stuff" to me. So why are so many really smart people I follow on Twitter using Scala with Scalaz and "Type Classes" instead of just using Haskell which has all that stuff already?





Usage of MVVM in iOS


I'm an iOS developer and I'm guilty of having Massive View Controllers in my projects so I've been searching for a better way to structure my projects and came across the MVVM (Model-View-ViewModel) architecture. I've been reading a lot of MVVM with iOS and I have a couple of questions. I'll explain my issues with an example.


I have a view controller called LoginViewController.


LoginViewController.swift



import UIKit

class LoginViewController: UIViewController {

@IBOutlet private var usernameTextField: UITextField!
@IBOutlet private var passwordTextField: UITextField!

private let loginViewModel = LoginViewModel()

override func viewDidLoad() {
super.viewDidLoad()

}

@IBAction func loginButtonPressed(sender: UIButton) {
loginViewModel.login()
}
}


It doesn't have a Model class. But I did create a view model called LoginViewModel to put the validation logic and network calls.


LoginViewModel.swift



import Foundation

class LoginViewModel {

var username: String?
var password: String?

init(username: String? = nil, password: String? = nil) {
self.username = username
self.password = password
}

func validate() {
if username == nil || password == nil {
// Show the user an alert with the error
}
}

func login() {
// Call the login() method in ApiHandler
let api = ApiHandler()
api.login(username!, password: password!, success: { (data) -> Void in
// Go to the next view controller
}) { (error) -> Void in
// Show the user an alert with the error
}
}
}




  1. My first question is simply is my MVVM implementation correct? I have this doubt because for example I put the login button's tap event (loginButtonPressed) in the controller. I didn't create a separate view for the login screen because it has only a couple of textfields and a button. Is it acceptable for the controller to have event methods tied to UI elements?




  2. My next question is also about the login button. When the user taps the button, the username and password values should gte passed into the LoginViewModel for validation and if successful, then to the API call. My question how to pass the values to the view model. Should I add two parameters to the login() method and pass them when I call it from the view controller? Or should I declare properties for them in the view model and set their values from the view controller? Which one is acceptable in MVVM?




  3. Take the validate() method in the view model. The user should be notified if either of them are empty. That means after the checking, the result should be returned to the view controller to take necessary actions (show an alert). Same thing with the login() method. Alert the user if the request fails or go to the next view controller if it succeeds. How do I notify the controller of these events from the view model? Is it possible to use binding mechanisms like KVO in cases like this?




  4. What are the other binding mechanisms when using MVVM for iOS? KVO is one. But I read it's not quite suitable for larger projects because it require a lot of boilerplate code (registering/unregistering observers etc). What are other options? I know ReactiveCocoa is a framework used for this but I'm looking to see if there are any other native ones.




All the materials I came across on MVVM on the Internet provided little to no information on these parts I'm looking to clarify, so I'd really appreciate your responses.





can neural network (ANN) perform well when there is overlapping between data?


My professor told me to search and find out if ANN can perform(be well trained, predict) when our input data overlap each other.


our research field is "multivariate calibration" and our data is 'UV-vis spectroscopy'. the figure attached can show what I'm talking about.


thanks


fig


additional info: professor's paper here_ http://www.sciencedirect.com/science/article/pii/S1386142509006957





Create an Inferface for different data sources but same datastructure


At the moment I have my sourcedata stored in different excel files but in the future I want to use a database. Since I dont want to write everything new when I have to change the source and maybe in the future there will be other possibilities to store my data so I want to write an interface that I can adjust as I want. The import data is the same so I created a Data-Class (or IData Interface) with the properties firstData and secondData (this names are just for demonstration) and do not depend on the source. My idea is writing a Database_Filler Class and a Excel_Filler Class and the both inherit the IData interface. But I am not sure since I have not done that yet. Could anyone help my get this done?





Pre-Compilation Processor:


What I want to do:


Parse source code, search for a beginning and closing tag of my own definition (one that does not conflict with any defined patterns in the programming language), and then replace then everything from the beginning of the opening tag to the end of the closing tag with some function of the data within. (For context: This is part of sort of building a language ontop of an existing language.)


So, say my pattern is @#$.


and I have a line of code:



int x = @#$42@#$;


I would like to replace


@#$42@#$


with f(42), which is some return value of some function f.


I know how to search for the tags and replace everything and that works just fine.


Something to the effect of:



//filePointer points to the beginning of a file
while(filePointer != EOF)
{
//find index of first character of next opening tag
//find index last character of next ending tag
//infer data between tags
//calculate new data from data between tags
//replace index_first to index_last with new data
}


However, where I run into trouble, is that I do not want to perform this replacement if the tags lie within a string literal and can not think of an elegant way to handle this case.


Example:



int x = @#$42@#$;


would have a replacement.



String x = "@#$42@#$";


would not have a replacement.


Naive algorithm considered:


Iterate through file, track pairs of quotes indicating string literals.


Iterate through file again, find my tags, check to see if they are inside of any of the string literals, if so, do nothing.


I just feel that there is a better way that is escaping me.


Any suggestions would be most appreciated.





Does software development model/process depend on software architecture?


I am making an application , the parts of one component of the app are separate from the other but the results given by first component on some data are required for the second component to function and for being tested.I am confused whether I should follow incremental , agile or iterative process.





In a mutual credit network, how would you program an automatic jubilee?


A little explanation might be needed. I mean mutual credit the way that it's defined here:



a type of alternative currency in which the currency used in a transaction can be created at the time of the transaction



Imagine you have a network of accounts. Each starts out at zero and any account can extend a limited line of credit to any other account. My total balance would just be the sum of what others "owe" to me, minus the sum of what I owe to others.


Lines of credit can be represented with a simple table. In pseudo-code for some kind of ORM:



type LineOfCredit struct {
Creditor string, // Account ID of person offering credit
Borrower string, // Account ID of person taking on debt
Owed int, // Amount owed
Limit int, // Credit limit
}


I'll use "$" to represent the currency, though, of course, the units are arbitrary. Imagine that...



  • Bob owes $20 to Sally

  • Sally owes $20 to Joe

  • Joe owes $20 to Bob


It's clear that there's no actual debt here and they don't owe one another anything.


So, how would you detect these kinds of cycles in a balance sheet and then eliminate them? Is this a problem for graph theory? I imagine this can be represented as a directed network graph. My knowledge here is very limited, but I understand it's possible to detect cycles with Tarjan's strongly connected components algorithm, though that doesn't seem to offer much help, especially as those cycles get larger. I also thought that, maybe, shortest-paths could be crunched at the time of a transaction, with the reciprocals of outstanding "debts" represented as edge-weights/distances.


I think Ripple pay possibly did something like this, but I'm having trouble finding a precedent.





vendredi 28 novembre 2014

Recommended programming language


Currently I'm trying to make a horoscope software. This type of software actually gives various predictions depending on various parameters regarding an individual. For this the software is to have a huge collection of rules(may be more than fifty thousand). Based on these rules prediction will be made. Please recommend a programming language and pattern to achieve this goal.


Thanks in advance.





Type Casting in Java


Could anyone explain why short(100000) is -31072 as said in p.48 of java-notes.The article says that "the value -31072 is obtained by taking the the 4 byte int 100000 and throwing away two of these bytes to obtain a short".


The code in the article related to the question is:



int A;
short B;
A = 17;
B = (short)A;




Most Efficient way to Compute the sum of divisors of N (1 ≤ N ≤ 1 000 000 000)


I want to write a code which computes the sum of divisors of a number N(1 ≤ N ≤ 1 000 000 000), excluding the number itself.


However, I need an efficient way to do it. It suppose to print the answer under 1 second. I know it depends on hardware etc. But I have an i7 machine though it takes more than a second (for the worst case scenario which is 1000000000 ) because of my poor code.


So to make it more understandable:


EX: Sample input: 10 --> Output should be: 8 (because we know 1 + 2 + 5 = 8)


EX: Input: 20 --> Output suppose to be: 22 ( 1 + 2 + 4 + 5 + 10 = 22 )


So far i wrote this:



public class Main
{
public static void main(String[] args)
{
@SuppressWarnings("resource")
Scanner read = new Scanner(System.in);

System.out.print("How many times you would like to try: ");
int len = read.nextInt();

for(int w = 0; w < len; w++)
{
System.out.print("Number: ");
int input = read.nextInt();

int remains = 1;
int sum = remains;

/* All I know we only need to check half of the given number as
I learned ages ago. I mean (input / 2) :D */

for(int i = 2; i <= input / 2; i++)
{
if(input % i == 0) sum += i;
}

System.out.print("Result: " + sum);
}

}
}


So the question is How to improve this solution ? How to make it more efficient or let me put it this way. Is there a way to do it more efficient ?


If you could help me and show a solution code wise in Java, I would very appreciate it. Thanks for checking!





I need help figuring out if computer programming is right for me


Basically I just turned 28 and decided that I really want to go to school and get a degree in Computer Science. Specifically to get into programming. But I do not have any computer experience at all. I mean really I just use my laptop for web browsing and typing papers if needed. But I was on youtube about a month ago and came across this computer programming video and it really got my attention for some reason. So I ended up watching more videos and looking up websites and reading about code and the different languages and what computer programming actually is. I recently downloaded this Microsoft Visual Studio C++ program and was reading about typing your first code. Of coarse hello world I guess is the popular first code. But anyways I am very interested in this and told my wife I would like to go to school and get an associates in computer science and eventually my bachelors. I really want to pursue a career in computer programming. But at 28 I am a little worried that by the time I finish school and stuff that I might not be a hot ticket for employers being 30 or 32 with no prior computer history except for my degree. Meanwhile there are 15 year old's writing whole programs already lol. Also being a husband and a daddy to a 3 year old and working full time, I imagine its not not going to be a easy road ahead of me. But definitely not impossible. Anyways I have no one else who can actually help me out with my question and figured I would ask everyone on here who has experience and knows what is expected to accomplish such goals before I set myself up for failure lol. Any information, help or advice would definitely be appreciated. Thank you!





Query on Recursive composition


For the below relation between Container and Componentin java.awt class hierarchy, I see that,


enter image description here


in addition to is-a relation, class Container has composite relation with class Component with below line of code,



/**
* The components in this container.
* @see #add
* @see #getComponents
*/
private java.util.List<Component> component = new java.util.ArrayList<Component>();


But am still not clear with the below diagram wrt operation() method.


enter image description here So,


1) What does class Leaf and class Composite signify in the below diagram?


2) What exactly are we depicting about operation() method in class Leaf and class Composite as per the below diagram?


Note: I am java beginner learning java





Mobile App to Scan Barcode


I'd like to write an app to read a bardcode, IOW, to be a barcode scanner.


The barcode is on a label at the back of our University books. It's how books are identified within our library management system. It's not the ISBN barcode it's our own book #.


The app should scan this barcode and do some other dialogs (student #/pwd etc) so that students might be able to withdraw the book from the library. The app might even have access to the phone # so that I could verify it at our database to check if the # is corrent and then allow the book withdraw.


The point is :


1) Could I do that using HTML5 only ? Cause I'm very fluent with Web Programming... Also the same app might be running at the desktop for instance. I could have PCs installed at the library so that users might do their registrations (for those who dont want to use the mobile).


2) I'd better do an specific app to be installed on the students mobile phones ? Since I dont know any platform for doing this very likely I'd start with some Python stuff....


Other ideas ?


Thanks in advance !





Unit testing the variables passed to the view from the controller


Let's say I want to test a controller that gets some value from a service and then pass some of all of those values to the view.


Do you test that the view gets the result that the controller took from the service, without taking care of seeing the exact variables being passed, or do you test specifically for the variables that you need on the view?


So if in the view you have var 'foo' and 'foo2', you can test that the controller is simply passing the info it gets from the service, or you can test that the variables being passed are effectively called 'foo' and 'foo2'.


What approach do you use?





iOS Eye Tracking


Long story short: My mom passed away from ALS when I was little, I've always wanted to develop something that might improve the lives of others (and potentially myself in the future) with ALS and related diseases, and I'm an iOS developer who has found that there seems to be nothing thus far addressing this issue on iOS devices.


What I'm envisioning is similar to the Hawking-esque characters on screen, but rather than blink when certain characters are lit up, I think it could be nice to be able to look at groups of characters and have the camera detect where you're looking and use that to drill down ultimately to the character, word, etc., desired.


At first blush this doesn't seem too difficult, but then once I start thinking about it I come to the realization that it is absolutely a non-trivial thing to work out - all the math around the angle of gaze, distance from camera, etc...


Does anyone have any information that might lead me in the right direction? Other open-source applications doing something similar, maybe projects that use parts of this, like eye detection + location on screen, and so on... Perhaps other considerations that would make this essentially not doable with the current tech? Anything would help, thanks!





What is the design pattern for WordPress Core?


What is the design pattern of WordPress Core? As this Stack Overflow question shows, WordPress does not follow the MVC pattern; however, developers can write plugins and themes that follow MVC. But my question pertains exclusively to WordPress Core, not to any additional add-ons, themes, extensions, plugins, or forked projects that may or may not follow an MVC pattern.


If WordPress Core does not follow an MVC design, then what design pattern does it follow?





STMicroelectronincs (CR95HF) NFC Reader [on hold]


For a project from school I want to do something with NFC. I received an NFC reader from a teacher and said that I could borrow it. At this moment I have only experience with C#. Now I was wondering if some people here have used the CR95HF (MB1054A) from ST Micro Electronics before and know if it is possible to write some code for the reader in C#. When there is some sample code available the would be great!


I searched the website ( st.com ) but couldn't find any library.


Thanks in advance!


Jules





What is the point of making a syntactic distinction between standard and user-defined types?


Although here I will refer specifically to C++ and Bjarne Stroustrup's naming conventions, in principle, I've seen that people use somewhat similar rules for other languages here and there.


So, the basic idea is that one should be able to distinguish standard types from user-defined types while reading the code. For instance, Bjarne Stroustrup suggests that one uses



an initial capital letter for types (e.g., Square and Graph)



which, taking into account that



The C++ language and standard library don't use capital letters



allows achieving the goal mentioned above.


But why do we need to do so? What can be the purpose of distinguishing standard and user-defined types?


I could not find any Bjarne Stroustrup's reasoning on that matter, and besides, I myself think in diametrically opposite way. :D I know, I know, "Who am I to dispute Stroustrup?" But, listen, a bunch of the C++ language features, e.g. operator overloading, serve the purpose to allow user-defined types a similar level of syntactic support as standard types. And then all this is baffled by a different naming discipline...


P.S. Not to mention that often one word is not enough to name a class and an underscore-separated word that starts with a capital letter looks so foreign.





Should I accept empty collections in my methods that iterate over them?


I have a method where all logic is performed inside a foreach loop that iterates over the method's parameter:



public IEnumerable<TransformedNode> TransformNodes(IEnumerable<Node> nodes)
{
foreach(var node in nodes)
{
// yadda yadda yadda
yield return transformedNode;
}
}


In this case, sending in an empty collection results in an empty collection, but I'm wondering if that's unwise.


My logic here is that if somebody is calling this method, then they intend to pass data in, and would only pass an empty collection to my method in erroneous circumstances.


Should I catch this behaviour and throw an exception for it, or is it best practice to return the empty collection?





How to avoid switches?


I use Laravel as a PHP framework, although the question is not exactly about laravel, more about structuring controller methods.


I have a route to orders page. Depending on the user role I need to include different views and I have different logic for each role. It looks like this:



public function index()
{
switch ($this->user->role->name) {
case 'admin': {
// Some code
break;
}
case 'customer': {
// Some code
break;
}
case 'manager': {
// Some code
break;
}
}
}


I repeat this pattern for all routes which are accessible for many roles. I know that using repeatedly if/else, switch or this kind of stuff is not the best solution. Also the function becomes quite big (not much but depends on logic). Of course I can break it into 3 subfunctions lie (indexAdmin, indexManager, indexCustomer) but am still not sure if it's good.


Could anybody explain how to deal with it, preferably using Laravel (I use 5 dev version)?