I’m trying to setup WSO2 Identity Server 5.0.0 as an OAuth 2.0 enabled SSO server. It seems that IS500 doesn’t have the ability to define scopes and provides you with whatever scope that you ask no matter they are defined or not. Please someone tell me that I’m even on the right path!
mercredi 31 décembre 2014
Difference in computer usage with these two examples
What is the difference in computer/memory usage in the following code examples, also if there is any benefit to one or an other. Rough class below:
class Player
{
private Rectangle boxRectangle = new Rectangle(*defined elsewhere*);
private Vector2 boxPosition = new Vector2;
//box rectangle is moved constantly (through keyboard input)
public void Update()
{
//example one
boxPosition.X = boxRectangle.X;
boxPosition.Y = boxRectangle.Y;
//example two
boxPosition = new Vector2(boxRectangle.X, boxRectangle.Y);
}
}
Which is more efficient to use when updating the Vector2?
What is different between the internal design of Java and C++ that lets C++ have multiple inheritance?
It's drilled into the newbie Java programmers that Java (pre-Java 8) has no multiple class inheritance, and only multiple interface inheritance, because otherwise you run into diamond inheritance problem (Class A inherits from classes B and C, both of which implement method X. So which of those classes' implementation is used when you do a.X() call?)
Clearly, C++ successfully addressed this, since it has multiple inheritance.
What's different between the internal design of Java and C++ - (i'm guessing in the method dispatch methodology, and vaguely recall that it had to do with vtables from my long-ago computer languages class) that allows this problem to be solved in C++ but prevents in Java?
To rephrase:
What is the methodology of the language design/implementation used in C++ to avoid the ambiguity of diamond inheritance problem, and why couldn't the same methodology be used in Java?
Programming Behind Integral Calculators
In simple, layperson terms, can someone explain the programming behind integral calculators like Wolfram Alpha? How do they get it to know what to do for any given function...there are hundreds of methods of integration?! Thanks in advance
How do I unit test a heuristic algorithm?
Say we have our route finding algorithm:
def myHeuristicTSP(graph):
/*implementation*/
return route
Now we want to unit test this:
class TestMyHeuristicTSP:
def testNullGraphRaiseValueError(self):
self.assertRaises(ValueError, myHueristicTSP(None))
def testSimpleTwoNodeGraphReturnsRoute:
self.assertEquals(expectedResult, myHeuristicTSP(input))
The question is, for a non-heuristic TSP algorithm, we can give a variety of graphs and check that they always return absolutely the shortest route.
But because a heurtistic algorithm, while is still deterministic, is less predictable, are simply meant to understand how the algorithm is meant to be working, and find those edge cases?
Adding values to HashMap
I want to add values to a HashMap
, which would be used by methods in the same class. I have two solutions:
- Adding all the values with
static
- When the first method is called, add the values
Solution #1:
private static Map<Character, String> codes = new HashMap<>();
static {
codes.put('A', ".-");
codes.put('B', "-...");
codes.put('C', "-.-.");
codes.put('D', "-..");
codes.put('E', ".");
codes.put('F', "..-.");
// ...
}
Solution #2:
boolean methodIsCalled = false;
public static char decode(String s) {
if(!methodIsCalled) {
addValues();
}
// ...
}
private static void addValues() {
codes.put('A', ".-");
codes.put('B', "-...");
codes.put('C', "-.-.");
codes.put('D', "-..");
codes.put('E', ".");
codes.put('F', "..-.");
// ...
}
Which one is the most efficient? Which one is the best practice?
How long does it take to build a chat room web app?
How long would it take a lone developer to create a simple web chat application with extremely basic and minimal functionality (i.e., users can sign up and create or join chat rooms and nothing else)? I'm assuming it would be built using JavaScript. It wouldn't just be for me to use, but for others as well (i.e., it's not just a learning project).
I understand this is going to heavily depend upon how skilled the developer is. I'm just looking for a ballpark range/time order of magnitude. Is it going to be measured in days, weeks, or months?
Two classes that behave identically yet are semantically different
I am writing a program which is a similar to Ruby's Active Record Migrations, in which that every migration has both an "Up" and "Down" in terms of creating a change to the database, "Up" meaning bring the database forward in time, and "Down" reversing that change.
My program has two main functions to achieve its use-cases
- Get a list of scripts off the filesystem
- Execute the appropriate migrations on the database
The "Up" and "Down" migrations are stored in their own separate files, but they match with a similar naming scheme
- 2014000000000001_CreateTable_up.sql
- 2014000000000001_CreateTable_down.sql
There is a 1:1 correlation between up and down scripts. Having just an up without the corresponding down script is not valid (and vise verse).
I have two classes in my project to represent these filesystem files.
public sealed class UpScript // (and DownScript, which looks identical)
{
public UpScript(long version, string name, string content)
{
Content = content;
Version = version;
Name = name;
}
public long Version { get; private set; }
public string Name { get; private set; }
public string Content { get; private set; }
}
The reason that I did not make a single class called Script
is I didn't want to create ambiguity about the purpose of a specific Script
instance. UpScript
and DownScript
classes should not be used interchangeability as they do not conform to the Liskov Substitution Principle.
The problem that I have here is a few parts of code that are dealing with both either UpScript
or DownScript
instances look almost identical. How do I reduce the duplication without losing the expressiveness of having different classes?
My current ideas with concerns are:
Abstract base class
public abstract class Script
{
protected Script(long version, string name, content)
{
// code
}
// properties
}
public sealed UpScript : Script
{
public UpScript(long version, string name, string content)
: this(version, name, content)
{}
}
public sealed DownScript : Script
{
public DownScript(long version, string name, string content)
: this(version, name, content)
{}
}
This reduces the redundant code in the two classes, however, code that creates and consumes is still very duplicated.
Single class with Direction
property
public enum Direction { Up, Down }
public sealed class Script
{
protected Script(Direction direction, long version, string name, string content)
{
// ...
}
public Direction Direction { get; private set; }
// ...
}
This code reduces the duplication, however, it adds onus on consumes to ensure the proper script is passed to it and it creates ambiguity if you ignore the Direction
property.
Single class with two Content
properties
public sealed class Script
{
protected Script(long version, string name, string upContent, string downContent)
{
// ...
}
public string UpContent { get; private set; }
public string DownContent { get; private set; }
}
This reduces duplication and is not ambiguous, however, the usage of the program is to either run the up script, or run the down scripts. With this scheme, the code that gathers and creates these Script
instances is doing twice as much work, I don't consider not doing this being premature optimization because if the user wants to do an up migration, there's no point is looking at down scripts.
With all that said I may be looking at the wrong problem to solve entirely.
If more information would be helpful in forming a suggestion, you can view ScriptMigrations on GitHub
Understanding memory update propagation in x86/x86-64 CPU L1/L2/L3 caches and RAM
I'm trying to understand in a general sense how L1/L2 (and now L3 caches) are updated and how the updates are propagated in a multi-core x86/x86-64 CPU to the other cores and eventually RAM.
Assuming an 4 core CPU and 2 pairs of L1/L2 caches, where pairs of cores share a common L1/L2 pair and there's an interconnect between the 2 L1/L2 pairs. And the cache lines are 64-bit wide. So we have:
- Core-0/Core-1 on (L1/L2)-0
- Core-2/Core-3 on (L1/L2)-1
- (L1/L2)-0 is connected to (L1/L2)-1
Let's say there is a thread T0 running on Core-0 that is writing to a 64-bit integer variable called X, and there's another thread T1 on Core-3 continually reading variable X's value - Please ignore the logical race conditions for a moment.
Question: Assuming X has been cached in Core-0's L1. When T0 writes a new value to X, Is the following sequence of events correct?
- X's value is pushed from register to L1-0
- X's value is pushed from L1-0 to L2-0
- X's value is pushed from L2-0 to L2-1
- X's value is pushed from L2-1 to L1-1
- X's value is pushed from L1-0 to RAM
Note: Steps 2 and 4 may happen concurrently.
Is there an algorithm to determine the amount of work needed to keep workers busy?
I wrote a multi-threaded program that randomly generates strings, and after generating, checks to see if the string contains a certain value. Namely, StringGenerator
and StringChecker
. What I'm trying to figure out is how many StringGenerator
threads I would need in order to keep StringChecker
busy.
All StringGenerator
threads have a reference to a Queue
that contains all of the Strings needed to be checked, and when they generate a String, it gets added to the Queue
. All StringChecker
threads also have a reference to the same Queue
and poll it to get the next string, and checks to see if it contains the keyword.
Because generating the Strings takes more time than checking them, what I want to know is if there are any equations, algorithms or analyses that can be done on the code that can help tell me approximately how many threads of each I will need such that the sum of all Strings generated by the StringGenerator
s is as close to the number of strings checked by the StringChecker
s as possible.
Where can I learn more about writing puzzle solvers?
I posted a similar question on Stack Overflow a few years ago and it was closed for being too vague. Please, let me know how I can clarify this question if it needs elaboration.
I'm starting my first college programming class in January (C++, an accelerated course smooshing two quarter classes into one) and I've gotten started early. The official textbook is Starting Out with C++, Early Objects (syntax heavy) and I'm complimenting it with Think Like a Programmer.
I want more resources like Think Like a Programmer: source code in C++ for solving simple puzzles; strategies for solving puzzles in a methodical fashion; writing puzzle solvers and general guides to formalizing that thought process programmers go through when they solve everyday problems and turn them into loops and conditions.
Tl;dr: I'm looking for puzzles that will help me become a better programmer by both practicing them and writing solvers for them.
To what extent can impact analysis of a code change be automated?
I'm not sure how possible it even is but as a programmer I have a sense of risk involved when I'm making changes to a code base.
I've never seen a tool which basically tells me, as I'm coding, how far reaching my changes potentially are.
Examples off the top of my head (which are probably debatable but this is just to be less abstract):
- Adding a property to a POCO is a "green" change
- Making a field readonly is a "green" change
- Adding a constructor when Unity DI is present is a "yellow" change
- Modifying conditional logic in a public method which has usages that span multiple assemblies is a "red" change
Does anything like this exist, or is it even possible?
C++ 3D Matrix Using References
Request for a sanity check ...
I am storing a 3D matrix in a 1D array as follows:
double * myVector = new double[NCHANNELS*NROWS*NCOLUMNS];
I want to be able to access myVector using [channel][row][column] syntax, so I am creating a C++ reference:
double (& my3dMatrix)[NCHANNELS][NROWS][NCOLUMNS] = myVector;
Have I used the proper syntax here, i.e., will
my3dMatrix[channel][row][column]
return
*(myVector + channel*NROWS*NCOLUMNS + row*NCOLUMNS + column)?
Thanks.
Using macros to implement a generic vector (dynamic array) in C. Is this a good idea?
So far I have only done personal projects at home. I hope to get involved in some open source project some time next year. The languages I that have been using the most are C and C++. I have used both languages for over a year and I feel like I have become quite proficient with both of them, but I really don't know which one I like better.
I personally like C because I think it is simple and elegant. To me C++ seems bloated many unnecessary features that just complicates the design process. Another reason to why I like to use plain C is because it seems to be more popular in the free and open-source software world.
The feature that I miss the most from C++ when I use plain C is probably the std::vector
from STL (Standard Template Library).
I still haven't figured out how I should represent growing arrays in C. Up to this point I duplicated my memory allocation code all over the place in my projects. I do not like code duplication and I know that it is bad practice so this does not seems like a very good solution to me.
I thought about this problem yesterday and came up with the idea to implement a generic vector using preprocessor macros.
It looks like this:
int main()
{
VECTOR_OF(int) int_vec;
VECTOR_OF(double) dbl_vec;
int i;
VECTOR_INIT(int_vec);
VECTOR_INIT(dbl_vec);
for (i = 0; i < 100000000; ++i) {
VECTOR_PUSH_BACK(int_vec, i);
VECTOR_PUSH_BACK(dbl_vec, i);
}
for (i = 0; i < 100; ++i) {
printf("int_vec[%d] = %d\n", i, VECTOR_AT(int_vec, i));
printf("dbl_vec[%d] = %f\n", i, VECTOR_AT(dbl_vec, i));
}
VECTOR_FREE(int_vec);
VECTOR_FREE(dbl_vec);
return 0;
}
It uses the same allocation rules as std::vector
(the size starts as 1 and then doubles each time that is required).
To my surprise I found out that this code runs more than twice as fast as the same code written using std::vector
and generates a smaller executable! (compiled with GCC and G++ using -O3
in both cases).
My question is:
- Would you recommend using this in a serious project?
- If not then I would like you to explain why and what a better alternative would be.
Asp.net Web Api Controller design
I am developing services using Asp.Net Web Api. I am debating on design of our controllers. We have this common scenario where user will be presented with bunch of search field, once he enters the search criteria we will show summary of records (not the complete details), user will select one summary record and can go to details for this.
Ex.
class PersonSummary {
string FirstName {get;set;}
string LastName {get;set;}
string Gender {get;set;}
}
class Person {
string FirstName {get;set;}
string LastName {get;set;}
string Gender {get;set;}
string SSN {get;set;}
string Race {get;set;}
Address Address {get;set;}
}
User will search by user first\last name and we will show will list of PersonSummary records, he can select one PersonSummary to look at the details (Person record).
Now is it best design that we go with two controllers PersonSummaryController and PersonController?
Thank you.
Digital copyright impossible?
All digital data is but a stream of ones and zeros. It is therefore (in theory) possible to encode all digital data as a decimal number, which cannot be copyrighted, at least in the US.
This leads to a rather intriguing question: would distributing these numbers be legal under US and international copyright law?
EDIT: what if this number happens to be prime? There are many sites dedicated to such numbers. Would they get sued or C&D'd over publishing the number?
C/C++: Using `extern const` in header files to make global variables read only
I was experimenting with GCC and found out that you can declare variables const
in header files but keep them mutable in implementation files.
header.h:
#ifndef HEADER_H_
#define HEADER_H_
extern const int global_variable;
#endif
header.c:
int global_variable = 17;
This makes global_variable
modifiable to the implementation but const
to every file that includes header.h
.
#include "header.h"
int main(void)
{
global_variable = 34; /* This is an error and will not compile! */
return 0;
}
Is this technique used in practise?
People often recommend using get
-functions to retrieve global state when building interfaces in C. Are there any advantages to that approach over this?
To me this approach seems to be a lot more clearer and does not have the added overhead of a function call each time someone tries to access global_variable
.
mardi 30 décembre 2014
Economics of scaling, denormalizing NoSQL for personalized content
I am using Cassandra for a data intensive app. With relatively little operations and deployment experience, the expertise I am looking for is someone that can read the example below and decide whether I am overlooking simpler solutions, or if the resources needed make this problem expensive or intractable.
~A million entries in a book table: each entry ~30 columns - name, array of themes, year, etc
~1-10 thousand book stores that each contain some subset of the main table in (1), perhaps containing the id field from (1). so a book store table for the store metadata, and a book store inventory table will be needed.
A million users - a million entries in a user table.
A sequential recommender algorithm is designed to rank the best choice out of all possibilities for a user in a certain store. first, it can easily score each book in the main movie table with a 1 or 0 based on user tastes. thus it can "filter out" what it knows the user wont like, and the 1's move on to the scoring round. second, it can take real time user data and rank the remaining books for the store the user visits.
the question is how to apply the first binary recommendation step to the data.
a) each of the 10,000 "book stores" has its own inventory subset of the main book list. at worst case if all stores have all books(just pretend), thats 10,000 stores X a million books. then a batch operation (spark perhaps) can pull a single store's inventory to score for a user, and in the application logic, each book is checked against a hash-table for whether it passed the first binary recommender filter, which is queried from the user table.
b) create a user-store-book table (since user only has one or two favorite stores) that includes boolean results of first round of recommender for each book. this means a million users X a million books X 2 stores as entries in this table. then the batch job just queries directly for the recommended books in order to rank.
To put my question more succinctly, I am worried that in solution a, the CPU resources required and extra IO would make for a low-performant solution, and that the sheer amount of data in solution b might make this solution intractable.
What is the correct way to publish a runtime? Should it be a singleton?
I have a compiler for a programming language that targets JavaScript. That language needs some global functions such as: alloc
, memcpy
, write
and so on. My question is: where should I position those functions? I have pretty much 2 options:
1: inside a self-contained object, runtime
. Compiled functions would need to receive that object:
function example_of_compiled_function(runtime, arg0, arg1){
var arrayPtr = runtime.alloc(arg0);
for (var i=0; i<arg0; ++i)
runtime.write(arrayPtr+i, arg1);
return arrayPtr;
};
2: globally. Compiled functions wouldn't need to receive an additional object:
function example_of_compiled_function(arg0, arg1){
var arrayPtr = alloc(arg0);
for (var i=0; i<arg0; ++i)
write(arrayPtr+i, arg1);
return arrayPtr;
}
Both ways have problems. For (1), there is a considerable slowdown for accessing methods inside an object, and using compiled functions becomes more complicated since users have to manually create that object and feed it to them. For (2), it is faster and simpler, but might pollute the global namespace. Is there a satisfactory solution for this?
Range of values based on key values
I'm trying to implement a method of searching trough a large amount of 2D points for those that match a certain range. I'm thinking of creating HashMaps for <X, Point>
and <Y, Point>
but I'm wondering is HashMap good for doing this, because I will be taking points in a range, based on values from x_min to x_max and y_min to y_max.
So I will basically take all points from <X,Point>
searching from x_min to x_max and compare them to points taken from <Y,Point>
from y_min to y_max...
HashMap<Integer,Point> x_coordinates = new HashMap<Integer,Point>();
for(int i=x_min;i<=x_max;i++){
x_coordinates.get(i);
}
HashMap<Integer,Point> y_coordinates = new HashMap<Integer,Point>();
for(int i=y_min;i<=y_max;i++){
y_coordinates.get(i);
}
Is there a faster way to get a range of values from a HashMap, or some other type of data structure?
How to access secure web services from a desktop application?
I'm writing a desktop application that will be available to the public. It will contact backend APIs via HTTPS using Jersey client.
I don't know anything about using certificates in desktop apps but from what I've found out so far I'll need to create an SSLContext that reads a public certificate from a KeyStore that is protected by a password.
I'm assuming I can distribute the contents of the KeyStore by packaging it in the Jar of my app. But I don't see how I can securely make the key store password available to the app. I don't want the users to have to enter it manually.
OCR for getting text from an image. Error management
I want to use an OCR program to obtain some text in an image. The text is not black on white so I don't know if it will be possible.
wget -q -O image http://4.bp.blogspot.com/-mIE4JlppKMU/T9_mxKR__wI/AAAAAAAAASs/deHLBL21ZbE/s640/Temple%20Garden.png
convert image -crop 90%x12% +repage name
tesseract name-0 stdout
rm name-* image
wget -q -O image http://4.bp.blogspot.com/-roqIxFx13vQ/T981I3wqwOI/AAAAAAAAAQ0/cJk5AWocPO0/s1600/Tundra.png
convert image -crop 90%x12% +repage name
tesseract name-0 stdout
rm name-* image
wget -q -O image http://2.bp.blogspot.com/-gwU4mAyVWtQ/T3rwIPoaBHI/AAAAAAAAAGA/oqU6T1bxqo0/s1600/Goblin%20Grenade.png
convert image -crop 90%x12% +repage name
tesseract name-0 stdout
rm name-* image
The expected output is:
Temple Garden
Tundra
Goblin Grenade
I also want to manage the error. If it fails I wan't to make an if statement saying "Can't get name".
Using higher order functions to apply a filter?
if user_filter:
for each in something:
if filter_condition_met:
do_something(each)
else:
for each in something:
do_something(each)
Here I am repeating the entire code again which is against DRY principles.
for each in something:
if user_filter:
if not filter_condition_met:
continue
do_something(each)
Here I am doing the filter check for all items in the loop, while essentially it needs to be done just once.
Can I use higher order functions to check the filter condition once and generate a code that does the job? It looks like a filter and then transform operation. Can someone give some ideas?
Scaling WPF GUI
Currently I am working on my first WPF project. I have designed a little Interface using GIMP as follow
When I designed the GUI in GIMP, I used percentages for the area sizes, e.g. the most darken panel has a width of 75% and a height of 90% (of the total window size). However WPF doesn't seem to support percentages for control sizes.
Is there a way to work around this?
I am aware that this question may have been asked before, but I can't find anything that gives me a working solution. Probably I am using wrong keywords.
Can someone help me out?
P.S.: My GUI is already looking like that, however it doesn't scale when the user resizes the window.
Help with this alghoritm in C
I want to create an algoritm for this problem:
- read a number "x"; x>=4
- find a and b so that x=2*a+5*b
How to go about making money from page scraping / data mining? [on hold]
I'm just about to finish writing a web crawler, parser, and indexer that I've been working on for a while now. These three programs work in conjunction with one another. My intentions for this project were to make a set of utilities I could use to download pages from specific sites with, parser over, extract any specific data anywhere on those pages, and then index that data in a database afterwards.
So, with that being said.. I'm wondering if anyone has ideas about how I could use these programs to potentially make a little extra income on the side? I developed these programs in c++ but I also have a very strong understanding of website scripting languages (PHP, perl, js, etc). I know that I will probably need to build a website which handles the mined data and what have you. However, I'm having a difficult time coming up with an idea.
What is different between the internal design of Java and C++ that lets C++ have multiple inheritance?
It's drilled into the newbie Java programmers that Java has no multiple class inheritance, and only multiple interface inheritance, because otherwise you run into diamond inheritance problem (Class A inherits from classes B and C, both of which implement method X. So which of those classes' implementation is used when you do a.X() call?)
Clearly, C++ successfully addressed this, since it has multiple inheritance.
What's different between the internal design of Java and C++ - (i'm guessing in the method dispatch methodology) that allows this problem to be solved in C++ but prevents in Java?
Mailbox Pattern with Variable Arguments in C++
In a game I'm developing, the GUI thread is catching user actions, and the simulation thread is responsible of handling and responding to them.
To minimize complexity and delay, I predefined all possible action types the user may trigger, and created an array of "opcodes". The GUI thread sets "happened" to the relevant array[opcode]
in real time, and the simulation thread, in the proper position in code, samples array[opcode]
and acts on array[opcode].data
if array[opcode].happened == true
.
The problem is that each opcode has a different set (size, types) of arguments. Currently I'm only allowing string arguments, and parses them in the simulation thread - not very efficient. Another solution I can think of is polymorphic opcode class and dynamically casting it in the simulation thread - ugly.
I named this the "mailbox pattern", but I'm sure someone more clever has solved (and named) it already. A pointer to a more elegant solution would be great.
C programming: Input Number and return the number name
I started programming recently, and a teacher of programming called a C program that allows the user to place a digit and in return receive the number of name, example:
input: 5 output: Five
I tried to do with a switch but the program fail when i use more the 1 digit, example:
input: 20 output (expected): twenty output (given): two zero
Right now I'm out of ideas, so I would ask for some tips to guide me, if anyone has any idea how to do, I appreciate the help
Javascript libraries/frameworks and the existing javascript plugin ecosystem
Whether it's Angular, Ember, Knockout, React, or whatever new library/framework has been pushed within the last week day minute second, you often come across a tutorial or getting-started example that leaves you thinking, "Hey, this could be a pretty fancy tool to use."
But while all these tools gain attention, a previously existing – and valuable – ecosystem of pure javascript or jquery-dependent plugins and widgets lurk in the background some of the promoters of the framework du juor ignore them or blissfully gloss over them with high-level integration instructions. It's all on you to try to integrate those plugins or make them on your own within the terms of the framework (especially how it handles the DOM), so have fun while you re-invent the wheel!
The more popular the framework, the more attempts people make to integrate existing tools. AngularUI is one of the more popular examples of such an effort.
One case where it seems to me the libraries/frameworks have not done so well as the existing widgets or integrated well with the existing widgets is the the DataTables table plug-in for jquery. I have yet to see a new framework do tables as powerfully and as feature-rich as DataTables does; this is significant, because most business-related applications are going to involve tables, tables larger than the 10 row, simplistic tables you see in a framework XYZ tutorial.
Then there are plugins/widgets that have received only a little open-source attention with an in-progress, incomplete integration, or else none at all. Given this situation, a few questions come to mind:
Is this concern valid? Is it worth it to buy into a framework but lose so much of the ecosystem and be forced to fit pieces of it into the framework?
What framework/library, in your experience, has the least amount of friction when attempting to integrate with existing widgets?
Does a different approach to building a rich client-side application exist (I don't mean a full-blown Single Page App) allowing you to use the widgets/plug-ins basically "as is", while still maintaining some structure and using js data-binding where possible?
Why are mostly 9999, 99999.... are used for making comparisons
I (I am sure everyone else also) have always seen comparisons of some value to 999 or 9999 .... etc. for e.g.:
in CSS
z-index: 9999
or some times
str.length < 99999
I wonder if there is some fact behind it or its a trend.
can I convert a label that shows the time into a background color?
I have a label that displays the time and I would like to convert that label.text into a color for the background that changes every time the time changes. Is this possible? My code is below. Example: If the time displayed is 11:23:04 I would like the background color to be changed to #112304. If the time displayed is 11:24:00 I would like the background color to be changed to #112400. etc. etc. Private Sub Timer1_Tick() Handles Timer1.Tick
Label1.Text = TimeOfDay
Label2.Text = System.DateTime.Now.ToString("MM/d/yyy")
End Sub
End Class
Help with date and time in vb
My code is below. Every time i debug it, the labels I put in show up as 'Label 1' and 'Label 2' and then switch to the correct date and time as I coded it. Is there a way that I can make the date and time show up right away instead of showing the 'Label 1' and 'Label 2' first? It's only showing up for a second.
Private Sub Timer1_Tick() Handles Timer1.Tick
Label1.Text = TimeOfDay
Label2.Text = System.DateTime.Now.ToString("MM/d/yyy")
End Sub
End Class
Declaring lambdas in Java8
What would be the best practice to declare lambdas in Java8 code? How it was designed to be used?
For example, let's say that we have a method that accept a Function
. I want to provide function implementation that can be reusable. So I can do this:
[A] Implement a Function
interface:
public class Foo implements Function<A,B> {
public B apply(A a) {...}
}
...
useFunction(new Foo());
[B] Declare Function
as lambda in some static
field:
public interface Foo {
Function<A,B> bar = it -> { ....}
}
...
useFunction(Foo.bar);
[C] Use method reference:
public class Foo {
public static B bar(A a) {...}
}
...
useFunction(Foo::bar);
Until functional programing in java8, I tried not to pollute code with static
s. However, now I am somehow 'forced' to use statics (or global singletons) for storing reusable lambdas.
Management System using Oracle DB and Java
In my current semester, I have to make a simple management system using Oracle as DBMS and Java as programming language.I have some basic concept of Java SE. As there is different kinds of java version(Java EE, JavaFX), is it enough to know Java SE or more to make this project? I am really confused about this. And I am sorry if I made any grammatical mistake but hope you understand my confusion. I'll be very grateful if I get any suggestion. Thanks in advance.
Flexible and easy to use settings class
I am thinking about a way to create a flexible "settings class" in C#. The question is: How to provide a confortable way to provide default values to the settings. I want the programmer to access the default settings as easy as possible using intellisense. Therefore I encapsulated the default values in a subclass of the actual settings class (instead of defining them directly in the settings class).
public class ServerSettings
{
public ServerSettings(int port = ServerSettings.Default.Port,
string anotherSetting = ServerSettings.Default.AnotherSetting)
{
this.Port = port;
this.AnotherSetting = anotherSetting;
}
public int Port { get; set; }
public string AnotherSetting { get; set; }
public class Default
{
public const int Port = 7000;
public const string AnotherSetting = "abcd";
}
}
The programmer now is able to access the default values like this:
ServerSettings.Default.Port
And after typing ServerSettings.Default a list with all available default settings will show up. It's like a "multitype enum".
What do you think of this solution? Do you have any alternative ideas? Or some criticism?
Use Case Diagram with all the possible actors, Use Cases and their relationship [on hold]
Sultan Qaboos Library System The Sultan Qaboos University Library has university staff and students as its primary customers. The library is also open to the public with a modest fee for the membership and some different rules. Each University staff member can borrow up to 20 books for up to 4 weeks, postgraduate students 10 books and undergraduate students 6 books. The limit for a member of the public is 6 books for up to 4 weeks. A user can search for a book with an on-line catalogue. If a book is not available for borrowing, a reservation can be made and added to the reservation queue of the book. The library will send a note to the one whose reservation is on the top of the queue when the book is available. When a book is overdue, a fine will be started which will build up each day. The staff and students have the same rate of overdue charge while it is twice as much for a member of the public. A reminder of the overdue item is immediately issued to the borrower when the item becomes overdue. Current journals and magazines can only be read in the library, but issues of past years are bound in volumes by year. These volumes can be lent out in the same way as books. The library has an annual budget for books, journals and magazines. University staff and students can recommend to the library books for purchase, together with details such the book title, authors, publisher, etc. The library will then contact the publisher and purchase a certain number of copies of the book. If there is a high demand on certain books, additional copies will be purchased. Journals and magazines can be recommended only by university staff. These recommendations will be reviewed and approved by a senior librarian.
Ideal export in terms of size for asynchronous module definitions in JavaScript?
When creating AMD modules you can export whatever you like whether it be an object or a function. I vaguely recall reading a recommendation somewhere to export just one thing; the idea being "keep it small."
Using this philosophy means that one might go as far as to export single functions. And when this is coupled with the idea of composition, one will very likely use one function to build up another function. As a result, when loading a page that uses a highly-composed function one might end up asynchronously downloading a handful of little modules in order to build up a composed function.
Take underscore.js which has many functions built in. There are web pages where I just need one or two of it's functions but I find myself a little at odds with pulling the whole library in as a module just for that. I am half tempted to rewrite the one or two functions to avoid that, but that goes against the idea of reuse. Still, because underscore has several dozen function, pulling it down with an AMD loader like RequireJS is often going to mean pulling down more than necessary. If one goes to the other extreme, decomposing a library like underscore into single function modules, one can run into the aforementioned issue of pulling a couple couple handfuls of tiny modules when highly-composed functions are needed.
So what's the verdict? How does one draw the line when deciding how much to export from an AMD module? A function is the smallest composable unit. An object that gets exported is often really a namespace which offers a suite a functions, many of which won't get used.
I searched online for discussions surrounding this, but apparently I couldn't find the right search terms to locate them. If you're aware of any, please include any links where this has been discussed to support your answer.
If MVC is "Separation of Concerns" then why was Razor Syntax introduced?
My question is related to MVC design pattern and Razor Syntax introduced by Microsoft.
While learning MVC design pattern I was told that the idea is based upon a principle known as Separation of Concerns.
But Razor Syntax allows us to use C# in Views directly.
Isn't this intersection of concerns?
Can i use MVC in my OOP exam project?
This is my first post in this forum. I've spend most of the day reading through post about MVC and OOP, most of them very informative, i think it's begging to sink in. . kinda. .
I am to make a program for my exam, it has the these requirements for the backend.
Requirements - back-end
ASP.NET Web Application
Object Oriented code in C#
Displaying data from a database
Saving information send from an HTML form in the database
I want to use MVC and Entity Framework for this. My application will use only CRUD level operations. Which means no business logic (which would be placed in the model), only application logic(placed in the controller). So the model will just be a class representaion of what data is stored in the database. Really i just want to know, when building an application like this, is it OOP?
Out of bound array elements being printed using gcc in Win8 [migrated]
I'm compiling the following code in my m/c using codeblocks and mingw32-gcc.exe v.4.8.1(tdm-2).
#include <stdio.h>
#include <stdlib.h>
int main()
{
int a[8] = {3,1,10,-1,7,2,-8,1};
int b[8] = {3,1,10,-1,7,2,-8,1};
int i=0,alength = (int)sizeof(a)/sizeof(a[0]);
for(i = 0; i < alength; i++){
if(a[i] > a[i+1]){
a[i+1] = a[i] + a[i+1];
a[i] = a[i+1] - a[i];
a[i+1] = a[i+1] - a[i];
}
}
printf("Original array size is %d \n", alength);
printf("Original array elements are given below: \n");
printf("Sizeof(a) is %d \n", sizeof(a));
for(i = 0; i < alength; i++){
printf("\n b[%d] = %d", i, b[i]);
}
for(i = 0; i < alength; i++){
printf("\na[%d] = %d", i, a[i]);
}
}
It's giving me the following output. Here for each array, two extra elements are being printed.
Original array size is 10
Original array elements are given below:
Sizeof(a) is 32
b[0] = 3
b[1] = 1
b[2] = 10
b[3] = -1
b[4] = 7
b[5] = 2
b[6] = -8
b[7] = 1
b[8] = 1
b[9] = 3
a[0] = 1
a[1] = 3
a[2] = -1
a[3] = 7
a[4] = 2
a[5] = -8
a[6] = 1
a[7] = 8
a[8] = 10
a[9] = 9
But compiling the same code in online compiler gives the correct output. OS is Win8 64bit. Any help in explaining and resolving the difference would be appreciated.
Should we refactor our existing codebase to use functional programming, especially streams?
We have a large project written in PHP. It almost exclusively uses imperative operations, as in example 1. Should we refactor our existing code to use functional operations? Do you think that the code in example 2 is easier to maintain?
Example 1 - imperative
$cookieString = '';
foreach($cookieArray as $cookieName => $cookieValue) {
if($cookieString != '') {
$cookieString .= '; ';
}
$cookieString .= $cookieName.'='.$cookieValue;
}
return $cookieString;
Example 2 - functional
return KeyedStream::of($cookieArray)
->mapEntriesToStream(function($cookieName, $cookieValue) {
return $cookieName.'='.$cookieValue;
})
->joinToString('; ');
}
Using macros to implement a generic vector (dynamic array) in C. Is this a good idea?
So far I have only done personal projects at home. I hope to get involved in some open source project some time next year. The languages I that have been using the most are C and C++. I have used both languages for over a year and I feel like I have become quite proficient with both of them, but I really don't know which one I like better.
I personally like C because I think it is simple and elegant. To me C++ seems bloated many unnecessary features that just complicates the design process. Another reason to why I like to use plain C is because it seems to be more popular in the free and open-source software world.
The feature that I miss the most from C++ when I use plain C is probably the std::vector
from STL (Standard Template Library).
I still haven't figured out how I should represent growing arrays in C. Up to this point I duplicated my memory allocation code all over the place in my projects. I do not like code duplication and I know that it is bad practice so this does not seems like a very good solution to me.
I thought about this problem yesterday and came up with the idea to implement a generic vector using preprocessor macros.
It looks like this:
/* Welcome to the DARK SIDE! */
int main()
{
VECTOR_OF(int) int_vec;
VECTOR_OF(double) dbl_vec;
int i;
VECTOR_INIT(int_vec);
VECTOR_INIT(dbl_vec);
for (i = 0; i < 100000000; ++i) {
VECTOR_PUSH_BACK(int_vec, i);
VECTOR_PUSH_BACK(dbl_vec, i);
}
for (i = 0; i < 100; ++i) {
printf("int_vec[%d] = %d\n", i, VECTOR_AT(int_vec, i));
printf("dbl_vec[%d] = %f\n", i, VECTOR_AT(dbl_vec, i));
}
VECTOR_FREE(int_vec);
VECTOR_FREE(dbl_vec);
return 0;
}
It uses the same allocation rules as std::vector
(the size starts as 1 and then doubles each time that is required).
To my surprise I found out that this code runs more than twice as fast as the same code written using std::vector
and generates a smaller executable! (compiled with GCC and G++ using -O3
in both cases).
It seems like I have created a miracle! :D
My question is:
- Would you recommend using this in a serious project?
- If not then I would like you to explain why and tell me (or point me to a link that explains) what a better alternative would be.
Thank you and have a good day! :)
Confusion between F# and C#
I am fairly new to functional programming and C#/F#.
What is unclear to me is: Can you do functional programming in C# and/or in F#? Or is it something like, you write some OO code in C#, and some FP code in F#, and use them together?
Kind regards
What is exclusive arc in database and why it's evil?
I was reading most common database design mistakes made by developer Q&A on stackoverflow. At first answer there was phrase about exclusive arc:
An exclusive arc is a common mistake where a table is created with two or more foreign keys where one and only one of them can be non-null. Big mistake. For one thing it becomes that much harder to maintain data integrity. After all, even with referential integrity, nothing is preventing two or more of these foreign keys from being set (complex check constraints notwithstanding).
I really don't understand why exclusive arc is evil. Probably I didn't understand the basics of it. Is there any good explanation on exclusive arcs?
unit testing using junit,mokito
i am new to unit testing, and i stuck while testing a spring mvc controller using junit,mockito which gets a data from data base. Here is my spring mvc controller code:
@RequestMapping(value="/getdata" , method=RequestMethod.GET)
public List<Components> listContact(ModelAndView model) throws IOException{
System.out.println("i made a call");
List<Components> listContact;
listContact= exampeldao.list();
System.out.println("hiii i made a call but i dnt have any data.....");
return listContact;
}
i can able to make a call from test code to "/getdata" uri, but i could not able to execute listContact= exampeldao.list(); statement. i have defined list() in some other class.
here is my test code:
public class RestTest {
@InjectMocks
ComponentController contrller;
@Mock
Example exampleda;
private MockMvc mockMvc;
@Autowired
DataSource dataSource;
@Autowired
private Example exampledao;
@Autowired
private WebApplicationContext webApplicationContext;
@Before
public void setUp() {
Mockito.reset(exampledao);
mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
}
@Test
public void findAllObjects() throws Exception
{
Components first = new TodoBuilder()
.cname("asdfasf")
.mdesc("asdcb")
.cdesc("asdfa")
.ccode("asdf")
.unitrateusd(24)
.build();
when(exampledao.list()).thenReturn(Arrays.asList(first));
mockMvc.perform(get("/getdata"))
.andExpect(status().isOk())
.andExpect(content().contentType(TestUtil.APPLICATION_JSON))
.andExpect(jsonPath("$", hasSize(0)))
.andExpect(jsonPath("$[0].cname", is("asdfasf")))
.andExpect(jsonPath("$[0].mdesc", is("asdcb")))
.andExpect(jsonPath("$[0].cdesc", is("asdfa")))
.andExpect(jsonPath("$[0].ccode", is("asdf")))
.andExpect(jsonPath("$[0].unitrateusd", is(24)));
}
and when i run unit test i am getting a SecurityException:org.hamcrest.Matchers signature information does not match wit signature of other classes in same package...
any one help me to sort out this issue
Thanks
How to keep awake when you are really sleepy?
I love my job and find my work (programming) very interesting, but sometimes I feel extremely sleepy. This usually happens when I hit a wall and cannot find a solution to some problem for an extended period of time (several days). I try drinking coffee, but it doesn't help much.
I exercise regularly and have decent 8 hour sleep every day, and I think I'm reasonably healthy.
What do you do if you feel extremely sleepy while trying to do programming work?
PS - I realize there are similar questions already, but they didn't get quite enough attentions and answers so I am posting my own.
Relatively larg data on client side in web application
well we are discussing on building a web application where (as per clients requirment) there will relatively large data (60,000 items) to be shown as tree view
lets assume each item is string of 500 characters .
My questions is about maintaining such data on client side.
Basically this is an over kill to be used in asp.NET web form with viewstate (correct me if i am wrong)
what are better options of handling such huge list of items with providing sorting and searching ability on them
I was thinking bring them once and keep them in local storage but then found out local storage to be limited to 5MB and its clear that we need more
lundi 29 décembre 2014
Data Structure Interview question for professional
Is there any one how can share data structure problem and their standard answer with me. So i got an ideal how to answer such a question in big tech company interview's. it quiet helpful for me if you are sharing the problem those they previously asked or similar to them.
Decoupling of Model and API (in an .net WEB API Project)
I currently have one separate project for my models, and one separate project for a API application that consumes this model. The intention of the separation is to avoid any outgoing dependencies from the core model to consumers like the API project, enabling me to have a nice layered structure of responsibility.
In this case though, the API can not use the model as-is, as it requires the classes to be decorated with attributes related to the serialization of the data. Since this is exactly the kind of dependencies from the model that I want to avoid, I can only see my only option being intermediate DTO's that the core model gets mapped upon.
This preserves the decoupling of the model to it's consumers, but obviously introduces some nasty redundancies where I not only manually have to create all the DTO's, but also maintain them to match an eventually changing core model. Even if AutoMapper can take care of the actual mapping.
This feels quite nasty, but since the model project is using an EDMX to define and auto generate code for the model, I'm thinking to change the t4-templates to generate an interface for every class, and using this in the consumer to put a contract on the DTO's and even let the IDE auto-implement them from the interface.
This seems quite reasonable for my, but I wonder if this would be considered a good approach for enterprise-level projects, or if I'm missing something. I guess that the extra layer of intermediate DTO's even could be seen as a good artefact in concreting a separation of the core model contract and the API contract. And if so, maybe the use of model-generated interface would conflict with this separation, even if it has some neat benefits? But in that case, maybe it would be a productive strategy to use the auto-generated interfaces where we do have an 1-to-1 mapping, and create a separate set of DTO's where the contracts actually differs?
Edit
So to be clear, I'm striving for a well partitioned and coherent architecture in order to increase general static code qualities like maintainability and cohesion. Above I gave a specific example of the partitioning of the core model from it's consumers that I try to do while rationalizing about it, and my question is whether the approach suggested could generally be considered good or not. Or could this be too specific to fit any generalized answer?
I know how to program and code, but don't have any idea what to code and program?
What is the best thing for a great developer to do who has the skills in coding and programming but doesn't have a clue what to create? or has an idea but lacks motivation?
Changing a BufferedImage pixel with setRGB changes all BufferedImages
I am having trouble with a weird phenomena with setRGB()
in BufferedImage
.
I am building a 3D Graphics library that relies only on 2D math, and that there are no vectors. It also is not polygon based. To start out, I thought I would try setting different pixels in an empty image by cutting and pasting them, but to my surprise, Java isn't doing what I want it to.
In Java, you can define integers like so:
int i = 0;
In Java, you can also store that variable in another variable. Java stores the value in this case, but only the reference when it comes to Wrapper type Objects.
int j = i; // j stores the value i, not the reference i
In Java, you can change the value of i and j will not be affected.
i++;
If you compare and use System.out to see the values, you will notice j != i and that j is 0, i is 1.
In Java, I have no idea how return
works in a getMethod. While it obviously returns an object, assuming it isn't a primitive type, I would guess just returns a reference if you do return obj
(again, assuming it also is not an anonymous type or local value). However, the getRGB()
and setRGB
methods seem to conflict and write to every BufferedImage no matter which one I choose:
public static void moveRGB(int dx, int dy, Graphics g, BufferedImage img, int x, int y, int distx, int disty) {
// get pixel
final int rgb = img.getRGB(x, y);
System.out.println(rgb);
// paste pixel
img.setRGB(distx, disty, rgb);
// "delete" pixel
img.setRGB(x, y, 0xFFFFFFFF);
g.drawImage(img, dx, dy, null);
}
Apparently the language does not work as expected here because I have rgb as final and yet the value changes and sometimes, the values are inconsistent. For example, sometimes I may put 0xFFFFFF and it will show as -1
or as -16777215
(negative 0xFFFFFF). I tested this on TYPE_INT_ARGB ImageIO-read in image and a TYPE_INT_RGB blank image (which of course was all black).
Logically, you should be able to "move" a pixel by storing the value into memory completely separate from the buffer, then deleting that pixel, and overwriting the stored value into a specified coordinate in the buffer. This is not the case.
What happens is the pixel deletion part causes rgb to lose it's value somehow because the buffer data was overwritten with null (0x00000000). Whether you set it to "null" before or after changing the location of the supposedly stored pixel in rgb
, rgb
still has it's value changed.
If you comment out the "delete" pixel part of the method, it works fine, until you draw two images. This led me to imply that the data is somehow related to the graphics context, but that seemed far-fetched, as looking at the call hierarchy for both setRGB and getRGB do not conflict with the graphics context (apparently).
What I do vaguely know about, is the JIT does optimizations, especially on these images. Another piece of incriminating evidence is that you can createGraphics()
from a BufferedImage. This heavily implies that the Graphics context is changed in such a manner that it is acting as a "static" raster for any image that uses that context.
Above all, the most baffling thing about this is how rgb's value is changing after I supposedly already got the pixel value.
The million dollar question
How can one prevent this from happening with only one Graphics context if at all possible, and how the whole Image drawing process works and what really goes on when setting and getting with setRGB
and getRGB
.
Why is my g++ compiler complaining about whitespace in my C++ code?
I will post the two versions of my code, the first program throws compile time errors, the second compiles and executes successfully. I would like to know if my compiler is complaining because it is just terrible, or if I'm actually violating the syntax of c++11 standard.
//C++ Chapter 4 Drills
#include<iostream>
#include<cmath>
#include<string>
#include<algorithm>
inline void winWedge(){char c;std::cin>>c;}
int main(){
//This is the beginning of the error
std::cout<<"Every time this program loops put in 2 numbers and it will print.\n
When you want it to stop, put in the symbol | ";
//This is the end of the error
std::string word1="a";
std::string word2="b";
while(word1!="|"&&word2!="|"){
std::cin>>word1>>word2;
std::cout<<"\n\n"<<word1<<" "<<word2<<"\n\n";
}
//winWedge();
return 0;
}
---------------------------------------------end of first program---------------
//C++ Chapter 4 Drills
#include<iostream>
#include<cmath>
#include<string>
#include<algorithm>
inline void winWedge(){char c;std::cin>>c;}
int main(){
std::cout<<"Every time this program loops put in 2 numbers and it will print.\n"
<<"When you want it to stop, put in the sybol | ";
std::string word1="a";
std::string word2="b";
while(word1!="|"&&word2!="|"){
std::cin>>word1>>word2;
std::cout<<"\n\n"<<word1<<" "<<word2<<"\n\n";
}
//winWedge();
return 0;
}
Obviously the second program compiles and runs, but it makes me inexplicably furious that my compiler is telling me there is an error when I don't believe there is, and it is refusing to compile the code. This is not python, so why is the whitespace causing this problem? is it the invisible 'return' character?
Everyone knows the adage about blaming your tools, so if this is all I'm doing please call me on it, I'm trying to learn so criticism is welcome as is any insight you can offer.
Providing production code samples as part of an invited freelance work proposal?
I have only recently started to market myself as a 'programmer' rather than an analyst or something else entirely. In a recent search of freelance/part-time/contract work, I came across an ad for a contract "R
Programmer". I was well qualified for the position and submitted my technical resume. I had an interview and was asked to submit a proposal for some contract work for the company, a well-funded start up that has an interesting--and useful--product.
As part of the proposal, they would like, among other things, an R
package that gives them the means to analyze their customer's data along with a write up of what the output(s) of my package means and how it would help their customers. The company also provided five samples of their client's data (along with an NDA that I was required to sign) so I could write and test out my code.
I'm curious as to how I protect myself and the code/R
package I've written from being used commercially? In other words, I'll be providing this R
package as part of a proposal; in other parts of my business, a technical proposal doesn't contain any sort of tool that could be used immediately as part of a commercial business. Is there some sort of copyright I could attach to the package or proposal documentation, similar to their NDA I was required to sign, that could afford me some sort of protection should they decide to use my R
package without payment?
Maybe I'm being anal about this, but what is there that prevents a company from using a code sample commercially without paying the author?
Infinite-Scroll Plugin by Paul Irish Broken--- how to trouble shoot
I am interested in using the Infinite-Scroll jquery plugin by Paul Irish, however it looks like this project is no longer being maintained and the plugin files are not functional.
(I downloaded them, and they do not work)
What is the best way to start trouble shooting this plugin?
Here is a link to the plugin files: https://github.com/paulirish/infinite-scroll
Are there visual learning aids for programmers?
Are there any well-known resources out there that take a visual approach to computer programming? Similar to how one can visualize certain mathematical functions with graphs, are there common ways one can visualize computer functions or other related concepts?
I am trying to create a prototype chat application with threaded messages in the quickest way possible
I have an app I want to make.
I believe the quickest way for me to make it right now would be to find [an open sourced project live chat program like this] (https://livehelperchat.com/how-to-use-chrome-extension-245a.html)and then extend that somehow.
I am not that well-educated in programming, only a few classes that taught java, C++, and basic computational theory. I am okay at figuring things out, but have a hard time even coming up with the question I want to ask.
If I were able to figure out how to extend the website above such that each incoming message has a clickable area, where a reply to that specific message can be returned to the sender of the incoming message, and tracked separately, that would serve the needs of the type of website I'm trying to create.
I understand Google Wave had this threaded chat option? I'm just really not sure where to go from here.
Where I am going by default: reading books about programming methodology, reading an iOS App development book and working through it, doing exercises on Khan Academy in their algorithms area, and searching for open source software that fits what I want to do.
Is this the right way to go about making a prototype people can use for free? I am having a hard time getting started in iOS programming so far, but I figure it will come after I am able to fully define my application. I have a rough description and features that are necessary and wished for, and I can elaborate every piece of it in my head, but I don't feel that I have the expertise to decompose it, much less look at someone else's work.
Do you have a suggestion as to what to work on first that will get me closest to realizing this chat program, fastest?
Most of my work is being done in trying to create the website. A forum with replies would even work if I could figure out a way to spawn a new forum with replies for each new pair of users, then deletes it once the conversation is over, or on a timer, and preferably locks it to those users.
If learning the iOS development parts to make it an app would be easier, I'd like to hear if I'm doing that the right way. Any suggestions vastly appreciated.
How do I call a parameterless function pointer from within a class?
This is an extended new question from my last post: How do I use function pointers within this class?
I have three members in my class:
void (X2D::Graphics::OpenGL::Circle::*draw_ptr)(void);
void draw_filled();
void draw_outlined();
This method shows how they are assigned:
void Circle::fill(const bool fill)
{
m_fill = fill;
if (fill)
draw_ptr = &Circle::draw_filled;
else
draw_ptr = &Circle::draw_outlined;
}
Thus, the 'draw_ptr' function pointer points to either draw_filled() or draw_outlined().
Within the same class, I have the following method:
void draw() { this->draw_ptr; }
However, I placed a debugging point within draw_filled(), which is where it should be calling, and calling draw() does not go in draw_filled(). Because draw_ptr is parameterless, I'm almost positive it's doing nothing but returning the address to the function. However, I want to call what's in this address.
Using draw_ptr() does not work, because I get the error: error C2064: term does not evaluate to a function taking 0 arguments
Am I calling draw_ptr wrong?
How do I use function pointers within this class?
I have a class: Circle. It can draw either a filled circle or an outlined circle. Based on its current setting, I want a general draw() method that calls either draw_filled() or draw_outlined().
In my class, I have the following member: void (*draw)(void);
I have two private variables: void draw_filled(); void draw_outlined();
Then, I have the following method:
void Circle::fill(const bool fill)
{
m_fill = fill;
if (fill)
draw = draw_filled;
else
draw = draw_outlined;
}
I get an error on both draw assignments:
error C2440: '=' : cannot convert from 'void (__thiscall X2D::GL::Circle::* )(void)' to 'void (__cdecl *)(void)' 1> There is no context in which this conversion is possible
Normally, I don't use function pointers in classes, so this is new to me. Any help would be appreciated. Thank you.
Starting a big application with unit testing
I am learning test driven develeopment and read some books about TDD. I learned rules of unit testing. How can I write unit test, how can I select test method names, Act, Assert, Action and like this.
In real word I developed applications that have layered architecture. Domain Layer, Data Layer, Service Layer, UI Layer, ....
How can I start an application with TDD. Is there a rule or way or else. For example starting Service Layer.
wordcloud2.js or d3 word cloud
For creating a word cloud I started using d3 word cloud, but ran into several issues, for most of them I could see a solution on stack overflow
- http://stackoverflow.com/questions/20705036/how-do-i-create-link-of-each-word-in-d3-cloud
- http://stackoverflow.com/questions/10692276/d3-js-tag-cloud-size-from-a-json-array
- http://stackoverflow.com/questions/14376162/can-it-is-possible-to-use-click-event-in-tag-cloud-of-d3-and-if-yes-how ... and a few more.
Does anyone have experience with both D3 word cloud and wordcloud2.js ? Would it be better to switch to wordcloud2.js from d3 cloud ?
I still have a few issues with d3 word cloud - specially around reactive/scalable design and the documentation and examples seem scarce. The example on http://www.jasondavies.com/wordcloud is cool but the git repo has a much smaller example and I am not too comfortable reverse engineering the website.
I primarily chose D3 word cloud - because of popularity in stackoverflow - but I am wondering if using wordcloud2.js is easier.
Are there Computer Softwares or phone apps that are useful to learn computer science?
Are there any Computer Software or phone apps to learn computer science? I want to learn computer programming and I want you guys to list any computer software or phone app that does not need internet connection and which will be helpful to me. Thanks.
Best practice for using namespaces in my PHP libraries
I've been using a tiny and neat caching library on my projects, but I realize that "Cache" is a very generic name and it's easy to get a collision when using it in large projects.
Also, I would like to publish it in Github in order to share it with colleagues and make it easy for all of us to install using composer.
The problem is that I don't really get all this PSR-4 recommendations.
How should I structure my folders? How should I namespace the library? And how should I autoload it from within my projects?
What I need is probably a very comprehensive composer tutorial, that I wasn't able to find yet...
What do I need to know to be a Junior programmer?
I'm a 16 y/o girl that is in love with Informatics and I want to be a junior programmer. But I don't know what skills I have to achieve to be a junior. Could someone reply on this question so that I can work on it and be a junior?
Converting List of objects to an Array of Strings [migrated]
In my main class, I have: List<Person> allPeople = new ArrayList<>();
Then in the class I have a method which returns a String array of all the Id
of people (Person has an accessor method getId()
).
What is the prettiest way to convert the list to an array with just the Ids as String?
This is my current solution:
public String[] getAllId() {
Object[] allPeopleArray = allPeople.toArray();
String allId[] = new String[allPeople.size()];
for(int i=0; i<=allPeople.size()-1; i++){
allId[i] = ((Person)allPeopleArray [i]).getId();
}
return allId;
}
Above works, but is there a 'better' way to do this?
GPL covers the linguistic data in *spell dictionaries?
There are good annotated vocabulary in {a,i,my}spell dictionaries, giving the lexical class et all.
I'm writing a program that needs a large vocabulary, but with a reduced scope, so I don't need all the information on the *spell dictionaries. Then, I'm reading this dictionary data, processing it and rewriting in my own format. The dictionary I'm using is GPLv2 and I want to release my program in BSD.
As the data itself [the idiom] is public domain, but the representation of data [*spell .dic files] is not, maybe I must follow GPL.
But as I'm not using the GPLd code itself, but a derived trough machine processing from it, maybe I must not.
Advice on adding a rich client to an existing ASP.NET WebForms app
I am a french teacher in computer science and I'm about to start a new project. Hre's the background : a colleague of mine has built a student response system similar to Socrative, albeit simpler. His project uses the ASP.NET WebForms technology and its UI feels rather outdated by today's standards for web apps (see the documentation to get an idea).
Our goal is to improve the UX by splitting the project in two :
- the server side containing business logic (authentication, assessment computation...) wouldn't be touched much and would continue to use ASP.NET. A JSON API would be created to expose the needed services.
- a new Web client would be written from scratch. It would consume the server services through the API and let users interact with data in a more modern way. We envision a single page web app using JavaScript heavily. I am in charge of this part.
I used to work as en engineer in CS with some background in Java/J2E, C++ and C#, and I know PHP and Twitter Bootstrap quite well. However, I'm new to JavaScript and professional front-end development. I have read this article, "You have ruined JavaScript" and "No more JavaScript frameworks" : what a mess ! I'd like to get advice on the following points :
- is the planned architecture coherent ? (rewriting the whole app is not a realistic option)
- what technologies should I use client-side ? I hesitate between leveraging a JS framework or a no-framework approach with Polymer.
- if I go for a JS framework, which one ? I had a look at TodoMVC and at first sight I'm considering React+Flux.
I hope my message makes sense. Thanks in advance for your help.
Baptiste
Paths for Programming Language Theory
First, I'm not sure if this is specific enough, but I can't seem to find the answer in other answers nor in a Google search. I'll add any specifics that might be needed.
Some background; I have a BS in CS (2005) and the past few years have found my interests moving towards PLT. Partially as a point of a new challenge in an area I do not currently understand as well. So, I would like to begin to go down this new rabbit hole head first.
My question is what might be the best path to start? I initially thought about an MS in CS, but that didn't work initially due to the curriculum structure (not working friendly). I might be able to swing it now, but have already begun to question if I might benefit from more of an Applied Math degree? In the meantime, I am going to read Type and Programming Languages as it seems to be THE go-to book.
So, to reiterate more clearly: What is the best path to learning PLT? If there is not a BEST, then what are the optional paths so that I can at least have a place to begin researching what works for me?
How to delete break points?
Somehow in visual studio I made a breakpoint. I want to get rid of it but I don't know how. It's the yellow arrow. I'm using visual studio 2013 community edition. Thanks so much for your help!!
Best practices to map DTO to Entity
This question could be subjective, but I'm hoping to gain some insights into how to properly map DTO back to Entity.
From what I've read and implemented, DTO is the object that hold a subset of value from a Data model, in most cases these are immutable objects.
What about the case where I need to pass either new value or changes back to the database?
Should I work with the data model/actual entity in my DAL?
Or should I create a DTO that can be passed from the presentation layer to the business layer then convert it to an entity, then be updated in the DB via an ORM call. Is this writing too much code? I'm assuming that this is needed if the presentation layer has no concept of the data model. If we are going with this approach, should I fetch the object again at the BLL layer before committing the change?
how to build something conceptional quick
Can someone help me to spin some ideas. I would like to build an app and use it only in the Google Chrome browser for practical reasons.
I want to make some helper app for renovation off a hotel complex. Basicly, there is a main contractor and a subcontractor. Every room needs to be renovated by the subcontactor wich consists of a couple of tasks for every room to be completed. During the day, the main contractor makes an inspection off the rooms wich are completed and if there is an issue he should be able to make a simple note and send it to the head of the crew doing the renovations.
I want to make a gui of cubes with room numbers of every room and then by tapping t the person could make a simple note in a sketchy way or typing it. and the sending it.
Can someone assist in giving advice about javascript libraries that could be used, wireframing it, experience with using the google browser app as a way to deploy an app. How to quicly get a nice user interface. Has anybody seen something like this already? I am looking for a way to use tools/components that can be combined to create a functional app.
I hope I am not asking too much so anything is appreciated
Thanks
Uncopiable data, how to?
Is there a way to make data uncopiable but still readable with proper key? Or is there a way to make it readable with key, but upon copy by unregistered system becomes corrupted?
Popbox.js via http://www001.upp.so-net.ne.jp/www2014/
I really like you popbox.js and I have it in my website here http://www.toolbin.com/template5.shtml My issue is that when you click the 1st tall image on that page it hides behind my nav menu. Is there a way I can edit popbox.js or my main css file to make the pop image appear in front of my nav menu? Any ideas or suggestions and much appreciated and I thank you in advance
Jesse
TextOut() - "invalid null pointer"
I've written a program in C++ which is displaying a white window.
Furthermore I'm displaying a text in the window. To accomplish this purpose,
I use the TextOut()
-Function. It's working,
but besides the displayed sentence, the following is displayed:
invalid null pointer (__onexitbegin != NULL && __onexitend != NULL)||(__onexitbegin == NULL && __onexitend == NULL)
After this error there are lots of chinese signs.
I researched on the internet but havn't found anything useful yet.
This is the code I'm using to display the text:
const wchar_t* string = L"This is a test.";
hdc = BeginPaint(hwnd, &ps);
TextOut(hdc, 0, 0, string, 500); //the length is just for test purpose
EndPaint(hwnd, &ps);
Thank you for your advice.
Is anyone capable of becoming a programmer and having a career?
There's a lot of articles I've seen debating that only certain people are capable of earning a living from programming. These sort of articles make me feel disheartened. I've dabbled a bit with programming, sure I haven't actually created anything yet but I'm really interested in learning and improving my skills.
I'd like honest answers please. If one is interested and puts in the effort to learn and practice, can they actually make a living, or am I wasting my time because "only some people can do it"?
PHP MySql - Statistical Reporting - Best Approach to query appointment system time utilization
I have built an appointments system for various medical practices. Practice schedule appointments - I am looking to provide analysis on the amount of time that has been utilised by the practice.
I can break up my requirements into lots of smaller queries in order to calculate the percentage of available time that has been utilised by the practice.
e.g A query to calculate the total available time that has been allocated to each practice for a given week:
# Get the practice and number of working hours they have per week allocated to them
SELECT
pd.practice_id,
sum((TIME_TO_SEC(TIMEDIFF(pd.close,pd.open)) - TIME_TO_SEC(TIMEDIFF(pd.lunch_stop, pd.lunch_start)) ) / 3600 ) as working_hours_per_week
FROM
practice_days as pd
GROUP BY
practice_id;
Then for each practice, I can sum the appointment lengths which are in the completed status in a given date range (e.g. last week) to see how many hours have been scheduled and completed for that week.
Finally - I can divide the time used by the working hrs per week to get a percentage utilisation.
Already this is a little hairy - however what happens when I want to look at a different weeks / months or all historical etc.
Is there a better cleaner way of analysing this data? e.g. a decent reporting system of some sort. I am using PHP mysql and Laravel PHP framework.
I don't really want to be going down the route of setting up a Shiny R server just for this unless absolutely necessary.
Java: Analyze audio from video
I am in the process of writing a file management application for film projects. It will parse the video and look for the sound of the clapperboard. Once found, it will provide the user a frame from the video so they can enter the information in some nearby forms. The formats I need to use are mp4 and MTS.
My problem is, I don't understand where to start. As far as mp4 goes, I have tried a combination of JAAD and musicg to split the audio off the video, save it as a .wav, and analyze it with musicg. While this works, it seems rather inefficient and it only works with mp4.
How are mp4 and MTS files saved, and how can I read them in java? Once I get the audio split apart, how do I find the clapperboard?
Thanks in advance.
Mac OS X preferences saving, when to apply/save changes made by user
It is typical for Mac OS X apps to have preferences that apply seamlessly, and preferences dialogs don't have "OK" or "Apply" button. I want to implement this behavior in my project, but I can't decide when to apply/save changes made by user.
It's quite clear that checkboxes and drop-downs can be saved immediately upon change, but when it comes to text fields, this approach seems questionable. For example, entering "programming.stackexchange.com" as host address will trigger 29 HDD writes, which seems just wrong. Moreover, in my simple implementation this will cause the entire settings file to be rewritten.
So is there any standard way to implement MacOS-like preferences?
Is it possible to prepare for a c++ interview in a day or two?
I need to prepare for a c/c++ interview, can you tell me if it's possible for me to prepare in two day's time? And it's specifically only for the interview. I do have the basic knowledge of OOPS concepts and a basic programming experience. Thank you.
Java script code help for a url textbox [on hold]
Can someone please give me Javascript code that when a user enters a url into a text box it filters it so that they can't enter a url without a .blogspot.com or .wordpress.com or .tumblr.com at the end? Also, I know how to code an add button, but could you make it so that this code is after the user taps the add button? Thanks so much!!
Buying music for a mobile app [on hold]
Not sure if this is the right place.
I am looking for a place to buy music for a mobile app. I found audiojungle but there is an apparent limit of 10000 copies of the app, was looking for somewhere around 250 000 allowed reproductions minimum.
So my question is, where programmers look for legal audio material when developing a mobile app?
Is it difficult to develop a programming language which is closely related to human language? [on hold]
Will it be difficult in developing a programming language which is much more closer to our language ?
It was just to know the view of programmers across the globe towards the natural programming language.Thanks for giving me your views on this .
What is the correct Object Design/Architecture for the following scenario?
I am developing some custom controls in an Object Oriented language (using Swift/Cocoa but this is a technology agnostic question). In particular, I have a horizontal and vertical set of buttons that behave very similarly except for the fact that one is oriented vertically and the other horizontally.
My question: what is the correct way to structure these two 'things' in my project:
Should I have a (abstract) parent class that has common functionality and then two derived concrete classes for the specifics needed for horizontal-ness vs vertical-ness. This feels the most correct but given that the object is composed of other objects you are then going to have proliferated throughout the view hierarchy going downwards.
Alternately, should I design one highly generalised class that has a property for orientation and then a lot of if/switch logic in the code to drive behaviour based on this. This feels like a code-smell.
Just go and create two separate similar but technically unrelated classes and just do a little more repeated typing. Since so many things are driven by the orientation this almost seems simpler than 1 above.
Or is there another alternative?
Other canonical examples where this would arise could be horizontal vs vertical: - scrollers - stacking panels
To attempt to clarify on regarding design goals and requirements, I would like the question answered in terms of how Apple Software Architects might have approached the NSScrollView class (or how any large organization might approach similar UI library code with "mirror" horizontal and vertical components).
birth and death process algorithm in Python
i did birth and death process in R for bayesian model detection. How can i do the program in Python ? I dont wanna call the program using PypeR or Rpy. I am new in Python.any suggestion or documentation please ?
Which Queue provides better performance? (Queue + Hashmap or just Queue)
Is it better (in terms of performance, OO design and readability) to manage a queue of events using a map (id/object) and then have queue to hold just the ID's like below:
1.
private Map<Integer,Person> allPeople = new HashMap<>(); //id, person Object
private Queue<Integer> peopleQueue = new LinkedList<Integer>(); //a queue of IDs
When a new item added to the map, then method adds the id to the queue: q.add(id);
Then the program retrieves the correct person object by something like:
int id = peopleQueue.remove();
Person p = Map.get(id);
//etc etc
Is above 'better' than doing:
2.
private List<Person> allPeople = new HashList<Person>();
private Queue<Person> peopleQueue = new LinkedList<Person>();
//then in method I would have
peopleQueue.add(person);
Then to retrieve an id I would do:
int id = (peopleQueue.remove()).getId();
for(Person person: allPeople){
if(person.getId().equals(id)){
return person;
}
}
The system must handle a large number of people, surely it would be quicker using my first implementation rather than iterating through each person.getId() until a match is found?
Difference between O(n) and O(n^2) and what is best/worst/average case for an algorithm
What is the difference between O(n) and O(n^2). when comparing both these orders which one is best case. Kindly suggest what is best case/worst case/average case and how can we find out for an algorithm. Thanks in advance
Why C is still in the category of High Level Language?
Many of the textbooks on C Programming language tells that C is a high level programming language but many of the tutors online says that C is also a middle level programming language .Why is it like that ?
Is it OK to use the MIT license for a project that uses Qt?
I built a Qt application. Am I allowed to LICENSE it under the MIT license?
Qt is a cross-platform application and UI framework for developers using C++ or QML, a CSS & JavaScript like language. Qt Creator is the supporting Qt IDE. Qt Cloud Services provides connected application backend features to Qt applications.
Qt, Qt Quick and the supporting tools are developed as an open source project governed by an inclusive meritocratic model. Qt can be used under open source (GPL v3 and LGPL v2.1) or commercial terms.
Since Qt is licensed under LGPL v2.1, I guess the answer is Yes, it's fine to use the MIT license on my non-commercial app.
The LICENSING page is too complicated for me.
So, is there any problem if I licensed my app under the MIT license?
Hi i'm a java developer planning to develope a software for my new medical shop. Which framework shall I use.
Sir, I'm a Java developer setting up a medical shop @ my location , Since i'm a J2EE developer i'm planning to write a s/w to maintain my medical shop's daily transaction and stock maintenance and weekly/monthly/yearly reports,also it should be web base.( is Web based application good for my requirements ? )
Need advice and which "JAVA" framework to use to develope my s/w also which DB to use. preferably using all open source tools available in the market.
If MVC is "Separation of Concerns" than why is Razor Syntax introduced?
I am new here. My question is related to MVC design pattern and Razor Syntax introduced by Microsoft. While learning MVC design pattern I was told that the idea is based upon a principle known as Separation of Concerns. But Razor Syntax allows us to use C# in Views directly. Isn't this intersection of concerns?
Accessing file from FTP server works for all but one file
I have an application setup on a FTP server. When users access it, it downloads some files (also hosted on the server) needed for the install.
I have a problem with only one of those files (office.dll) a library used to interact with Microsoft Office. When the program tries to download this specific file I get this error.
"You don't have permission to access {Path}/office.dll on this server." "Additionally, a 404 Not Found error was encountered while trying to use an ErrorDocument to handle the request."
I have checked that this file has the read and write permissions just like all the other files on the server.
Any help?
Host Application Online, Only Download Newer Version
Excuse me if this is not technically a programming question but I've spent the last 2 weeks on this to no avail.
I want to host my application (vb.net, winform) on a web server, embed the application URL in a config opened by a program used by my client daily. What I want is:
First time the program opens, download and install my application. Every time the program opens after that, my URL is opened and if the application on the server is of a newer version then the one installed on the client's device, install it. If not do nothing.
I want this to be done without opening webpages to the user and asking him to keep clicking on "Next" and so on. It would be annoying if everyday he has to see a webpage telling him he has the latest version of the application installed.
I tried ClickOnce Deployment but couldn't get it to do what I want. It works the other way around, every time the application is opened manually it checks for updates on the server.
Any help would be much appreciated.
Thank you
dimanche 28 décembre 2014
Java Ceil Weirdness
Why does this output 0 instead of 1?
System.out.println((int) (Math.ceil(1/2)));
While this one correct outputs 1
System.out.println((int) (Math.ceil((double) 1/ (double) 2)));
Shouldn't Math.ceil(double) automatically type cast the 1/2 to double?