vendredi 27 mars 2015

OS Development in C [on hold]


I'm almost too new in C. I come from a python background. However, I'm studying operating systems and I found out that most operating systems are built in C due to speed and ease of processing . So I would like to get help. I'm running on Linux and I'm attempting to create a simple operating system in C.

Somehow, I can't seem to get where to begin from because I was thinking of creating my own bootloader, of which I have no idea. Any help? Like, I do not really want the bootloader, I just want to know how I'm going to start off. Of course I know how my operating system should look like but my only problem is where and how I'm going to do my testing.

This is what I want:



  • Create a kernel

  • Create a GUI

  • Link the GUI and the kernel

  • Process inputs and outputs


Any help guys? I have no idea!





REST Services with ASP MVC WebApi architecture feedback


I'm working on a new project and I had to design some REST Services with ASP MVC WebApi.


I would like to show you my app architecture and learn from more experienced architects what I have potentially done wrong (I'm not an experienced architect). Can you please let me know your thoughts and recommendations?


Self-identifiable and self-validatable entities


All my entities inherit from BaseEntity<T> which is a generic because is implementing IIdentifiable<T>.I created IIdentifiable<T> in order to be able to have a unique way of getting the id of an entity. The entity Ids don't always use the same data type that's why the interface is generic.


BaseEntity<T> base entity also implements IValidatable which provides with a unique way of validating an entity.


enter image description here


Data access layer


All my repositories implement IRepository<T, IdT> which is used to implement the basics default CRUD operations. T is the entity type and IdT is the type of the entity ID.


The repositories don't implement directly IRepository<T, IdT>, for example, TermRepository implements ITermRepository and ITermRepository implements IRepository<Term, int>. I did it that way so I can add the Term non-standard CRUD operations to the ITermRepository interface.


enter image description here


Service layer


I have created a generic abstract class BaseHttpController<T, IdT> which implements IService<T, IdT> just like in the data access layer T is the type of an entity an IdT is the type of the entity's ID.


I don't have to implement the default REST operations because they are implemented in the BaseHttpController<T, IdT> class. BaseHttpController<T, IdT> has access to IRepository<T, IdT>


If I need to implement something non-standard I can do it in the in the controller. From a controller (e.g. TermController ) I can access its repository (e.g. TTermRepository).


All the REST services return a generic Response<T> object to wrap the entities and errors.


enter image description here


Note: I'm using IoC and each layer is in an independent DLL.


Thanks!





Is the target of 3 dependencies per class always achievable?


I'm reading the Clean Code book and a chapter says that if a class has more than 3 dependencies is a code smell of that class isn't doing one thing. Or what is the same, it isn't following SRP. I'm thinking in certain scenarios in which I am unable to reset the number of dependencies to stick to that number.


Let's say we have an app that connects to a public API REST what offers varied information about a lot entities in our domain. In our app we detect an use case repeated in many places where we request to the API the info about an entity with other dependent entities that it has.


The API REST doesn't offer the data in the format we want because the calls when can make are to get data from a single table on the web database, not offers the data agrouped with other tables as we want. So our use case have to make different Api Call's for to get all different data about the entities we need and then merge in the model we will use in the app.


To connect with the external subsystem we will hide implementation in a single Service class however this class has grown too much resulting a class with a lot methods to get data about all entities of the api rest. So we split this huge class into differents following the Repository pattern. Each class for each possible operations with an entity on the API.


Then, to hide all this concrete and common interaction with the service layer we will use a Facade class to coordinating all this calls. The problem I'm figuring it will have, is that it will have a lot dependencies in her constructor. Will have classes for each repository class and mapper classes to adapt the web data into app data.


The solution in these cases is merge all related dependencies in one so you reduce the number. One example is this: Refactoring to Aggregate Services. http://ift.tt/1eEbm4f


But you merge when you see a clear relationship. What happend if in your class you can't see that? All classes are granulated but all of them are necesary to achieve the goal but can't not be merged in an aggregate service.


So my question is, the "rule" that more than three dependencies violates SRP is always applicable? Returning to our example, our facade needs to access many repository classes and mapper classes. The mapper classes can be hide on a agreggated service, maybe, but repository classes are fine like are. We could introduce a service locator to store them but it is a very bad practice.





Are there any compilers that will turn an else-if cascade into a switch?


I don't like switch in C and its descendants. Maybe its the need for a break or the clumsiness of the syntax requiring a shifting of mental gears, I don't know.


Whatever the reason, I will almost always write a sequence of else-if conditions examining the same variable rather than write a switch.


I see from http://ift.tt/1ICPGCZ that switch is more efficient in most cases and it got me wondering...


Are there any compilers (for any language) that will detect a number of else-if conditions on the same value and internally re-write it into a switch?





How to create DFA from regular expression without using NFA?


Objective is to create DFA from a regular expression and using "Regular exp>NFA>DFA conversion" is not an option. How should one go about doing that?


I asked this question to our professor but he told me that we can use intuition and kindly refused to provide any explaination. So I wanted to ask you.


"Regular exp>NFA>DFA conversion" is not an option because such conversation takes a lot of time to convert a rather complex regular expression. For example, for a certain regex "regex>NFA>DFA" takes 1 hour for a human being. I need to convert regex to DFA in less than 30 minutes.





Closing Nonduplex Unnamed Pipes in C


I have 8 children, and am trying to use 8 pairs of nonduplex unnamed pipes to communicate with them. Thus, I have 2 pipes for each child and 16 pipes in total (one for childRead_ParentWrite and the other for parentRead_ChildWrite).


Anyway, my main question is when to close the pipes. I was taught to initially close the sides that are not being used by the process, and then when the process is finished with its side of the pipe, to close it off. However, I am brand new to the subject and am having some trouble. Here is my code:



// The 16 pipes
int fd_childReads_ParentWrites[8][2]; // Parent closes 0, Child closes 1
int fd_parentReads_ChildWrites[8][2]; // Child closes 0, Parent closes 1

// The 16 buffers
char buf_ChildReads_ParentWrites[8][80];
char buf_ParentReads_ChildWrites[8][80];

// CREATE THE PIPES

// FORK THE CHILDREN


// Manage processes
if (pid == 0) // CHILD
{
printf("I am the child: %d\n", getpid());
// Close the appropriate pipe ends
close(fd_childReads_ParentWrites[playerNumber][1]);
close(fd_parentReads_ChildWrites[playerNumber][0]);


// CHILD DOES STUFF WITH PIPES


// When finished, close the working child pipe ends
close(fd_childReads_ParentWrites[playerNumber][0]);
close(fd_parentReads_ChildWrites[playerNumber][1]);
}
else // PARENT
{
printf("I am the parent: %d\n", getpid()); // NOT BEING PRINTED

// Close the appropriate pipe ends
for (i = 0; i < NUM_PLAYERS; i++)
{
close(fd_childReads_ParentWrites[i][0]);
close(fd_parentReads_ChildWrites[i][1]);
}


// PARENT DOES STUFF WITH PIPES


// Finally, close the working parent pipe ends
for (i = 0; NUM_PLAYERS < 8; i++)
{
close(fd_childReads_ParentWrites[i][1]);
close(fd_parentReads_ChildWrites[i][0]);
}
// Wait for the children
for (playerNumber = 0; playerNumber < NUM_PLAYERS; playerNumber++)
{
wait(NULL);
}
}


I must be doing something wrong. The program prints out the correct number of children, but the parent's printf() line is never printed. When I take out all of the close() functions it prints, but even taking out solely the children's close()'s doesn't print he parent line.


If someone could explain to me the correct way to close nonduplex unnamed pipes in a situation like this, that would be awesome.





Which view resolver is required for implementing tiles in Spring 3.0 MVC application


I have a working Spring application. I would like to add some common headers,footers and such, hence I need to use tiles along with this. Currently, I use InternalResourceViewResolver for request mapping in Spring. I read somewhere http://ift.tt/1xEBxEF that we need urlbasedviewresolver. Do we need both viewresolvers? Could someone clarify this ? How to redirect to tiles from the controller class?





Get info to your site from another site


can anyone help me to find a way to get UserKey from TrueCaller ! And.. How can i build a code in C#,to get informations from another site An exampel.. i need to get info about a certain phonenumber like address,name...etc !





Should I initialize a member variable in declaration when it is initialized by a constructor parameter?


Which is recommended:



class Foo
{
public X x = new X();
public Foo(X _x)
{
x = _x;
}
}


Or



class Foo
{
public X x;
public Foo(X _x)
{
x = _x;
}
}


Please note in the second version, it is probable that I introduce other constructors where x may not be initialized!





How to draw rectangles for 2D arrays


I have an 2D boolean array that looks like this:



[0][0][0][0][0][0][0][0][0][0]
[0][0][0][0][0][0][0][0][0][0]
[0][0][0][0][0][0][0][0][0][0]
[0][0][0][1][1][1][0][0][0][0]
[0][0][0][1][1][1][0][0][0][0]
[0][0][0][1][1][1][0][0][0][0]
[0][0][0][1][1][1][0][0][0][0]
[0][0][0][1][1][1][0][0][0][0]
[0][0][0][0][0][0][0][0][0][0]
[0][0][0][0][0][0][0][0][0][0]


(0 = false, 1 = true)


I've found a way to combine neighbouring zeros on the horizontal plane like like:



[----------------------------]
[----------------------------]
[----------------------------]
[-------][1][1][1][----------]
[-------][1][1][1][----------]
[-------][1][1][1][----------]
[-------][1][1][1][----------]
[-------][1][1][1][----------]
[----------------------------]
[----------------------------]


The code for achieving this is as such:



for y = 0 to ySize
for x = 0 to xSize
if array[y][x] = 0
set width = 1

for x2 = x + 1 to xSize
if array[y][x2] = 0
width++
else
break

add object at x, y and set width to width
set x = x + width - 1


So it loops the 2D array looking for zeros, and if it finds one, it loops until the end of the row to find where it is no longer a zero.


It then creates an object at the position where it first found a zero, and stretches it to fill the part until it is not a zero.


I want to adapt this code in order to make rectangles instead of long planks, like:



____________________________
| |
| | <------ rect at 0, 0 with size (10, 3)
|____________________________|
| |[1][1][1]| |
| |[1][1][1]| |
| |[1][1][1]| | <------ rect at 6, 3 with size (4, 5)
| |[1][1][1]| |
| |[1][1][1]|__________|
| | |
|_______|____________________| <------ rect at 3, 8 with size (7, 2)

^
|
|
rect at 0, 3 with size (3, 7)


So instead of making 15 horizontal planks, it makes 4 rectangles that surround the ones.


In short, I want to create an algorithm that will, when given an 2D array of ones and zeros, create rectangles around the ones.


For a smaller example:



{
[0][0][0] { 0, 0, 0 },
[0][1][0] { 0, 1, 0 },
[0][0][0] { 0, 0, 0 }
}


Will return the position and dimension of rectangles such as:



[-------]
[-][1][-]
[-------]

{
{0, 0, 3, 1}, //rect at (0, 0) with width 3, height 1
{0, 1, 1, 1}, //rect at (0, 1) with width 1, height 1
{2, 1, 1, 1}, //rect at (2, 1) with width 1, height 1
{0, 2, 3, 1} //rect at (0, 2) with width 3, height 1
}


What should this algorithm look like?


Edit: There should be some effort to minimize number of rectangles used (otherwise, it could just leave it as is).


Also, it doesn't matter if it prefers horizontal or vertical rectangles. Example:



[-------]
[-][1][-]
[-------]


is the same as



_ _
| |[ ]| |
| |[1]| |
|_|[ ]|_|


In the end, both have 4 rectangles surrounding the [1].





Programming Concepts [on hold]


Can someone tell me the all the programming concept to be an expert programmer ? like Delegation, Classes etc.. any good books to learn those all the programming concepts that i can go from beginner to advance ? Please give me all the programming concepts that i need to know to be a good programmer. I know this may be off the topic of this forum. But I really really need help from you guys. This is the only place i know where i can get advice from expert programmers. So please help.


Thank you very much





how we can use class and components?


ans me that ques immediadiately its urgent





How is this data filter technique called


A while ago I read about a data filter technique or algorithm that could quickly determine if an object was not similar to an object in a group of objects. It was explained as having multiple overlaying stencils where each object is one stencil. The object (imagined as a cut out piece of paper) is placed underneath these group of stencils.

If some of the object is visible, than you know for certain that it is not similar to one of the other objects/stencils; if the object was not visible, there is a change it is similar to one of the objects, but that is not certain.


This is used for fast determining negatives, while a possible positive takes some more time (it must be compared to all of the other stencils to proof similarity).


I can not remember the name of this technique and I want to read more about it. How is it called?





Reading from html page that needs cookies passed and form data


I am writing a program in java in order to practice tough coding problems and learn more.


Program description The program reads first names from a text file one by one, then enters them into facebook search bar, and WITHOUT hitting enter, it sees who the first person is that pops up(when you type a name into facebook searchbar people drop down) and takes the name and stores it into a text file. Aka it sees which people are the first result for a list of a bunch of names.


The problem I am having with this is 2 fold.



  1. the search option on facebook isnt avalible unless you are logged in, meaning the cookies for the log in session would need to be passed else facebook.com just reads its home login page.

  2. the search bar needs the name entered into it in order for the results to drop down and apear in the source code/element info, I am especially unsure how to do this part since it seems like a special form of query since you arnt really submiting it, its just typed and results apear even before you hit search. (like googles recommend search feature)


Does anyone have any code examples or references to code examples that would help explain how to go about doing either or both of these 2 things. Have been stuck for a long time, thanks.





Should I ever reset object state?


I have a series of TextBlocks which are drawn on frames to make a video of a book. I do it when user click on Make Video. User may change the content of some blocks and click again on Make Video. I should reset some state of the TextBlocks (e.g reset LastWrittenWord to null). As I discussed it earlier it is a sign that I have mixed two responsibility for TextBlock (Drawing, Preserving content).


I would like to know can I conclude, every time which I need to reset some state of an object, I have had a bad design? I think on each click on Make Video I should instantiate some TextBlockDrawer to draw the TextBlocks again instead of resetting the object state!.





jeudi 26 mars 2015

I'm really terrible programmer. please help


I'm doing my 3rd year in BSc Software Engineering. I managed to pass all the exams but. I'm really a terrible programmer. I want to learn everything about programming concepts. but don't know where to begin and what to do. I got some knowledge from following Lynda video tutorials. But when it comes to doing projects and homework. I can't do anything. I really love computer/technology stuff. But I'm really bad at programming and think logically. I've really bright people in my class they can learn anything fast and I don't know. I can't do that. I'm okay with reading lecture slides and getting good marks for other subjects like Software engineering, operating systems but really bad at programming and logical stuff.


When i ask my smart friends how they learn those. they just tell they're learning from searching in google. I tried to do that and it's not working. I'm really frustrated. Please suggest me the way to become a better programmer and improve logical thinking. How should i study to get those skills ? I've to do several projects in this semester and I can't do those because I'm not good at programming. I've to work with C#/WPF, C, Java, Objective C and C++





Microservice architecture: single database owned by a single service?


We're rebuilding a system in a microservice archiecture. I know the standard practice for SOA is to have each individual service responsible for its own database.


However, does it make sense to have one 'database' service responsible for handling a monolithic database (i.e. holding users, orders, inventory, etc in one db)? Is this something that's considered reasonable?


Or is the expectation that users, orders, inventory will all have their own separate databases and according services? If that's the case, how do I handle it when I want to do a simple relational query like ordering a list of inventory by how many orders we've had for each item?





Advantage of Declaring and Initializing Different Object types?


I am learning how to use java to program, and am just learning about abstract classes and how they are useful. Say I have a class which extends another abstract class, which has 2 methods, one of which is abstract. My other, nonabstract class has 4 methods, two of which are the same as in the abstract class, and also defines the abstract method. When initializing my second object, my course tells me to use: (abstract class) foo = new (nonabstract class)(); My question, is that using this code prevents you from using the methods that have been added in the nonabstract class, and as a result, what is the advantage of using that code over (nonabstract class) foo = new (nonabstract class), which lets you use both the methods in the abstract class and the methods added in the nonabstract class. Thanks for the help in advance.





When to make a method part of an interface or a concrete implementation?


I create an interface for database access to a MySQL database. Currently, this is the only way to access day, but to make it easier to test and in the event that the data access might change, I used an interface, however, now I am faced with the dilemma of which methods I should put on the interface and which methods I should put on the concrete implementation directly. Is there a rule of thumb for this? I will give an example below where I have some CRUD operations for a ICar interface, but then some other utility functions that are just on the concrete implementation. Should these be on the interface as well? I wouldn't want a user to have to implement every method if they didn't need to?



interface ICar
{
Car GetCar(int id);
void DeleteCar(int id);
void InsertCar(Car car)
Car UpdateCar(Car car);
}

class Car : ICar
{
Car GetCar(int id)
{

}
void DeleteCar(int id)
{

}

void InsertCar(Car car)
{

}

Car UpdateCar(Car car)
{

}

// methods not on interface, but should they be

public string GetCarVIN(Car car)
{

}

public string GetCarColor(Car car)
{

}

public string GetCarMake(Car car)
{

}

public string GetCarModel(Car car)
{

}

public string GetCarOwner(Car car)
{

}

}




When did Agile Develop,ment Life Cycle start taking of?


When did the ADLC really start taking off and become 'main-stream', ie: more than just a 'few' development teams were working within it?





Non-fixed-size Fenwick Tree implementation


I'm planning to implement a non-fixed-size Fenwick tree. That is, a Fenwick tree that allows interleaving range queries with adding/removing elements.


All implementations and samples I've seen so far are for fixed-size Fenwick trees, where the number of elements is known before preprocessing the frequencies. They use a fixed size array, so it's not possible to add or remove elements after preprocessing is done. (Well, it is possible, but I'd need to re-build the structure).


I thought of extending TreeMap or maybe AbstractMap, but as TreeMap is actually a red-black tree, I don't know how to implement the red-black mechanics (so that the tree remains balanced) without loosing the cumulative sums of nodes involved in the rebalancing process.


So I thought that maybe I should take another approach: why not extend or adapt a simple random access ArrayList and re-calculate all cumulative sums when the underlying array is resized? This would of course have an impact but, hey, that's exactly what a HashMapdoes.


This is why I wanted to ask here first, in case someone has already done it, and to check which approach you think is the best.





array loop never stop



<?php
$ulang = true;
for ($i=1; $i <=3 ; $i++) {
for ($j=1; $j <= 7 ; $j++) {
if ($c[$i][$j] == $cS[$i][$j]) {

}else{
$ulang = false;
}
}
}
?>

<?php
if ($ulang == false) {
// echo $stop;
?>
<form action="kms.php" method="POST">

<?php
}else{
// echo $stop;
?>


i have a problem with my project, loop never stop. whats is wrong with my syntax? please help me!





Pattern for validating rules having different signatures


I have a class in charge of responding to an input event and maybe triggering another event. To decide, it has several rules to check.


I'm trying to get away from a class looking like this:



public class MyClass {
public void maybeTriggerEvent() {
if (!condition1 || !condition2) {
return;
}

// All rules have passed
triggerEvent();
}
}


I'd like this class to know that it has rules to pass, but not know about the implementations of rules. My attempt was to transform it like so:



public class MyClass {
private Rule[] rules;

public MyClass(Rule[] rules) { this.rules = rules; }

public void maybeTriggerEvent() {
for (Rule rule : rules) {
if (!rule.passes()) {
return;
}
}

triggerEvent();
}
}


where a Rule has this interface:



public interface Rule {
boolean passes();
}


Here comes my problem: I now have a new rule that takes in a parameter. Its passes method would require a String parameter. Is my foundation wrong with this new requirement? I don't see how I can adapt this pattern to accommodate rules having various parameters.


This parameter would indicate the source of the input event. I can modify maybeTriggerEvent to receive this value from whoever calls it, and change the Rule interface to be boolean passes(String str). Only now, the majority of my rules are getting a parameter they don't care about.


This is in the context of an Android app, where MyClass would be instantiated on different fragments.





Is there a CMS that can be hosted online but is merely a backend for a desktop application?


All the CMS's I've used and read about are geared toward building websites. I need to make a desktop application that connects to and grabs data and settings from a CMS-backed online source. There would be no public (or private) website. There would only be a CMS that allows changing the text, fields and data of everyone's installed desktop application.


The desktop app might be in Java or C++ or even a Chrome app.


Is there a CMS made for this type of situation?





Accessing intermittently available resources with transactions and post-access cleanup in a generalized, functional, composable way


The following psuedo-code illustrates what I'd like to be able to do. Is there a way to accomplish something like this in Scala?:



trait IntermittentlyAvailableResource
trait AlwaysAvailableResource
trait Transactional
trait CleanupAfter
sealed abstract class TransactionResults[A](val result: A)

class Something {
def grabItemFromQueue: Future[Item] = ...
def ifNoResourceAvailable = ...
def queueItemCleanup(item: Item) = ....
def queueItemTransactionCommit(item: Item) = /* delete from queue*/

val QueueGrabber grabs an IntermittentlyAvailableResource and performs an operation with Transactional and CleanupAfter ...
(ifResourceNotAvailable execute ifResourceNotAvailable)(cleanup execute queueItemCleanup)(commit execute queueItemTransaction)

def something = {
QueueGrabber.with{
resource =>
//operate on resource without worrying about cleanup, commit, availability, etc
}

}
}




Create a Winforms Flowchart Control when performance matters: Set of controls / Handle everything manually (painting, user interactions, etc.)


I am currently trying to create a Flowchart / Diagram Control (e.g. NShape) and I am struggling about what to use to manage the primitives (rectangle, rounded rectangle, square, circle, arrows, etc) and their respective user interactions (drag-and-drops, re-sizing, texture, etc.).


Is it better for performance matters to use a set a control for each of them? Therefore, a dummy hierarchy with a Shape Control as a base class can designed and other related paintings and region definitions defined in sub-classes.


On one hand, the good thing is that in this way, I can provide a very simple way to handle the user interactions through the events available in the Control class. In the past, I've already had done something pretty close to this approach and that was pretty straightforward.


On the other hand, I am not sure it is really performance-wise since there is a need to create hundreds of controls and therefore a lot of handles. At the same-time, it seems like doing otherwise is like re-inventing a lot the wheel and not taking any advantage of what is already existing and the point is that I do not feel quite confident to start something brand new to make it performant enough with a pretty low footprint, i.e. generating 300 primitives without having the canvas becoming sluggish when the user is about to interact with them.


Any insights about what I want to achieve?





Are there any good books/articles to understanding the complete development, build, automated test, deployment phases?


I've primarily been in a role as a developer and am looking to expand my knowledge into the other realms of the development -> deployment process.


Are there any articles/books that would help in this? My primary focus is currently with the Microsoft stack (mvc, webapi, ef), but would also love to learn another language/stack and the process if there are articles readily available for that.


I'm primarily looking at how someone would integrate the different aspects when setting up a project. What I know of (and do let me know if I'm missing something):



  1. development

  2. source control management

  3. automation (unit/integration testing)

  4. continuous integration


  5. deployment/caching and production management.


    My primary focus will still be on development, however I would like to begin learning about the other aspects and so anything that could point me in the right direction (articles/books/online courses) would be very helpful.


    Thanks in advance!







What are the big pros and cons of using Kivy over Java and Java over Kivy?


I know python very well and would like to use it as a medium of developing, but Java is fine with me too.


Things like...


(all these are theoretical)



  • worse workflow with kivy?

  • cannot use native android studio

  • GPS slower to access

  • updates harder

  • cannot use third party extensions like Vangle

  • harder to run and build

  • too much porting





When to use ANTLR and when to use a parsing library


I've always wanted to learn how to write a compiler - I've decided to use ANTLR, and am currently reading through the book (its very good by the way)


I'm pretty new to this, so go easy, but the jist seems to be that you write your grammar, transform this into a data structure (usually an AST) and then walk this one or more times actually executing the 'meat' of whatever you want your program to do.


If my input "language" was something like JSON or XML, i.e something that probably has a library that can turn it into a graph of pojos - does this negate the need to do the lexing and parsing with a compiler compiler like ANTLR? clearly if my input is very bespoke then I need to write my own lexer/parser - but could I and should I short-cut this if my input language is already broadly used.


Would be fair to say you could parse, say json, with Jackson,into POJO's and then drive your code of the resulting pojos? - or in this case, does a 'proper' compiler compiler offer some advantage?


Thanks, Ace





How to approach code review with limited resources [on hold]


I've been given the following task:



A company is giving source code for its product (comprising over 1 million lines of C++, Java, with some assembly) for my review. The code will be loaded onto a Windows machine that I do not control, has no USB ports, no network, and is a small controlled room. I must somehow sift through the code, figure out where the implementation of Action X is, and then trace through the code to see how Action X ties into the rest of the product.



The last time I did this, they gave me the code along with Notepad. Since I couldn't add software, that was it. I found myself using DOS command shells to get a grep-like ability with FINDSTR /R but this was painful, as you might imagine.


My question: how might one approach this chore in a logical and efficient manner? If you were given this task, how would you approach it?





Where can I find an easy summary of best Python programming practises?


Where can I find a compact summary of best Python Practises, preferably in poster format or a few pages long?


Giving my project group a website is in my eyes not too effective, since I'd like to have something that they can glance back on quickly and easily understand. I've tried Google but seem to have no luck.


Backstory: I'm in a project group with 8 people with a moderate volume of code, written in Python. I was able to convince them to use Git at the start of the project, that has worked quite nicely. What I am now having a greater problem with is trying to get people to use some decent code formatting. I spent no less than 8 hours deciphering spaghetti code today that had no spaces, no comments and home-written functions for stuff that was available in libraries.





Upgrading inherited 3rd party code with changes


I inherited a php project of 3rd party code with a good deal of company-specific customization lumped on top of it. Now I've got to upgrade it and the person who owned the project is the one I've replaced and no one else knows what changes are 3rd party changes and what changes are company specific.


It's not too terrible a situation because he did check in the initial version of the application from a few updates back. But then he checked in 2 or 3 updates and about 10 or 15 patches.


So, say I've got a completely generic 3rd party version from the company we bought the code from. How do I go about merging the changes the last developer made into a fresh version. We're using git.





Use of FindWindow and window handles within a Windows service


I've got a third-party vendor who is installing a series of Windows services to a (Windows 2008 R2) server in my control. Whilst attempting to run each service under its own least-privilege account, we have hit upon obligatory permissions issues. These only seem to be resolvable by running the service as Local System -- even membership of the local Administrators group is insufficient.


The issue appears to stem from some IPC-related code, which is built around a single .NET class, referenced by the individual services.


As far as I can tell from the IL disassembly (via Telerik JustDecompile), the IPC class derives from System.Windows.Forms.NativeWindow and sets up a WndProc override to handle a custom message.


Each service instantiates the IPC class with a given name parameter, which it passes as the NativeWindow's title and, when it needs to send to the other service, uses the Win32 API FindWindow method (called as Win32.FindWindow(null, targetName)) to determine the handle of the hidden NativeWindow of the target service, and calls PostMessage on that handle, to trigger the remote action.


The issue appears to be that, unless run as Local System, the call to FindWindow only returns a zero-handle, which the sending service perceives as the target service not being found. As mentioned, even when run as a member of Administrators, it still appears to return the zero value.


I thought this might be an issue with Session #0 isolation but, since this is all service-to-service IPC, rather than service-to-desktop, all executables are running in Session #0, anyway.


There's not much I'm going to be able to do about this -- business needs must, after all -- but, from a theoretical perspective:




  1. Am I right in thinking a global, named EventWaitHandle, with a while (true) { _h.WaitOne(); /* handle event */ }-style message loop, on its own thread, is the more-appropriate option for this kind of work?




  2. Is this a case of permissions to the window handle (do such things exist?) and, if so, could these be changed (e.g. with DuplicateHandle); or does a Windows privilege exist (e.g. in Local Security Policy / User Rights Assignment) that permits/overrides access to the handle? (I considered SeDebugPrivilege, but local Administrators already has that.)




  3. Is there anything that documents the inappropriateness of FindWindow/PostMessage for this kind of work (specifically for service-to-service IPC)? i.e. is this a known limitation for FindWindow, with which I might beat the third-party over the head?







How to code a Data Scrapper


I’m a javaScript beginner. For a practice project, I want to create a Page Scraper that will list of all classical musicians, (say from classicalmusic.com), and then have that data returned in a categorical order. i.e. NAME, CITY&STATE, and EMAIL ADDRESS. Will I need to write a script that would page scrape for this data? Or is there a Data Scraping engine, that I can build this around?





Undefined index looping through json associative array in php


I'm having an issue with a json associative array. If I print_r this:



print_r ($boxscore['game']['home']['players'][0]['statistics']['hitting']['ab']);


It will return a result. But if I try to use a foreach loop through that array:



foreach ($boxscore['game']['home']['players'] as $home)


I get this error:


Severity: Notice


Message: Undefined index: players


I have several json associative arrays that work fine but I can't quite figure out why this one isn't working. Even weirder is I can go a few levels deeper than where I'm getting the error and print_r a value.





What to call "server" software the requires a gui? [on hold]


We require a dedicated copy of our desktop application to be running to support a number of tasks. One of these tasks requires a 3rd party active x control that must be in a GUI to function correctly (vendor will not budge and no alternative in site).


This means that we essentially have "server" sofware that require an active user session, eg someone must logon before the "server" can run.


We have been trying to find a name or term to describe this setup. We cannot use the term "server" anywhere in the discussion as it brings up too many assumptions: beefy hardware, high cost, processes and services, major IT involvement, etc.


So the question is, what do you call "server" software that runs in user mode with a gui?





Use of SAL annotations for C++


Code analysis tool for visual studio is able to detect some kinds of errors statically if you annotate functions with SAL


We used it at first in windows driver when code was mostly C code, and where for example Out annotation used in conjunction with NTSTATUS as return would check if the client access of the Out variable was done only on the success path and also assure that the implementer was setting the out parameter when no error occurred.


Switching to c++ code it would be helpful to use some of the same tools support but things seem much more limiting in this context. For example if i have an Out Obj& - I didn't manage for SAL to detect misuses as in the case of an C Out pointer.


Also __checkReturn SAL seems to work only for primitive types. What is your experience using SAL on windows (including C++ driver) ?





What programming languages were used to build Kindle and Nook apps? [on hold]


Can anyone please tell me what programs were used to build the Kindle app?


I would also greatly appreciate advice about the programming languages that were used to build the Nook app as well.


Also, if there are any suggestions about languages that could be used to build similar programs, I would greatly appreciate this information.


Thanks in advance to those who respond.





There are paradigms for owning and passing information. But has any serious thought been given to initializing information, in a generic way?


When I write object oriented code, some function has to fetch or generate or tell an object to generate the initial set of information that starts an app. When I write functional code, some imperative command has to tell a database or a file to spit out the initial information. When I write declarative code, I assume that the information that I am acting on just exists already.


Always, initialization is an afterthought in my programs, done in an ad hoc way, that breaks all the beautiful patterns that my predecessors have prepared for me. Has there been any serious research or experimentation into how systems should initialize themselves?


I finally realized that initialization is a concept that I do not understand well while reading Tom Ashworth's excellent introduction to the ideas behind communicating sequential processes. I had been reading it because I was struggling to find a clean way to initialize Flux (actually Reflux) stores in a larg-ish isomorphic React app, but now I realize that passing the information around isn't really the problem I am wrestling with (although CSP channels look really really cool); the problem is deciding what information will be needed to initialize the entire app, before it starts running in any particular context (home page, reseller manager's agent management page, etc.)


So, initialization. Is it a thing? Do people study it in a general sense, outside of the divisions of programming paradigms? Are there enlightening 40 year old papers on this topic that have been forgotten and partially rediscovered?





Software versioning for Python Apps


I have a question about software versioning. I want to release a Beta package (Python application) i.e. 1.0b.


However, versioning my software is just so confusing due to the different versioning methodologies. There seems to exist a variety of different version numbering schemes.


My question is, within the Python community what is the most common versioning system used and why?





Hidden dependencies - why not?


Hidden dependencies:



function __construct($dep_registry){
$this->db = $dep_registry->get('db');
$this->request = $dep_registry->get('request');
...
}


Not so hidden:



function __construct(Db $db, Request $request, ....){
$this->db = $db;
$this->request= $request;
...
}


The disadvantages of the last is that, if I need to change the class later and need another dependency, I have to change the constructor arguments. And if I change the constructor, I need to also change every file that uses it. With hidden deps the change would only be needed in the two places: the constructor and the registry class. Another fail of the 2nd method is that it's not possible to lazy load dependencies, i always have to pass the instances


So what's the disadvantage of hidden deps and why is it bigger than this disadvantage of not so hidden deps?





Structure project based on platform or design?


I have a medium sized project (~10,000 lines) that runs on Windows and Linux. However it is only specific components of the program that are platform dependent and are located in a folder called event_producers.


Now my main concern is to how go about organizing this folder since the project starts becoming more complicated and I would like to keep the organization at an optimal level.


Organization based on platform:



'-- event_producers
|-- Linux
| '--- monitoring.py
'-- Windows
'--- monitoring.py


This looks more implementation agnostic which is a bonus since someone can change things in the future without creating any new files. The main problem is that no one can guarantee that every programmer follows the pattern of having a file with the same name in each platform folder.


Organization based on design:



'-- event_producers
'-- Monitoring
|-- linux.py
'-- windows.py


This doesn't leave much space from the programmer to organize things in the wrong way. What bothers me is that I have a module called linux.py and windows.py, something I never came across in any other project. Also if in the future a new folder (say Activator) needs to be created, no one can guarantee that the programmer will follow the pattern of naming files according to the platform.


Questions



  • How would you organize the project and why?

  • Is there some other advantages/disadvantages with each way that I missed?





In an interview, are you expected to populate data structures so you can test your code?


I've worked at the same company as a Web Developer for a VERY long time and am now looking around, so I haven't encountered many interview tests. I'm doing the test questions in Programming Interviews Exposed, but am curious if in the actual interview your expected populate data structures before manipulating them, etc.


I understand that it's different in each company and some questions will be answered on a white board, but in cases in which you're expected to test your code would they provide you with some code that populates the data structure?


For example, say you're asked to find the lowest common ancestor for 2 nodes in a BST. Would I be expected to first create a BST class and then populate it with data or would the interviewer provide me with that part of the puzzle?





Is Red Star OS released under the GPL?


According to Wikipedia, Red Star OS is



is a North Korean Linux-based operating system



Does that mean it's covered by the GPL, or are there exceptions?





What are the different types of whitespace referred to by Perl?


I am trying to find the Java equivalents of the Perl regular expressions not supported by Java. These are, as listed in the Java Documentation:



\h A horizontal whitespace
\H A non horizontal whitespace
\v A vertical whitespace
\V A non vertical whitespace
\R Any Unicode linebreak sequence \u000D\u000A|[\u000A\u000B\u000C\u000D\u0085\u2028\u2029]
\X Match Unicode extended grapheme cluster


However, I have no idea what any of these mean, which makes it rather challenging to recreate them.


(I think) I know what whitespace is, but I did not know there were multiple kinds of whitespace. What is the difference between horizontal, non-horizontal, vertical, and non-vertical whitespace?





AngularJS $http.get JsonResult [migrated]


I am building a dx-chart inside of an AngularJS file. I would like to use $http.get inside of my ng-controller. Here is the AngularJS file. However, when I try to use $http.get I still display the chart but there is not data passed in. If I remove the $http argument and $http.get in the dataSource, I am able to display my data using the Json format passed in from my URL.


AngularJS File



var app = angular.module('customCharts', ['dx']);

function ChartController($scope, $http) {
$scope.productSettings = {
dataSource: $http.get("http://localhost:53640/Home/PostChart"),
title: 'Displays Product Costs for items in our Database',
series: {
argumentField: "Name",
valueField: "Cost",
type: "bar",
color: '#008B8B'
},
commonAxisSettings: {
visible: true,
color: 'black',
width: 2
},
argumentAxis: {
title: 'Items in Product Store Database'
},
valueAxis: {
title: 'Dollor Amount',
valueFormat: 'currency'
}
}
}




Is there a performance benefit to using a method reference instead of a lambda in Java 8?


According to the Java Tutorial on Method References:



Sometimes... a lambda expression does nothing but call an existing method. In those cases, it's often clearer to refer to the existing method by name. Method references enable you to do this; they are compact, easy-to-read lambda expressions for methods that already have a name.



Do method references skip the overhead of the lambda wrapper? Might they in the future?


Despite Oracle's claims, I find the lambda syntax easier-to-read than the method reference short-hand. Plus, you can wrap any function in a lambda. The method reference syntax won't work on methods that return void, take or return primitive arrays, or throw checked exceptions.


If there's no performance penalty for doing so, I'm tempted to turn off the warning in my IDE and use the lambda syntax consistently without sprinkling the occasional method reference into my code.





Mail exchange software


I need to allow users of my site to write emails to each other, without revealing their email addresses.


Here’s an example: user1@gmail.com sends an email to user2-alias@mydomain.com, user2@gmail.com receives it as sent by user1-alias@mydomain.com


I can do this with a process which checks the user1-alias@mydomain.com, modifies the email addresses of sender and recipient accordingly and forwards the email to user2@gmail.com.


But I’d like to know if there are other easier ways to do it. I tried with postfix forwarding, but couldn’t get to get both addresses translated.


Any ideas?





Please assist me to choose a platform between PHP/Mobile Apps programming and SOA development? [on hold]


I am a PHP programmer with 3+ experience with start-up knowledge of mobile app frameworks like jQuery mobile/Sencha touch etc and I love programming. I have an opportunity in my company to switch from PHP/mobile apps to SOA development. I discuss with one of my colleague who is working on this. He told me that SOA is not a programming job (only little bit java programming if needed) but using it we have to combine some web services together. So just want an advice from you guys that which one is best between PHP/mobile apps and SOA for a bright future scope.





Tools for data modelling


I am refactoring a one year old web applications. My first few steps to gain a bigger picture is to "draw" all the models I would need or already there.


Is there a tool out there which helps me with the process? Something like a mind mapping tool where I can quickly note down the names, and later a few relations. I don't want to build a database, just my models should be clear.



Which tool is the most helpful to visualise models and their relationships?






Atlassian Bamboo package from multiple repositories


We're currently developing a server/client application. The server is a maven Java EE project. The client interfaces are in HTML5. We use Stateless REST interfaces to communicate with each other. As there are two subteams in our project team, we decided it was a good thing to separate the server and client interfaces in two git repositories (web dev team doesn't need the server for developing/testing interfaces, and vice versa).


However, when it comes to packaging, we use git subtrees to install the web interfaces in the server projet before launching mvn package.


We recently have felt the need for a CI server, and we went for Bamboo, as we already use Jira and Confluence in our company.


Is there a way to make Bamboo actually do the web interfaces integration before packaging so we don't have to use git subtree?





Can't get path-dependent types to work in scala enumerations


I'm trying to spin my head around the path-dependent types in Scala's enums while making a Reads/Writes for Play2. Here is the code I have so far, it works, but with an asInstanceOf:



implicit def enumerationReads[T <: Enumeration](implicit t: T): Reads[t.Value] = {
val validationError = ValidationError("error.expected.enum.name", t.values.mkString(", "))
Reads.of[String].filter(validationError)(s ⇒ t.values.exists(v ⇒ v.toString == s)).map(t.withName(_))
}

implicit def enumerationValueSetReads[T <: Enumeration](implicit t: T): Reads[t.ValueSet] =
Reads.seq(enumerationReads[T]).map(seq ⇒ t.ValueSet(seq.asInstanceOf[Seq[t.Value]]: _*))


What can I do to get rid of the asInstanceOf on the last line? I tried typing the enumerationReads as enumerationReads[t.Value], but that doesn't work, the compiler complains in the argument of t.ValueSet that Seq[t.Value] cannot be cast to Seq[t.Value]. Yes, that didn't make sense to me too, until I started to realize these different t's might actually be different, since they are used in a closure.


So, what to do to make my code super-duper asInstanceOf free?





FP: Capturing the characteristics of a process which blocks, causes side-effects, and may fail


I have a driver function modifyFile that interacts with many sources in the outside world (e.g. HTTP, filesystem). Let's say the code is as such:



def downloadFile(from: String, to: String): Try[Unit]

def runUnixProcess(cmd: String): Boolean

def modifyFile = {
downloadFile(from = "http://.../some/file.dat", to = "/tmp/file.dat") //
val status = runUnixProcess("/usr/bin/somebinaries /tmp/file.dat")
if (status == Status.OK) deleteFile("/tmp/file.dat")
}


For the sake of the argument, let's consider that these functions abide to the Single Responsibility Principle rule, and that modifyFile is only a driver that "integrates" and facilitates communication between separate entities such as OS, File system and web service.


While this function will most likely sit in the higher level of the application logic, some other application function might be built on top of it. Hence, I want to have some kind of proper abstraction (e.g. by wrapping it with a monadic construct) so that we can still compose an even higher abstraction over it.


Now my question: What is the best language construct to abstract this kind of computation? Namely a computation that:



  • calls to many entities in the external world

  • may fail, either partially or completely at some steps due to various conditions. To name a few, we might be dealing with filesystem permission issue, network connection issue, unix binaries missing issue, etc.

  • might need to be ran asynchronously, considering that there are several blocking calls in it.


Is Scalaz's Task up for it?


Or should I simply wrap it as a Future[Try[T]], which basically captures most of the characteristics it exhibits?





Creating a simple Window program


so I am new to programming I am using mainly the console do program.And since I am a beginner I was wondering how can I make a simple window program with Text?I am sorry for my newbie question but I don't know where else I can ask.I am programming in C++.





Why does Golang expect a right bracket in the middle of a for loop?


When I try and run my Go test file, I get some errors.


This is the test file:



package rb_database

import (
"system"
"testing"
"time"
)

func TestGetBinContentsResult(t *testing.T) {

errCount := 0

currentTime := time.Now()

gbcr := new(getBinContentsResult)
ids := make([]system.ID, 5, 5)

for i := 0; i < 5; i++ {
ids[i] = system.GenerateNewID()
}

copy(gbcr.deletedIds, ids)
gbcr.earliestRecordDeletedDate = currentTime

//Test functions
for j := 0; j < len(gbcr.DeletedIDs()); j++ {
if gbcr.DeletedIDs()[j] != ids[j] {
t.Error("Element " + j + " in ID array not equal to value set. Expected Value: " + ids[j] + ". Actual Value: " + gbcr.DeletedIDs()[j])
t.Fail()
errCount++
}
}

if gbcr.EarliestRecordDeletedDate() != currentTime {
t.Error("Earliest record time not equal to value set. Expected Value: " + currentTime + ". Actual Value: " + gbcr.EarliestRecordDeletedDate())
t.Fail()
errCount++
}

if t.Failed() {
t.Log("Test failed: TestGetBinContentsResult. " + errCount + "/6 possible errors occured.")
} else {
t.Log("Test passed: TestGetBinContentsResult. ")
}

}


I'm using LiteIDE 27.1 and Go 1.3.3. I have made sure my GOPATH and GOROOT are set to my project directory and the Go install directory respectively.


The build output when I run TestAll is:



C:/Go/bin/go.exe test -v [C:/Users/Adam/workspace/RedboltMarch/src/rb_database]
# rb_database
get_updated_result_test.go:18:9: expected ')', found ':='
get_updated_result_test.go:49:2: expected '}', found 'EOF'
FAIL rb_database [setup failed]
Error: process exited with code 1.


When I build and run the program normally:



C:/Go/bin/go.exe build -i [C:/Users/Adam/workspace/RedboltMarch/src/rb_database]
Success: process exited with code 0.
rb_database [C:/Users/Adam/workspace/RedboltMarch/src/rb_database]
Error: process failed to start.




DataThread class that doesn't extend Thread, poor naming?


I created a DataThread class that doesn't extend a Thread, but has one as a member variable.


Favor composition over inheritance, is a rule that I heard of, but I am thinking that the name of the class should be change, as to not mislead.


Is this true?





What is a simple, correct and secure way of executing code stored in database?, that is also sandboxed


Webhooks can be a very powerful thing when you try to automate or integrate software, however, handling their deployment in a controlled environment can suck in terms of security and deployment alone.


I need a way of allowing anybody in the company —anybody that can be trusted with API access, that is— to be able to create, deploy, use (and perhaps even share) webhooks without requiring access to a server.


I have thought that a way of doing this is to create a small application that can store, route and run scripts. The best way I can think to implement such a thing is by taking code stored in a database and creating a temporary file to then run a system command for the given language.


However, I think there would be nothing that would prevent that code from, say, shutting down the machine, downloading and executing external dangerous code, etc.


Then I thought about Linux containers, but I would preferably want a portable solution. I looked for an equivalent in Windows and apparently the technology does not exist yet:


http://ift.tt/1wbU5X5 http://ift.tt/1uO4Bpl


Is there a simpler approach that can still be regarded as secure?, I would want to at least be able to execute php, python, ssj and shell scripts.


P.S.: Free downvotes for whoever suggests PHP eval





Get from object or use variable


Which one is better



//somewhere here i have Test test = new Test(); object

String name = "default";
if(test.getName() != null) name = test.getName();


or



String name = "default";
String testname = test.getName();
if(testname != null) name = testname;


As I understand second is better , as i will not get from object twice , am I right ?





what is the relationship between CORBA, JMS and MDB?


In the context of my previous fuzzy question on microservices, please help me break down the terminology involved in these technologies:


CORBA


JMS


MDB


Utilizing JNDI, I believe it's possible to do a remote lookup with CORBA, using, for example, Active MQ as a broker. In that case, it's broker to broker -- almost peer to peer.


With JMS and MDB, I'd expect a richer technology if only because it's not limited to, ironically, the multi-platform nature of CORBA. I say ironic in recognition of the cross-platform intention, at least, of Java.


For remote message, object, "thing" getting sent around the intertubes, why is CORBA passe and why aren't JMS or MDB used instead of REST or SOAP?


(confining this strictly to Java-to-Java and ignoring other languages for the purpose of the question. That is, assume that program x is written in Java.)


See also:


http://ift.tt/1E3hIcd





Who should write the Technical Design Document? The BA or the Developer?


I work as a Snr. BA in a large Manufacturing company and I've just implemented a new Requirements Management Process.


We have a large range of internal developers who in the past have never been asked to define solution via a Technical Design Document once they have received an approved Requirements documents. They normally just go ahead and code without any written reference of their solution or why it was chosen and any associated risks involved.


Now our release manager states that it should be the BA who writes the solution and Technical Design documents. I disagree as I believe it should come directly from the Developer, especially as there is an easy-to-complete TDD template.


I feel it's a waste of the BA's time to repeat and try to interpret a Developers solution and it runs the risk of misinterpreting the Developers solution. BA's aren't supposed to be THAT technical! :-)


In my experience it's been the Developer / Architect who writes it.


Please let me know how it works in your Companies!


Thanks Daz





in c programming i need custom atoi code


i want to subtract two 64 bit hex numbers(in c programming), 0x0000888888888888 -1st hex value - 0x00000000839DDB7A -2nd hex value = 0x0000888804EAAD0E =(need the above result in hex)


The 1st hex value is in a unsigned long long int variable. But the 2nd hex value is in a unsigned char array. So i want the value in this char array as hex value in another unsigned long long int variable,then i can subtract those two. I have tried ATOI function,but it can convert only ascii number to its integer,it wont convert ascii character such as 'A' to hex value 'A'.


Am using the final result as key for the DES operation. Please help me to get this...Am stuck in this part through my big project from Harman technologies..Thank you in advance.





Examples of operating systems capable of serving http-requests that does not support direct slash for directory separator


My php framework uses DIRECORY_SEPARATOR constant instead of /. Can there be any other options for a directory separator?





Once I have gained access to the Raspberry PI GUI remotely can i be able to install any software or package?


Visit http://ift.tt/1s887aW


This shows how to access Raspberry PI GUI remotely using Virtual Networking Computing(VNC)





Any error will ocurr in this statement? ((a)*(b))


define Product (a,b) ((a)*(b))


I assume "a" and "b" is an integer or a real number.


Here are the errors I could think off




  1. If the programmer for some reason and apply string or character or symbol in either "a" or "b", then the program will fail.




  2. If "a" and/or "b" is real number or integer, then we could assume the result of this statement is integer or real number, if the result is integer, integer has range of value (float or double), if the result from actual calculation is more than the range, then the error will occur.




For example, if the result of this statement is 2



"a" = 1
"b" = 2.5
1 x 2.5 = 2.5 (so is not equal to 2, then is false)


Anyone have any more example for this statement?





mercredi 25 mars 2015

Any good data structure to perform efficient lookup and modification operations about what are the shapes containing the current cursor position


I think I'm facing a pretty common issue but cannot remember which solution is the most suitable one.


Let's put it that way: I can, in a, certain, given, language get some events anytime the user is moving the mouse. I therefore get the position the current cursor position in let's say in absolute coordinates based system.


Now considering that this system is also capable of containing up to thousands of thousands of shape objects (with a certain location point and size). In a first rough approximation, we can think about them as their related bounding boxes in order to make the lookup operation and classification a bit more simpler, let's also add another simplification by omitting the fact that shapes can overlap each other.


What can be the best data structures to retrieve the shape(s) under the cursor position and allow relative fast insertion / deletion / modification operations?


Thanks,


ps: I was thinking about some sort of sorted trees but I think they are pretty demanding when it comes about maintaining their internal sort.


Additional curiosity: how it works in Winforms? I mean the Control class in the .NET Framework is related to the underlying HWANDLE in windows and capable of firing events when cursor is entering or leaving a Control. I do not really think that there is a thread allocated to perform some dummy hit tests... and trigger the related events.





Is storing data that rarely changes in-memory a good candidate for a singleton/cache?


I have a class called DataPoint that is defined like the following. Currently, it goes through each property on an object and based on the DataPoint, it does some formatting like padding, trimming, etc... before it will save the record to the database. The current implementation makes a database call for each property which is slow, so my first step is to get everything at once into an in-memory collection. What else can I do below? Is this a good candidate for a singleton since the data rarely changes and/or is it possible to cache it (if so, how)?



public class DataPoint
{
public string Name {get;set;}
public string Justification {get;set;}
public int MaxLength {get;set;}
public string Format {get;set;}


public DataPoint GetDataPoint(string name)
{
var dataPoint =
db.Query<DataPoint>("SELECT * FROM DataPoint WHERE name = @name", new {name}).FirstOrDefault();

return dataPoint;
}

public T FormatObj<T>(T obj)
{
foreach (var propertyInfo in typeof(T).GetProperties())
{
var dataPoint = GetDataPoint(propertyInfo.Name);

//Do formatting on obj Properties such as setting values, etc...
}

return obj;
}

}




What's the best way to implement a real time show board to show results from concurrent result producers in Java?


I'm making a load test tool that launches multiple thread to simulate load on the target server. Each thread executes a predefined set of commands in the structure of TestSuite - TestCase- TestStep and each level returns results objects (of respective types). Each thread loops its predefined commands, so a series of TestSuite results are generated and it takes a while for all the loops to finish.


I'm trying to find the best way to show results generated in the still running threads. I've thought about a few possible ways:




  1. Use BlockingQueue and producer - consumer pattern. This requires heavy concurrency programming and I haven't been very clear on how I should handle different levels of results - suite results, case results and step results.




  2. Use a concurrent map to hold reference to results, and poll that map periodically to show what's available. This can be very inefficient. How do I just get the new results every time I poll?




  3. Develop a custom Log4J logger, so I can add appenders which will receive results on-the-fly. I haven't researched on how much work is involved if I use this approach. Is it even possible? Considering the level of result types it needs to handle.







Development Time: sql in UI code vs domain model with datamapper


First, sorry for my English guys.


Currently this is my first programming job. I am labeled as the most incompetent programmer in my company that's because they measure the performance and productivity of programmer by how fast you can get things done. I'm not really sure if I'm slow or not, because I always test(manual testing) my code before submitting it, and I'm pretty sure that most programmers here don't test their code the way I test mine. I don't do automated test because I admit that the concept is still complex to me. Since our software is not yet use by the user, we don't know which programmer has the most or fewer bugs. And also the system is for internal use only, so we don't have strict deadline. Time to ship is not that important.


We don't have best practices, automated testing, code reviews, and coding standard here in the company, so basically you are on your own, just make the code works and your fine. Almost all of the programmers here are fresh from college. Even me I'm a fresh graduate.


I think the reason why they are fast it's because they do all of the business logic in sql. So Basically they have all the UI code and Sql code in one .aspx file just like the code below



Patial class InvoiceView : Page
{
protected void button_click(object sender, Eventargs a)
{
string sql = "Select * from some blah blah blah";
DataTable tab = .....some Ado.net code here.
Gridview.DataSouce = Tab;
Gridview.DataBind();
}
}


Before I got my first job(although this is my first job), I don't code like this anymore I usually use a custom object just like the code below.



Public class Invoice
{
public int InvoiceNo {get;set;}
Public DateTime PaidDate {get;set;}
Public List<Item> Items {get;set;}
public decimal Amount {
get
{
decimal amount = 0;
foreach(var i in Items)
{
amount = amount + i.TotalPrice;
}
return amount;
}
}
}


after that, I'm going to create a DataMapper class, and I'm pretty sure this is the reason why I'm slow, because I have to manually map the row table to objects and test the datamapper. So basically their is no ORM or micro ORM. Our database don't have referential integrety and tables always change. So I thought ORMs are not ideal for this project.


The person that labeled me as the most slowest is actually a junior programmer just like the rest. He has 2 years experience ahead of us, that's why he is our immediate superior. Sometimes I always think that the reason why he said that is because he is still a junior and no experience when it comes to managing a team of programmers.


I'm confident that I can do all the job they will throw at me.


Here is my question.




  1. Should I use DataTable and shove it to gridview just like the rest of my team do?




  2. When to use DataTable instead of custom objects or domain classes?




  3. Currently I only know two Data Access pattern, ActiveRecord and DataMapper. What do you call the pattern that my team uses?




  4. How can I code faster?




Thanks guys, sorry for my English.





WebAPI to source Location Satellite Images


I am developing an ASP.NET web application that calculates a percent score of an algal bloom from a satellite image. I'm looking for a WebAPI that will allow me to access a recent satellite image based on a specific location: i.e. a user inputs a lat/long and the correct image is returned.


I looked through NASA's API catalog, but couldn't seem to find what I was looking for. Does anyone know where I could an API that would have or allow this kind of functionality?





Beginner Decorator Pattern Question


I came across this article: http://ift.tt/1CrtqLD


After reading it, I am having a little bit of difficulty understanding a concept. If you look in the Structure section in that article when it shows the UML class diagram, I am confused on why the Option Wrapper class extends the Interface class but the Option Wrapper class has an instance (composition) of the Interface class as well. Why are both of these relationships needed to in order to accomplish what the Decorator Pattern hopes to do? In other words, why is neither relationship good enough by its self?





please anyone solve this c++ question for me


Write a program that accepts the following data about customer’s bill; customer area code (3 digits), customer phone number(7 digits), and number of text messages sent. Display all the data including the month-end bill both before and after taxes are added for the following scenario.


The cell phone company charges customer a basic rate of $5 per month to send text message. Additional rates are as follows. The first 60 messages per month, regardless of message length are included in basic bill An additional 5 cents is charged for each text message after the 60th message, up to 180 messages An additional 10 cents is charged for each text message after the 180th message Federal , state and local taxes add to the total of 12 percent of each bill





Social Bookmarking for Programmers?


I am a new programmer, really just getting started. I don't know too many people who program around here so I am not sure where to take this question. I will try to express it as a proper question and not a matter of opinion or debate.


I just am wondering - what sites do programmers use for social bookmarking? Do any of these these sites have a significantly larger user base than the others?


Thank you.





What's the best way to handle slightly different exceptions?


My code right now looks something like this:



void throw_illegal_part_of_input_exception(char c) {}
void throw_invalid_input_length_exception(int position, int length) {}
void throw_invalid_subinput_length_exception(int position, int length, bool is_greater) {}
// Some other similar functions

// ... do some stuff inside a function
if (errorCondition1) {
throw_invalid_character_exception(c);
} else if (errorCondition2) {
throw_invalid_input_length_exception(position, length);
} // etcetera


The content of the functions is largely the same; however, the error messages I want to use in the thrown exceptions are very different and depend on the arguments. Is there a better way to write this?





Does a computer science major need any certificates after completing their major?


assuming one were to do well academically, and build up their portfolio also during their free time (hobby and such), would a programmer/software engineer need certs, like IT pros do? or is it enough to just learn extra languages and such on your own, and prove it to your employer.


my plan is to excel in my BS program, and once i have some years under my belt, go for an MS program.


thanks in advance!!!





How to search for patterns on a gameboard?


Assume a gameboard with two kinds of pieces.


Let the task be to find a common patterns of pieces, namely the patterns that lead to winning.


The problem is general, but the game in question is Gomoku, i.e. tic-tac-toe on a 15x15 board with requirement of having five pieces in a row. But the similar problem would be the mouse moves recognition when concerning screen as an array of pixels.


To let any data mining model solve the problem of finding pattern that can lead to a win, the problem of identity of patterns must be solved. That is, it must be programmed that a given pattern moved left/right/down/up or rotated is still the same pattern. Like in an example of mouse moves, it is unimportant where a move starts on a screen.


My question is how to to solve this issue of identity efficiently.





Help On My First Website!


This is my first go at things and the webpage looks good on my computer but looks wayyy different on others in terms of alignments. Is there some sort of coding I can do to make the page universal to all different resolutions?





What to call an HTTP API that is not RESTful? [on hold]


What would you call an API that is HTTP-based, uses URI to name resources and HTTP verbs (PUT, POST, DELETE, GET...) to manipulate those resources?


According to Roy Fielding's complaints it is not REST, because there is no hypermedia.


Internally, in my team, everyone calls it "REST API". I call it "REST-like" but it is not descriptive and its meaning is fuzzy. I'm quite confused about it, since there is huge disagreement about REST. I don't want take part in flame wars, but just use correct terms.





Best environment for code review on Windows


I've been given the following task:



A company is giving source code for its product (comprising over 1 million lines of C++, Java, with some assembly) for my review. The code will be loaded onto a Windows machine that I do not control, has no USB ports, no network, and is a small controlled room. I must somehow sift through the code, figure out where the implementation of Action X is, and then trace through the code to see how Action X ties into the rest of the product.



The last time I did this, they gave me the code along with Notepad. Since I couldn't add software, that was it. I found myself using DOS command shells to get a grep-like ability with FINDSTR /R but this was painful, as you might imagine.


I have a chance to tell them what I would like installed on the machine next time. What do you think makes sense? Ideas:



  1. Ask code to be loaded into some IDE

  2. Ask them to put it all in doxygen

  3. Ask them to present the code in an HTML format that has cross-referenced links (sort of like MS reference code uses)


Or something else?





How is the best way to work with step by step documentation to software maintenance


I'm working on a web project in java and I have a problem with the documentation we are making.


The goal is to has step by step how to do some basic stuff for system maintenance, like add fields to a report, for guidance for me and another programmer and maintain consistent code.


For this I have multiple Word documents with screenshots and step by step how to do things in the project code, also we comment the code but not step by step.


The development IDE we use is Intellij IDEA Ultimate.


The problem we have is that the Word are not comfortable, because it has many pages with a large index (about 175) and has a huge time-keeping when we make a change. For example: we are now changing the version of the IDE and we take more or less a couple of hours of extra work to change and adapt the word files.


We have also tested using Wikis (like tikiwiki), but it was difficult to maintain with images and we dont feel very comfortable using it.


1- how we could manage this documentation better to fulfilling my goal?, there is a better way to do it? 2- Is there a practical way to integrate the IDE?


Greetings





Clojure NameSpace Design


I am new to Clojure and trying to get a handle on organizing a project's namespaces. I am working on a solver for the knapsack problem. Currently, I have broken the modules into files, but everything lives in one namespace: my-project-name.core. I am using load to manage access across files and it seems like a bit of a kludge. I've drawn a digram of how I think I want the various parts to interface:


architectural diagram


My goal is to be able to work on each of the nodes in the diagram independently. I am trying to come up with a strategy for rational namespace design somewhere between everything in one and each in its own.


In particular I want to be able to swap out the solver and estimating components since these are the most tunable.





To KISS or not when coding?


I don't consider myself "ninja" but I don't think I'm bad dev either. Anyway, after many years of development I tend to keep it simple more ofthen than before. For small projects there is no need to bring MVVM and all boilerplate code, OnClick() will work..


Recently one of my developers wrote this code (C# ASP.NET)



public static class PageHelper
{
public delegate TResult Func<in T1, T2, out TResult>(T1 arg1, out T2 arg2);

public static Func<string, int?, bool> NullableInt32Parser
{
get
{
return (string s, out int? int32) =>
{
int result;

if (int.TryParse(s, out result))
{
int32 = result;
return true;
}

int32 = null;
return false;
};
}
}

public static Func<string, Guid?, bool> NullableGuidParser
{
get
{
return (string s, out Guid? guid) =>
{
Guid result;

if (Guid.TryParse(s, out result))
{
guid = result;
return true;
}

guid = null;
return false;
};
}
}

public static T GetRouteParameter<T>(HttpRequest request, string name, Func<string, T, bool> stringToOutputTypeParser)
{
if (request == null || name == null) return default(T);

var valueString = request.RequestContext.RouteData.Values[name] as string;
if (valueString == null) return default(T);

T value;

return stringToOutputTypeParser(valueString, out value) ? value : default(T);
}

public static int? GetInt32QueryStringParameter(HttpRequest request, string name)
{
if (request == null || name == null) return null;

var valueObject = request.QueryString[name];
if (valueObject == null) return null;

int value;

return int.TryParse(valueObject, out value) ? (int?)value : null;
}
}


Delegates, generics, etc - all to get query string params parsed out. I ended up rewriting it like so:



public static int? GetIntQueryStringParameter(HttpRequest request, string name)
{
int value;
return int.TryParse(request.QueryString[name], out value) ? (int?)value : null;
}

public static Guid? GetGuidQueryStringParameter(HttpRequest request, string name)
{
Guid value;
return Guid.TryParse(request.QueryString[name], out value) ? (Guid?)value : null;
}


What I'm not getting is why developers trying to make it harder? To show they know delegates? To show they know generics? I know that 60% or so of developers won't even understand what's written. So, why do it?





Testing a method that reads from standard input and outputs to standard output


I have a method which reads lines from standard input and outputs them to standard output. In a JUnit test, how can I have it send standard input to the method and how can it make assertions about the output?





Let the programmers do what they want. The code just "works"


I have inherited a large application built over years without real structure. I managed in some way to improve it and make it in a commercial product sold to more than 20 customers.


Now more programmers are coming in. The CEO and the PM, skipping totally my responsability as tech coordinator, ask any kind of feature development on a daily base to juniors or less juniors.


I cannot enforce any coding or architectural guidelines. Things just get added on a "I want it now - it works" basis.


I don't know really if I should just "let it go" or try to enforce my vision...


Agile methodology will not be understood by the team. We don't have any kind of unit testing nor bug management. We deploy several time per day.





Is there a way to change javascript in browser before loading the page?


Hello I am new to javascript. For a specific example, If I want to change some javascript code in Google.com webpage before it loads in $my$ browser... Is it possible ? Thanks!





XML Parsing| JaxB vs Xslt | Java


Working on some analysis for parsing the XML data so that this can be used by the system , I have worked with both JaxB based XML parsing and Xslt and have mixed experience with both.


The system on which I am working provide a way to import the data using CSV format, all I need to pass the CSV files to the platform and it will import the process using spring integration and its build in mechanism to transform CSV file to its own internal format for importing. Currently I have to deal with parsing large XML files ( > 500mb or more sometime) and I have these 2 options


JAxB



  1. Use JaxB with StAX XMLStreamReader to read files in chunk and use platform system API to save data in to the system using the ORM ( like sending data in batch mode )


XSLT



  1. Use XSLT technique to convert XML to CSV format and let the system to handle rest of the process for me


I am fine in using any of the options but not sure what might be the best way to handle large XML file parsing (provided size of the XML will keep growing based on the number of product system have).


Can any one provide there input on choosing the approach.





Mobile development experience using Kony?


I have an opportunity to "level up" at my job in enterprise IT/development by moving from front end/back end web development to a mobile development team which will be developing apps on the Kony platform. Any programmers out there with positive or negative software development experience working with Kony?





Using advertising with free app is a commercial app?


I have a simple question: if I publish a free app (iOS, Android, ...) and implements advertising in the app, does it's considered a commercial app? I'm asking this question because I don't know if I can use tools that have a certain license to build a game and get money with advertising from fee app.





Object Storage where Object Type is variable


From time to time, we come across a problem where we must store an object, but we don't know in advance what kind of object we're going to store. I'm going to give a very simple example.


Requirement: All questions have answers. All answers have at least one part. Some answers have more than one part.


We're going to focus on how to store and retrieve multi-part answers. We want our view or possibly our controller to behave differently depending on whether the answer has one part or many parts.


Conceptually (without object storage) we might write the following:


Data Model:



class Answer
Wording (string or Array of strings)


Controller:



if ourAnswer.wording instanceof String:
doSomethingWith(ourAnswer)
else
foreach (answerPart in ourAnswer.wording)
doSomethingElseWith(answerPart)


So I think that would be the simplest possible way you could meet that functionality, but I'm not aware of any database that will let us store our objects like that, except maybe JSON. (No POJOs presumably because of static type checking.)


I'm actually using Node.js and Javascript with a NoSQL database here which is why I can get away in my pseudocode with not caring at compile time about whether my Answer.wording is a string or Array. But this is a very common problem when I've been using Java as well and I've not yet found the most elegant solution. For example, imagine trying to write that out in Java. We'd probably do:



public interface Answer {
public String getAnswer();
}
public class SingleAnswer implements Answer {
private String wording;
public String getAnswer() {
return this.wording;
}
}
public class MultipartAnswer implements Answer {
private String[] wording;
public String getAnswer() {
return doSomethingWithThisArray(this.wording);
}
}


... and of course that raises all kinds of weird issues with separation of concerns -- how do we know our Multipart Answer will do the right thing with its array, for example? What if we need to work with the array directly? And so on.


Well these are all implementational issues which we can fix. I'm really interested in the best practice for a language like Javascript where we can't use a hierarchy of objects and specificly, their storage in something like an NoSQL database or even worse, an actual SQL database. This problem is the kind of thing which pops up all the time for me with the LAMP stack.


There may be a simple solution for this specific example: we could assume ALL answers are multi-part answers, some of which have an answerPart array length of 1. Nice, simple, clear, easy and that is in fact what I ended up doing. But what if it isn't so simple and we really don't know what kind of thing we want to store, only that it is one of a finite set of well-defined things? What if our objects are preferredColour objects of either a centipede's shoes (16) or a car's wheels (4, different functionality from whatever it is the centipede's shoes do)?


Too contrived you say? Here's another real-world example I dealt with a few years ago.


Requirement: Ask the user if they suffer from a heart condition. If they do, they must give details of that condition.


Since I was using the LAMP stack, the easiest way to store that was in a database column named heart_condition_details, which may be null. In checks where has_heart_condition?() mattered we could simply return the whether heart_condition_details was null or not. Unfortunately, the framework I was using (cakephp) wouldn't allow me to extend the data model like that, with a boolean type has_heart_condition predicated upon whether heart_condition_details was empty.


In the end, I used separate columns for varchar heart_condition_details and boolean has_heart_condition. To this day, I think, I still regret it.





Non-fixed-size Fenwick Tree implementation


I wonder how to implement a non-fixed-size Fenwick tree. That is, a Fenwick tree that allows interleaving range queries with adding/removing elements.


All implementations and samples I've seen so far are for fixed-size Fenwick trees, where the number of elements is known before preprocessing the frequencies. They use a fixed size array, so it's not possible to add or remove elements after preprocessing is done. (Well, it is possible, but I'd need to re-build the structure).


I thought of extending TreeMap or maybe AbstractMap, but as TreeMap is actually a red-black tree, I don't know how to implement the red-black mechanics (so that the tree remains balanced) without loosing the cumulative sums of nodes involved in the rebalancing process.


So I thought that maybe I should take another approach: why not extend or adapt a simple random access ArrayList and re-calculate all cumulative sums when the underlying array is resized? This would of course have an impact but, hey, that's exactly what a HashMapdoes.


This is why I wanted to ask here first, in case someone has already done it, and to check which approach you think is the best.