Ques: We know how the regular tree walk algorithm works. If you have some values in the tree then the tree walk algorithm prints everything in order. This means all the succesor and predessor are near eachother. Explain Why all the successor and predessors are near eachother with the tree walk algorithm. Remember about the situation when there is a subtree and when there is no subtree.
samedi 31 janvier 2015
Is my boss's preference for Latin-1 over UTF-8 when it comes to database configuration justified?
We are using MySQL at the company I work for, and we build both client-facing and internal applications using Ruby on Rails.
When I started working here, I ran into a problem what I had never encountered before; the database on the production server is set to Latin-1, meaning that the MySQL gem throws an exception whenever there is user input where the user copies & pastes UTF-8 characters.
My boss calls these "bad characters" since most of them are non-printable characters, and says that we need to strip them out. I've found a few ways to do this, but eventually we've ended up in a circumstance where a UTF-8 character was needed. Plus it's a bit of a hassle, especially since it seems like the only solution I ever read about for this issue is to just set the database to UTF-8 (makes sense to me).
The only argument that I've heard for sticking with Latin-1 is that allowing non-printable UTF-8 characters can mess up text/full-text searches in MySQL. Is this really true?
Aside from that point, I see no reason why we shouldn't switch to UTF-8. It's my understanding that it is superior and becoming more ubiquitous.
Which of us is right?
Avoiding a large amount of overloads
I'm currently writing a mailing interface for our enterprise application. Dependent on the send mode (regular email, bulk email, templates, mailmerge, ...) our Send()
method requires a bunch of parameters.
Now we have got this Send()
method that offers to take around 20 parameters, with nearly 10 overloads and default values.
Now of course you could use the C# 4.0 feature of named parameters like described here, but even that would be a mess when mostly 10 of 15 overloaded parameters have to be used.
Is there some better practice?
Algorithm for merging multiple rows of data
I need an algorithm to merge multiple rows for data, where one column is the index column and if one or more rows have the same index value merge the column values into a single row, and lastly sort the rows one the index column.
ASCII ART Example:
Starting point:
------------------------------------
| IndexCurve | Column A | Column B |
------------------------------------
| 1 | 1 | |
------------------------------------
| 2 | 5 | 5 |
------------------------------------
| 1 | | 1 |
------------------------------------
| 2 | 5 | 5 |
------------------------------------
| 3 | 1 | |
------------------------------------
Outcome:
------------------------------------
| IndexCurve | Column A | Column B |
------------------------------------
| 1 | 1 | 1 |
------------------------------------
| 2 | 5 | 5 |
------------------------------------
| 3 | 1 | |
------------------------------------
As you can see the empty columns have been merged, duplicates have been discarded and rows have been sorted on the index column. (NOTE: The column values should not add to each other.)
I have been trying to come up with an efficient algorithm for this but so far I think I have failed as i think its pretty ineffective and also its not working correctly.
Here I have some code to show you what I currently have, the first code pieces are just POCO objects to give you an idea of what I'm working with, have also included equal methods for you to see how I compare objects.
public interface IWitsmlLogCurveInfo
{
string Mnemonic { get; set; }
bool IndexCurve { get; set; }
}
public class WitsmlLogCurveInfo
{
string Mnemonic { get; set; }
bool IndexCurve { get; set; }
protected bool Equals(WitsmlLogCurveInfo other)
{
return string.Equals(Mnemonic, other.Mnemonic);
}
public override bool Equals(object obj)
{
if(ReferenceEquals(null, obj))
{
return false;
}
if(ReferenceEquals(this, obj))
{
return true;
}
if(obj.GetType() != this.GetType())
{
return false;
}
return Equals((WitsmlLogCurveInfo)obj);
}
public override int GetHashCode()
{
return (Mnemonic != null ? Mnemonic.GetHashCode() : 0);
}
}
public interface IWitsmlLogDataColumn
{
IWitsmlLogCurveInfo WitsmlLogCurveInfo { get; set; }
string Value { get; set; }
}
public class WitsmlLogDataColumn : IWitsmlLogDataColumn
{
public IWitsmlLogCurveInfo WitsmlLogCurveInfo { get; set; }
public string Value { get; set; }
protected bool Equals(WitsmlLogDataColumn other)
{
return string.Equals(Value, other.Value) && string.Equals(WitsmlLogCurveInfo, other.WitsmlLogCurveInfo);
}
public override bool Equals(object obj)
{
if(ReferenceEquals(null, obj))
{
return false;
}
if(ReferenceEquals(this, obj))
{
return true;
}
if(obj.GetType() != this.GetType())
{
return false;
}
return Equals((WitsmlLogDataColumn)obj);
}
public override int GetHashCode()
{
unchecked
{
return ((Value != null ? Value.GetHashCode() : 0) * 397) ^ (WitsmlLogCurveInfo != null ? WitsmlLogCurveInfo.GetHashCode() : 0);
}
}
}
public interface IWitsmlLogDataRow
{
IList<IWitsmlLogDataColumn> Columns { get; set; }
IWitsmlLogDataColumn GetIndexColumn();
}
public class WitsmlLogDataRow : IWitsmlLogDataRow
{
public IList<IWitsmlLogDataColumn> Columns { get; set; }
public IWitsmlLogDataColumn GetIndexColumn()
{
return Columns.SingleOrDefault(x => x.WitsmlLogCurveInfo.IndexCurve);
}
protected bool Equals(WitsmlLogDataRow other)
{
return Columns.All(x => other.Columns.Contains(x));
}
public override bool Equals(object obj)
{
if(ReferenceEquals(null, obj))
{
return false;
}
if(ReferenceEquals(this, obj))
{
return true;
}
if(obj.GetType() != this.GetType())
{
return false;
}
return Equals((WitsmlLogDataRow)obj);
}
public override int GetHashCode()
{
return (Columns != null ? Columns.GetHashCode() : 0);
}
}
public enum FrictionType
{
Annulus,
Sliding,
Rotating
}
public interface IWitsmlLogFriction
{
FrictionType Type { get; set; }
IList<IWitsmlLogDataRow> Rows { get; set; }
}
public class WitsmlLogFriction : IWitsmlLogFriction
{
public FrictionType Type { get; set; }
public IList<IWitsmlLogDataRow> Rows { get; set; }
public override string ToString()
{
return string.Format("FrictionType: {0}", Type);
}
protected bool Equals(WitsmlLogFriction other)
{
return Type == other.Type && Rows.All(x => other.Rows.Contains(x));
}
public override bool Equals(object obj)
{
if(ReferenceEquals(null, obj))
{
return false;
}
if(ReferenceEquals(this, obj))
{
return true;
}
if(obj.GetType() != this.GetType())
{
return false;
}
return Equals((WitsmlLogFriction)obj);
}
public override int GetHashCode()
{
unchecked
{
return ((int)Type * 397) ^ (Rows != null ? Rows.GetHashCode() : 0);
}
}
}
Here is the Algorithm Function itself:
private IList<IWitsmlLogDataRow> CombineMultipleFrictionTypes(IList<WitsmlLogFriction> witsmlLogFrictions, WitsmlLogCurveInfo indexCurve)
{
if(indexCurve == null)
{
throw new NoNullAllowedException("IndexCurve can not be null!");
}
if(witsmlLogFrictions.Count == 1)
{
return witsmlLogFrictions.First().Rows;
}
WitsmlLogFriction witsmlLogFrictionA = witsmlLogFrictions.FirstOrDefault();
List<IWitsmlLogDataRow> rows = new List<IWitsmlLogDataRow>();
if (witsmlLogFrictionA == null)
{
return rows;
}
foreach(WitsmlLogFriction witsmlLogFrictionB in witsmlLogFrictions.Where(witsmlLogFriction => witsmlLogFriction.Type != witsmlLogFrictionA.Type))
{
foreach (IWitsmlLogDataRow witsmlLogDataRowA in witsmlLogFrictionA.Rows)
{
// Get index curve for row A
IWitsmlLogDataColumn indexCurveA = witsmlLogDataRowA.GetIndexColumn();
if (indexCurveA == null) continue;
IWitsmlLogDataRow tempWitsmlLogDataRowA = new WitsmlLogDataRow(witsmlLogDataRowA.Columns);
foreach(IWitsmlLogDataRow witsmlLogDataRowB in witsmlLogFrictionB.Rows)
{
// Get index curve for row B
IWitsmlLogDataColumn indexCurveB = witsmlLogDataRowB.GetIndexColumn();
if (indexCurveB == null) continue;
// Compare index curve values
if(indexCurveA.Equals(indexCurveB))
{
// Index curve values are identical, append columns from row B onto row A, except row B's index column
foreach(IWitsmlLogDataColumn column in witsmlLogDataRowB.Columns.Where(column => !column.WitsmlLogCurveInfo.Equals(indexCurve)))
{
tempWitsmlLogDataRowA.Columns.Add(column);
}
}
else
{
rows.Add(witsmlLogDataRowB);
}
}
// Add the new row
rows.Add(tempWitsmlLogDataRowA);
}
}
switch(indexCurve.IndexType)
{
case LogIndexType.datetime:
return rows.OrderBy(x => Convert.ToDateTime(x.GetIndexColumn().Value)).ToList();
default:
throw new ArgumentOutOfRangeException("indexCurve", "IndexType: " + indexCurve.IndexType + " is not supported.");
}
}
The problem is I think its pretty ineffective, but it could also be the only way to do it, and it adds more data then it should. What would be a better and efficient way to solve this?
How to make scalable modules in a div element
I'm interested in creating web modules that are encapsulated by a div element in a manner that, by simply resizing the div, everything in that div scales to the dimensions of that div proportionately (fonts, sub-divs, etc.).
A couple of weeks ago, I made this form that scales pretty well as you resize the page. I was able to achieve this by sizing things with the CSS3 viewport relative sizing units.
These viewport units work great if your module is the size of the entire viewport (the size of the whole page), but these same units don't work if your intended "viewport" is going to be just a div that is only one part of an entire web page and a div you intend to reuse in multiple pages with total different "surroundings".
Conceptually, the idea is to be able to create reusable modules that can be placed anywhere inside of any webpage, and by simply setting the modules div container size, all contents scale proportionately based on the size of the div.
I want to create modules that can be consumed by any webmaster, and all the webmaster has to do is set the height, width and location of the module, and the module scales perfectly to the webmaster's desired dimensions.
Any advice toward this concept would be appreciated.
How to handle authentication to web service from mobile?
I'm making a mobile application, and I use JSON Web Token Authentication (JWT Auth), but I have three questions about:
- Should I use refresh-tokens or non-expiring access tokens?
- In case I use refresh-tokens, when the token expires, should I sign out the user (and force the user to login again) or create a new one and send it back to the app so it can be used for future requests?
- How should I save the token on the mobile (database, preferences,etc.)?
Any help and resource about this (books,documents,blog,etc.) would be appreciated, thanks in advance!
Why many duck-typed dynamic programming languages would use class-based approached instead of prototype-based OOP?
Since quite many dynamic programming languages have the feature of duck-typing and they can also open up and modify class or instance methods at anytime (like ruby and python), then…
Question 1) What’s the need for a Class in a dynamic language? Why the language is designed that way to use a class as some kind of “template” instead of do it the prototype-way and just use a object?
Also javascript is prototyped-based, but coffeescript (the enhanced version of js) chooses the class-based way. And it goes the same for lua (prototyped-based) and moonscript (class-based). In addition, there’s class in ES 6. So…
Question 2) Is it suggesting that if you try to improve a prototype-based language, among other things, you should change it to class-based? If not, why is it designed that way?
Symfony 2 Log out error
I am trying this links from 7 days but still today I am getting errors may I know what the wrong with this login page?
Why I am not getting log out after login?
My Code
# app/config/security.yml
security:
encoders:
Acme\MainBundle\Entity\User: plaintext
role_hierarchy:
ROLE_ADMIN: ROLE_USER
ROLE_SUPER_ADMIN: [ ROLE_ADMIN, ROLE_ALLOWED_TO_SWITCH ]
providers:
administrators:
entity: { class: AcmeMainBundle:User, property: username }
firewalls:
admin_area:
# pattern: ^/admin
http_basic: ~
logout:
path: /logout
target: /
access_control:
- { path: ^/admin, roles: IS_AUTHENTICATED_FULLY }
I can Login with this code after 7 days of work but can't log out may I know where I am wrong?
When are you violating a license like the GPL?
Specifically in the following scenarios where you're working on an open source library using an incompatible license like the MIT license.
- You copy & paste a method from a GPL library - blatantly a violation assuming the GPL library created the method themselves.
- You create a function with a similar purpose but you create it from scratch - presumably not a violation
- You use the same code as a GPL library, but you improve on it (optimize performance for example) - is this a violation?
- You use the same code as a GPL library, but you superficially refactor it (e.g. rename variables for clarity, add comments, but don't really change the underlying logic) - is this a violation?
- You translate code from a GPL library to another language but keep the logic exactly the same - presumably not a violation?
I know these are possibly questions for lawyers but I'm hoping to get a rough idea.
ORMLite on App-Server
I am wondering if it is a good idea to use ORMLite as persistence layer in Java EE environments?
I am also uncertain about the implementation of ORMLite in a JAX-RS Jersey environment in particular. Should I either access the DAO in a static way, wrap it in a Singleton or instantiate it when needed in my resources?
When does ORM become "requirement" for RESTful API?
I've started building a RESTful API in PHP's Slim framework. The framework appealed to me because of its light-weight design and routing features.
However, the dataset is somewhat large - there would be about 20 types of resources, with many associations and nested sets. So far, I have implemented my own custom ORM methods on resource classes, such as "select from database by primary key". Slim does not provide any ORM features. I am wondering if the scale of the API is large enough to recommend the use of a framework with built-in ORM support or integration with an ORM such as Doctrine or Propel.
Am I at the point where I should use an ORM to help mitigate the complexity of changes to database tables, attribute names, etc?
I am also open to using other technologies - it seems Python's Django is highly regarded as a framework for building RESTful APIs.
RESTful Backend - How coupled should my back end and front end be?
I'm creating a web application with a front end client written in angular as well as a back end that I'm writing in Django (there are reasons I picked the frameworks but they are irrelevant to my question).
I have my front end planned out down to every page that will be available. I currently am only going to implement the angular cient but in the future I plan on implementing a native android and iOS app for learning purposes.
My question is how coupled should my back end design be with my front end client?
Should I design my endpoints on a per view basis? This seems like back end will need work when I create another client.
Or should my endpoints be more focused around exposing CRUD functionality for my models? This seems like it would leave room for creativity and make the back end more flexible.
These are a few of the questions I have been asking myself and I provided them to add a little more scope to my question.
Even if I went with the crud approach it seems like I will still be implementing specialized endpoints for handling common application features.
Thanks in advance.
Setting logging in GlassFish
I use Server-sent events technology and GlassFish with standart java.util.logging. How can I disable logging event is sent to the log file?
Why is the Document Object Model the view?
I was told by a Javascript programmer not to do DOM manipulation in model code.
I also remember hearing a snazzy tune for a JS framework (I forget which one): "Get your models out of the DOM".
This is confusing to me. The DOM is the Document Object Model. To me it sounds like "get your model out of the model".
Should my JS model really not touch the DOM? Can someone set me straight on model v. model?
Difference between constructor property?
Using parentheses:
function Constr(){};
console.log(Constr.prototype.constructor);//logs Constr()
Constr.prototype.constructor === Constr();//returns false
Without using parentheses:
function Constr(){};
Constr.prototype.constructor === Constr;//returns true
Why is this so?
Console-like interface GUI for browser or linux
For a long time I'm in search for something like a good old terminal framework/tool to create user interfaces with just text and easy to develop.
I want something like that used to build SUSE/openSUSE Yast (when called from console). I already saw "Curses" but it doesn't pleased me.
This is a really silly question, but there is some tool or framework to create text only interfaces, or, even if doubtful, a text-only GUI for web pages (some where mouse is not required, just a keyboard)?
You might be thinking why in hell I need something like that, but this is the reason: I'm a developer working to upgrade an old software used in car repair shops by mechanical professionals. They're always with hands dirty with a plethora of oils and/or busy and the old App have a nice interface developed in Visual Foxpro (no mouse is needed at all).
The first requirement is to build a new application where a mouse should not be used; second is it must be running an application server and a PostgreSQL database with a "dumb" client (should run on terminal or web browser).
So, is there some kind of tool/framework for mouse-free GUI?
No changes in requirements are allowed (believe me, I tried).
Why C++ STL vector does not go out of range
I have this code and I am wondering how it works; Why does it allow me to access an element using a value larger than the size of the vector using the operator[]
?
But then when I use the at()
function which does bounds checking, it throws the proper error.
I read that the behavior of doing this is undefined
, but I am curious: Why does operator[]
work for out of range element access?
// vector of length 3
std::vector<int> adj(3);
// output: 3
printf("Size of adj is %lu\n", adj.size());
// assign using index that is larger than vector size, e.g., 12
adj[12] = 314159;
// succeeds, output: 314159
printf("adj[12] is %d", adj[12]);
// fails, throws out_of_range
adj.at(12);
A quick question about twitter automation
I am posting this because I'm hoping someone will give me an idea on how I can accomplish the following. I am not expecting anyone to do all the work for me but I would like some direction and some ideas.
It's quite simple. I have a list of around 400 "tweets" in text. Like this:
1) "@tomweber Hello, I'm tom and I do not know programming"
2) "@barrysmith I like icecream and football and cake"
3) @mikeweber I have brown hair and blue eyes ....
....
400) @katweber This is now the end of the list
I'm wondering if it is possible to create a simple program which will take each text in turn with a few seconds gap in between each and then tweet them in my twitter account. I am aware there are "scheduled tweeters" available like hootsuite or futuretweets but I am not looking for something like that.
I am a complete n00b but I just learnt how to do macros in word, and I was wondering if there is something like that I could use in this scenario, except it's not restricted to Microsoft Word; basically I only need three actions: 1) select one piece of text 2) tweet it in my account 3) move onto the next piece of text. And then run this continuously until I reach the end of the text?
Could someone give me some direction? Is it absolutely necessary that I must create my own "twitter app" or is there a simpler way that I can accomplish this?
Much appreciated and I apologize if I sounded like an idiot / clueless :-)
login to programme java using hsqldb?
hi i need help in my programme i need to vérifier login from my database hsqldb to access to my programme in mysql everything is good bat in hsqldb is not wanting to work at all i using hsqldb is memory database this is my code i using
for connection to database:
Connection conn = null;
private static final String USERNAME = "root";
private static final String PASSWD = "toor";
private static final String CONN_STRING ="jdbc:hsqldb:Data/explorecalifornia";
public static Connection Conne_HSQLDB(){
try {
Connection conn = DriverManager.getConnection(CONN_STRING,USERNAME,PASSWD);
System.out.println("Connected");
return conn;
}catch(SQLException e){
JOptionPane.showMessageDialog(null,e.getMessage()+ "\nCode: " + e.getErrorCode());
return null;
}
}
for login this is my code
if(UserTFD.getText().length()==0 || PassTFD.getText().length()==0){
JOptionPane.showMessageDialog(null, "un champ est vider !");
}else{
String sql = "select * from LOGIN WHERE USERNAME=? and PASSWORD=?";
try(
Connection conn=ConxDB.Conne_HSQLDB();
PreparedStatement pst=conn.prepareStatement(sql);
){
pst.setString(1, UserTFD.getText());
pst.setString(2, PassTFD.getText());
ResultSet rs = pst.executeQuery();
if(rs.next()){
dispose();
new SettingGUI().setVisible(true);
}
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
and the message erreur is
user lacks privilege or object not found: LOGIN
for my database this is my the code
SET DATABASE UNIQUE NAME HSQLDB397995F7ED
SET DATABASE GC 0
SET DATABASE DEFAULT RESULT MEMORY ROWS 0
SET DATABASE EVENT LOG LEVEL 0
SET DATABASE SQL NAMES FALSE
SET DATABASE SQL REGULAR NAMES TRUE
SET DATABASE SQL REFERENCES FALSE
SET DATABASE SQL SIZE FALSE
SET DATABASE SQL TYPES FALSE
SET DATABASE SQL TDC DELETE TRUE
SET DATABASE SQL TDC UPDATE TRUE
SET DATABASE SQL TRANSLATE TTI TYPES TRUE
SET DATABASE SQL CONCAT NULLS TRUE
SET DATABASE SQL NULLS FIRST TRUE
SET DATABASE SQL UNIQUE NULLS TRUE
SET DATABASE SQL CONVERT TRUNCATE TRUE
SET DATABASE SQL AVG SCALE 0
SET DATABASE SQL DOUBLE NAN TRUE
SET DATABASE SQL LONGVAR IS LOB FALSE
SET DATABASE TRANSACTION CONTROL LOCKS
SET DATABASE DEFAULT ISOLATION LEVEL READ COMMITTED
SET DATABASE TRANSACTION ROLLBACK ON CONFLICT TRUE
SET DATABASE TEXT TABLE DEFAULTS ''
SET FILES WRITE DELAY 20
SET FILES BACKUP INCREMENT FALSE
SET FILES CACHE SIZE 10000
SET FILES CACHE ROWS 50000
SET FILES SCALE 1
SET FILES LOB SCALE 32
SET FILES DEFRAG 0
SET FILES NIO TRUE
SET FILES NIO SIZE 256
SET FILES LOG TRUE
SET FILES LOG SIZE 200
CREATE USER SA PASSWORD DIGEST 'd41d8cd98f00b204e9800998ecf8427e'
CREATE USER "root" PASSWORD DIGEST '7b24afc8bc80e548d66c4e7ff72171c5'
CREATE SCHEMA PUBLIC AUTHORIZATION DBA
SET SCHEMA PUBLIC
CREATE MEMORY TABLE PUBLIC.LOGIN(ID INTEGER GENERATED BY DEFAULT AS IDENTITY(START WITH 0) NOT NULL PRIMARY KEY,USERNAME VARCHAR(40),PASSWORD VARCHAR(40))
ALTER TABLE PUBLIC.LOGIN ALTER COLUMN ID RESTART WITH 3
ALTER SEQUENCE SYSTEM_LOBS.LOB_ID RESTART WITH 1
SET DATABASE DEFAULT INITIAL SCHEMA PUBLIC
GRANT USAGE ON DOMAIN INFORMATION_SCHEMA.YES_OR_NO TO PUBLIC
GRANT USAGE ON DOMAIN INFORMATION_SCHEMA.TIME_STAMP TO PUBLIC
GRANT USAGE ON DOMAIN INFORMATION_SCHEMA.CARDINAL_NUMBER TO PUBLIC
GRANT USAGE ON DOMAIN INFORMATION_SCHEMA.CHARACTER_DATA TO PUBLIC
GRANT USAGE ON DOMAIN INFORMATION_SCHEMA.SQL_IDENTIFIER TO PUBLIC
GRANT DBA TO SA
GRANT DBA TO "root"
SET SCHEMA PUBLIC
INSERT INTO LOGIN VALUES(1,'root','toor')
INSERT INTO LOGIN VALUES(2,'onee','onee')
Where should I create utility classes that are used by unit tests, integration tests and functional tests?
Say I have a project that's using the standard Maven/Gradle project directory structure, with the source file directory like this:
src
├── functTest
├── integTest
├── main
└── test
What would be the best way of creating utility classes that provide methods that may be used by unit test, integration test and functional test classes? Is there a standard approach to this?
Would a suitable approach be to create a testutil
folder under src
and place utility classes in there?
Php Form Data to Text Problem
Whenever i enter form data, the form action points to my php processing script but instead of writing it to a text file, it opens the code in the browser, what could be wrong?
My form
<form name="web_form" id="web_form" method="post" action="myprocessing.php">
<p><label>Enter name: </label><input type="text" name="name" id="name" /></p>
<p><label>Enter email: </label><input type="text" name="email" id="email" /></p>
<p><input type="submit" name="s1" id="s1" value="Submit" /></p>
Myprocessing.php
<?php
$name = $_POST['name'];
$email = $_POST['email'];
$fp = fopen("formdata.txt", "a");
$savestring = $name . "," . $email . "n";
fwrite($fp, $savestring);
fclose($fp);
echo "<h1>You data has been saved in a text file!</h1>";
?>
Measure and locate areas of similar value in an image
I saw this picture online and wanted to see if I could create an algorithm to give ordinary images an effect like this: http://ift.tt/1BF03Rw
My idea was to take the input image and first find the largest area of pixels that are within a predefined threshold of similarity (basically are of similar value). Then I take those pixels and form a square containing all of them. After doing that until most of the image is covered in squares, (no overlapping squares) I plan to color the squares based on their values (so that lighter values might be colored white, midtones green, and dark shades purple.
My problem is that I can't find an algorithm to group pixels with similar values. It'd be nice if someone could point me in the right direction or if someone has some comments on my algorithm idea that's fine too.
As a side note, I'm going to make this completely in javascript so whatever method you suggest should preferably be fast and shouldn't require server side code (for example no storing of data for genetic algorithm training) Thanks in advance!
Small code, big test
I have this code in a controller of an MVC implementation:
public void execute() {
try {
String path = userSelectsFile();
if ( path == null ) return; //Just returns if the user press "Cancel"
//Load the data
Collection<Info> infos = Infos.fromJSON(getInputReader(path));
//Show the data in the interface
new ShowTransformationsInTree(win(), infos, win().getTree()).execute();
} catch (Exception e) {
new ComplainAction(win(), "Unable to...blah, blah", e).execute();
}
}
To test this, I have to mock the user interface to show file dialog and make getInputReader method an abstract factory method.
So here goes the test:
/**
* Mocks the LoadTransformationsAction so the factory method getReader returns a ByteInputStream
*/
public class MockLoadTransformationsAction extends LoadTransformationsAction {
//CONSTRUCTOR REMOVED FOR CLARITY.....
@Override
protected InputStreamReader getInputReader(String path) {
assertEquals(FAKE_ABSOLUTE_PATH, path);
return new InputStreamReader(
new ByteArrayInputStream(TestHelpers.createDataBytes());
}
}
/**
* Test the proper loading of the data.
*/
@Test
public void testLoadData(@Mocked final FileChooser anyChooser) {
new Expectations() {{
//Mocks the IntelliJ idea API
FileChooser.chooseFile(null, null, null); result = new MyFakeVirtualFile(); //Returns a fixed path
}};
//Loads the data from the JSON file
MainToolWin m = new FakeMainToolWin();
LoadTransformationsAction action = new MockLoadTransformationsAction(
m, new FakeProject(), new MockInputProgram());
action.execute();
//Test that the transformations are in the UI Tree
DefaultTreeModel model = (DefaultTreeModel)m.getTree().getModel();
assertEquals(2, model.getChildCount(model.getRoot()));
assertEquals(3, model.getChildCount(model.getChild(model.getRoot(), 0)));
}
QUESTIONS
Am I doing to much to test to little?
As you can see there are mock and facke objects all the way, so much mocking can make my test unreliable?
A better design can be proposed?
Is there an optimal way to find the best division of an interval of some positive integers?
I am struggling with a conceptual problem. I have positive integers from an interval [1800, 1850]. For every integer from that interval, let's say (without loss of generality) 1820, I have about 3000 horses. The 1820 number is a year of birth for a horse. Thoses horses were fed with a traditional food and some of those horses were fed with experimental food (there were 29 types of different experimental food). For every horse there was recorded a variable for each feeding named goodness of sneeze (the higer the goodness variable is, the better). Let's assume after every feeding a horse did sneeze. Every single horse could be fed with different type of food every time he came on feeding (with uniformal distribution). Let us assume that sneeze for horses comes from Poisson distribution with lamba=1 parameter.
Now I am looking for the best [1800,1850] interval division on intervals like:
[1800,1810), [1810,1826), [1826,1850] to say: for every subinterval this or that experimental food (or maybe traditional in some cases) gave best average sneeze for horses born in that interval.
I do not know if it is possible, but let's assume that horses does not come on feeding with regularity. Some of them come more often than others. Experiment took 20 days.
If there is a good way of generating the best interval in a relatively fast way? I tried to make a loop for i in 1 to 50 where i is a number of [1800,1850] interval divisions centers. If i=1 I check: [1800,1801],(1802,1850] [1800,1802],(1803,1850] ... [1800,1849],(1849,1850] and check which experimental food gave the biggest mean sneeze in that subinterval and answer the problem as this example:
[1800,1807],(1807,1850] is the best division from division with 1 interval centers for horses born in [1800,1807] the best food is experimentalFoodnr25 and for horses born in (1807,1850] the best food is experimentalFoodnr14. With respect to traditional food they give 0,04 higher mean sneeze for horses. (0.04 is of course a weigthened mean with respect to number of horses in both intervals)
Then I can go for i=2, and so on and so on but there higher the i is, the less horses are in the subintervals and the estimate of the average sneeze has greater standard error. So I thought about to choose the best [1800,1850] division that has the biggest weigthened mean of a's where a is calculated from subinterval and is to be as formula:
$a = \fi( 1- p )^{-1} * \sqrt( Var(X)/n_{x} + Var(Y)/n_{y} ) + \mu_{X} - \mu_{Y}$
where X are the records for horses treated with the experimental food giving the highest average sneeze in that subinterval, Y are the records for horses treated with traditional food in that subinterval. $\mu$ are means of that records, $Var$ are variances and p is the probability of that P( \mu{X}-\mu{Y}>a)=p (where I assue \mu{X} has normal distributions).
Can someone has any idea of relatively fast algorithm for that problem? If the problem is not clear please tell me what to specify.
How to measure the quality of a web crawler algorithm
I developed a new web crawler algorithm as a part of my thesis using java. Now i should compare my work with previous developed crawler algorithms. Since every developed algorithm has its own web server environment to test on and its different with the other environments of the other web crawler algorithms. Besides some of these algorithms are uses just a single as a starting seed while the others are using multiple seeds for crawling. So it will not be fair to compare them as same standards.
I need to know how to find (or what is) the common futures that can allow me to compare these previous algorithms like BFS [1], OPIC [2] and PageRank[3] with I developed one, and what is the key future for measuring the quality when you developing a new web crawling algorithm.
References:
[1] Najork, Marc, and Janet L. Wiener. "Breadth-first crawling yields high- quality pages." Proceedings of the 10th international conference on World Wide Web. ACM, 2001.
[2] Abiteboul, Serge, Mihai Preda, and Gregory Cobena. "Adaptive on-line page importance computation." Proceedings of the 12th international conference on World Wide Web. ACM, 2003.
[3] Page, Lawrence, et al. "The PageRank citation ranking: Bringing order to the web." (1999).
Thanks in advance
insert photo in mysql database
I am using mysql database.I am using mysql work bench for the user interface.I also connect libre base for the user interface.now my question is how to insert photo in the server.what are the ways to insert jpeg files inside the schema
Getting wrong answer on online judges [on hold]
I have written the following code for the http://ift.tt/1yQ6C2s, which I have tested thoroughly. I have tried running it on all the corner cases and also on some very typical inputs like 0 and 1. It ran successfully each time, but I'm still getting WA. What might be the reason?
#include<stdio.h>
int main()
{
int t;
scanf("%d",&t);
while(t--){
int a,end=1,i,unit[500],temp=1;
scanf("%d",&a);
long long b;
scanf("%lld",&b);
if(a==1){
printf("1\n");
continue;
}
if(b==0){
printf("1\n");
continue;
}
unit[0]=1;
bool goOn=true,marker=false;
while(goOn){
temp*=a;
for(i=0; i<end; i++){
if(unit[i]==(temp%10) && (temp%10)!=1)
marker=true;
}
if(marker)
goOn=false;
if(!marker){
unit[end]=(temp%10);
end++;
}
}
int tmp=b%(end-1);
if(tmp==0)
printf("%d\n",unit[(end-1)]);
else
printf("%d\n",unit[(tmp)]);
}
return 0;
}
Which might be the test case that I might be missing?
Is there some structured format for drawing source control branching diagrams?
Everyone on my team draws branch diagrams differently, including how branches exit or reintegrate to the parent, how cherry-pick merges are shown, and a host of other aesthetic choices.
Is there some structured format for drawing source control branches (like UML but for source control)?
software shows contact system administrator suddenly
I am using point of sale software for my business. the software has been installed my system.the shortcut and some of the files has been implemented in my usb drive.i am using ms sql for database.suddenly today my software shows contact system administrator when i am clicking the shortcut.please help me.
What is really a resource?
I'm starting to study about web api's and REST and I'm having a hard time to understand what is really a resource. Basically the book I'm reading says that a resource is a conceptual mapping to one or more entities. Searching on the internet I found this from a dissertation:
The key abstraction of information in REST is a resource. Any information that can be named can be a resource: a document or image, a temporal service (e.g. "today's weather in Los Angeles"), a collection of other resources, a non-virtual object (e.g. a person), and so on. In other words, any concept that might be the target of an author's hypertext reference must fit within the definition of a resource. A resource is a conceptual mapping to a set of entities, not the entity that corresponds to the mapping at any particular point in time.
Which again says a resource is a conceptual mappings to one or more entities, but that says that any information that can be named can be a resource. The book also stresses that entity in this case doesn't refer to business objects but can be really anything.
Now, this idea of resource seems pretty important, but I can't grasp what really a resource is and why it should be a mapping.
So what is really a resource, why it should be a mapping to one or more entities and what are some examples?
Using actionBar items within a method to navigate the app
How can i use actionbar menu items from within a method. *Somthing like public boolean page2() { WebView webView1 = (webView) findViewById(R.Id.webview1); webView.loardUrl("file:///android_asset/zoo_plant2.html"); { boolean onOptionsItemSelected(MenuItem item) { switch(item.getItemId()) { case R.id.action_prev: page3(); return true; case R.id.action_next: page1(); return true; } return super.onOptionsItemSelected(item); }} these code gives me errors though. Thanx for the help..
What does stubbing mean in programming?
I often hear the term stub, stub out somethings, stubs, ...etc. What does stubbing mean in programming, where the word come from? and in what contexts it can be used?(just examples)
Statistics about the usage of programming paradigms
I hear very often that the object-oriented programming paradigm is the most widespread. But are there any scientific statistics about how often other programming paradigms like procedural programming are used today?
I searched at gartner, but didn't found anything.
Transpose a matrix without a buffering one
How is it possible to transpose a MxN
matrix without using a "buffering" matrix? In the latter case it's easy and quite the "classic" approach...
Given a matrix[M][N]
, I would like to put it into a void transpose_matrix(int matrix[][])
function which operates directly on the matrix passed as reference which, as previosly said, would edit the matrix memory space to transpose its elements.
e.g:
A =
1 2 3 4
5 6 7 8
9 1 2 3
A after transposing itself (without pretty printing)[1]:
1 5 9 2
6 1 3 7
2 4 8 3
Thanks!
[1]: Printing the matrix as if it was actually a "new" NxM
matrix.
vendredi 30 janvier 2015
Finding a Pre-Written Software License
I've been researching licenses for a few days for a software project I've been working on that I'd like to apply a license to. I couldn't find anything on Stack Exchange, but I apologize if a very similar question has already been asked.
I know I'm going to upset a few of you, but I'm looking for a very restrictive open-source software license. To give an example, something like the Creative Commons BY-NC-ND v4.0 license would be perfect, but if it were for software (CC is not for software).
Here's what I'm looking for in a pre-written license:
- End user is free to share and redistribute the source code (and/or binaries)
Under the following conditions:
- End user must provide appropriate attribution, a link to the license, and indicate if changes were made (in any reasonable manner, so long as it does not suggest I endorse their use)
- End user must not use the software for commercial purposes.
- End user must not share or redistribute the software (source or binary) if they modify the source.
Thank you for any and all help you can provide. I'll be glad to share any additional details if necessary.
How to implement the repository pattern for an app that will change its database from sql to nosql on in couple of years?
I have been reading a lot about repository implementation. I am confused about which way to implement it for a project I am sure would change its data layer methods because of db migration from MS Sql Server to NoSQL in a couple of years.
Imp #1
- Implement Rep layer as a completely separate layer. This will have its own interface and conversion methods here. This rep layer has a dependency on DAL and in turn BLL will have a dependency on this layer
Imp#2
- Implement Repository not as a separate layer but have its interfaces in Business Logic Layer and the methods in DAL.
I am leaning more towards imp #1 since it looks cleaner. However some explanations of experts I have read use imp#2. I think there must be a clear reason to use one over another according to the situation. I would ideally want our switch to a different database be as painless as possible.
Injecting a javascript code to all requested web pages by a desktop application
I work in a community school and I have been requested to censor some words in all requested web pages (page content-html level). If I could inject a javascript code I can do that with a simple javascript code.
My question is can I inject that javascript code to every requested web page with a desktop program? If yes, can you recommend me some topics so I can start research?
I'm a web developer. I could also do that with browser extensions but managing browser extensions are hard for all browsers that's why i am looking a solution at system level.
Where is the Elasticsearch topology/architecture diagram?
Where's the Elasticsearch topology/architecture diagram? I've heard many good things about Elasticsearch and it seems to be widely used for some time now, but what boggles me is that there is no simple conceptual diagram to be found on their website: http://ift.tt/lFHJOM. Well, at least not an easy to find kind of way. Sure there's some videos, but that's it?!
What I'm looking for is information on a few things:
1) What are 'master' and 'slave' concepts? What are the general terms to describe these concepts? I want to know so I can then further Google on these higher-level terms to understand analogous concepts in other distributed systems like Couchbase.
2) Does the client talk to a master node, and then is the master node in charge of routing the request to the proper shard in the cluster (possibly a different node)? Or is the hashing done on the client side and then talks to the proper node directly?
3) Can you explain to me a split-brain scenario in depth? How does this apply to other distributed systems like Couchbase? Or is it not applicable?
Thank you.
Forcing Opengl 2.0 and above in c++
I am a student learning c++ and opengl for 5 months now and we have touched some advanced topics over the course of time starting from basic opengl like glBegin/glEnd to VA to VBO to shaders etc. Our professor has made us build up our graphics engine over time form first class and every now and then he asks us to stop using one or the other deprecated features and move on to the newer versions.
Now as part of the current assignment, he asked us to get rid of everything prior to OpenGl ES 2.0. Our codebase is fairly large and I was wondering if I could set OpenGL to 2.0 and above only so that having those deprecated features would actually fail at compile time, so that I can make sure all those features are out of my engine.
Thanks!
AdMob singleton class method import
For iAd i coded my own singleton iAd class however, for AdMob I found a tutorial from Google developers...
I needed to get the AdMob to work in a different ViewController called ViewControllerTWO.
So I imported #import "GADMasterViewController.h" into ViewControllerTWO and I placed...
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
shared = [GADMasterViewController singleton];
[shared resetAdView:self];
}
However, i'm receiving 2 errors:
1)No known class method for selector 'singleton'
2)No visible 'GADMasterViewController' declares selector 'resetAdView:'
I don't understand why i'm getting this error when i properly imported AdMob from one VC to another.
Git, semantic versioning and how it fits into (my) a typical development timeline?
I'm working on a Q&A system and about to tag my current application with "1.0.0" for it's first official version/tag. It's about to be rolled out for beta testing to a limited test audience next. Is "1.0.0" correct at this stage?
Also, no doubt there will be many bugs found at that stage. Do I keep it as "1.0.0" but forcefully moving the tag until it's release. Or upon fixing the bugs, would I give it a new tag "1.0.1". Then after another round of testing perhaps "1.0.2"
So when working on enhancements (e.g. new features such as a new menu, new search input field) would these be minor changes as in from "1.0.0" to "1.1.0"?
Return message to Android client from java Server via tcp sockets
I am a beginner in Android with intermediate Java programming skills. I am also just learning socket communication. I am trying to make a very simple client/server connection. I have Android app as a client and trying to
1) pass message to Java program on PC and then
2) return a message back to the android client.
First part is working fine. The problem is in returning the message from server to client.
Server code (Java):
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class Main {
private final static Integer IN_PORT = 4444;
private static ServerSocket serverSocket = null;
private static Socket sktIn;
private static InputStreamReader inputStreamReader;
private static BufferedReader bufferedReader;
private static String message;
private static PrintWriter printWriter;
public static void main(String[] args) {
try {
serverSocket = new ServerSocket(IN_PORT); //Server socket
System.out.println("Server started. Listening to the port " + IN_PORT);
} catch (IOException e) {
System.out.println("Could not listen on port: " + IN_PORT);
}
while (true) {
try {
sktIn = serverSocket.accept(); //accept the client connection
inputStreamReader = new InputStreamReader(sktIn.getInputStream());
bufferedReader = new BufferedReader(inputStreamReader); //get the client message
message = bufferedReader.readLine();
printWriter = new PrintWriter(sktIn.getOutputStream(), true);
printWriter.write("Returned back \n"); //write the message to output stream
printWriter.flush();
printWriter.close();
inputStreamReader.close();
sktIn.close();
System.out.println(message);
} catch (IOException ex) {
System.out.println("Problem in message reading/sending.");
ex.printStackTrace();
}
}
}
}
Client main activity (Android):
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class SimpleClientActivity extends Activity {
private final Integer OUT_PORT = 4444;
private final String S_IP = "192.168.1.104";
private EditText textField;
private Button button;
private String message;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
textField = (EditText) findViewById(R.id.editText1); //reference to the text field
button = (Button) findViewById(R.id.button1); //reference to the send button
//Button press event listener
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
message = textField.getText().toString(); //get the text message on the text field
textField.setText(""); //Reset the text field to blank
new ConnectClient(message, S_IP, OUT_PORT, getApplicationContext()).execute();
}
});
}
}
Separate AsyncTask class for connection:
import android.content.Context;
import android.os.AsyncTask;
import android.widget.Toast;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
public class ConnectClient extends AsyncTask<String, Void, String> {
private Socket socket;
private PrintWriter printWriter;
private String param;
private Context context;
private Integer PORT;
private String IP;
private static InputStreamReader inputStreamReader;
private static BufferedReader bufferedReader;
private static String message;
public ConnectClient(String par, String ip, Integer prt, Context ctx){
super();
this.context = ctx;
this.param = par;
this.PORT = prt;
this.IP = ip;
}
@Override
public void onPreExecute() {
Toast.makeText(context, "start " + param, Toast.LENGTH_SHORT)
.show();
}
@Override
protected String doInBackground(String... params) {
try {
socket = new Socket(IP, PORT); //connect to server
printWriter = new PrintWriter(socket.getOutputStream(), true);
printWriter.write(param); //write the message to output stream
printWriter.flush();
printWriter.close();
socket = new Socket(IP, PORT); // second connection to server
inputStreamReader = new InputStreamReader(socket.getInputStream());
message = "after isr";
bufferedReader = new BufferedReader(inputStreamReader); //get the client message
message = bufferedReader.readLine();
inputStreamReader.close();
socket.close(); //closing the connection
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return message;
}
@Override
protected void onPostExecute(String result) {
Toast.makeText(context, result, Toast.LENGTH_SHORT).show()
}
@Override
protected void onProgressUpdate(Void... values) {
Toast.makeText(context, "In progress", Toast.LENGTH_SHORT).show();
}
}
The java program executes ok and the Android app runs without any problems but the end result is not as desired.
If I remove the second socket = new Socket(IP, PORT); // second connection to server
, then server is receiving messages fine. In the java console I get printed whatever I put in the app and send. But the second Toast is empty (the message from the server is not passed). And I get SocketException (closed) in the LogCat:
01-29 06:38:36.039: W/System.err(11547): java.net.SocketException: Socket is closed
01-29 06:38:36.059: W/System.err(11547): at java.net.PlainSocketImpl.checkNotClosed(PlainSocketImpl.java:134)
01-29 06:38:36.059: W/System.err(11547): at java.net.PlainSocketImpl.getInputStream(PlainSocketImpl.java:216)
01-29 06:38:36.059: W/System.err(11547): at java.net.Socket.getInputStream(Socket.java:343)
01-29 06:38:36.059: W/System.err(11547): at com.example.simpleclient.ConnectClient.doInBackground(ConnectClient.java:63)
01-29 06:38:36.059: W/System.err(11547): at com.example.simpleclient.ConnectClient.doInBackground(ConnectClient.java:1)
01-29 06:38:36.059: W/System.err(11547): at android.os.AsyncTask$2.call(AsyncTask.java:287)
01-29 06:38:36.059: W/System.err(11547): at java.util.concurrent.FutureTask.run(FutureTask.java:234)
01-29 06:38:36.059: W/System.err(11547): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
01-29 06:38:36.059: W/System.err(11547): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
01-29 06:38:36.059: W/System.err(11547): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
01-29 06:38:36.059: W/System.err(11547): at java.lang.Thread.run(Thread.java:841)
If I leave socket = new Socket(IP, PORT); // second connection to server
line of code in, there are no error messages, but the message is passed only once to the server. 2nd, 3rd, end so forth don't go through (nothing displaying in the console). Though if I leave the console running and shut down the app, another null comes through.
In any case, the second Toast (on the client side) is either empty (the message from the server is not passed) or not displayed at all (message = bufferedReader.readLine();
blocks further execution). For instance, If I comment out the line message = bufferedReader.readLine();
, then I get "after isr" in the second Toast. Or, in the case when the second socket = new Socket(IP, PORT); // second connection
is present the second Toast does not display at all.
What am I missing. How do I send a message from server back to the client?
YAGNI principle put to practice
I recently came across to this principle and so far it is clear the fact that doing things that you don't need at the moment is not feasible as they might not be used or might be changed.
That being said, consider the following scenario: You're working on an application that needs to display text in labels, in several places/parts. The targeted language is English, and there is no requirement to implement multi-language. At this point, if you needed multi-language feature, you'd define every string in a resource file (let's say it's an XML file) and create/use a class to read them and assign them to the corresponding labels (according to the language). Thing is, since multi-language is not a requirement, YAGNI.
So, do you still define strings into a resource file and implement the reader, or you hard-code them and reafactor when you actually need it?
What is a better design a light weight user or a heavy weight heavy user model?
This is a design question and I am confused about how to design my user object. As in most systems, user is the central part of my application and a lot of information scattered around my database points back to the user for example a user can have multiple orders, mulitple Addresses, and he may have won multiple prizes. If we want to talk about ONLY user and his basic information we can be done with ID, firstnmae, lastname etc. So I have two clear choices
- Create a light weight user object which looks like following:
public Class User
{
public int Id {get;set;}
public string FirstName {get;set;}
public string LastName {get;set;}
public string SomeMoreInformation {get;set;}
}
and get all the infromation at the other information at the run time like orders and Prizes on need basis.
OR
Design a more contained object which carries all the required information with it but is little heavy:
public Class User
{
public int Id {get;set;}
public string FirstName {get;set;}
public string LastName {get;set;}
public string SomeMoreInformation {get;set;}
public Address HomeAddress {get;set;}
public List<Prizes> Prizes {get;set;}
}
Which Does any design model align to a good design philosophy? Are there any best practices in the kind of situation that can help me make a decision?
2D Desktop Application Engine
Okay I know this is some kind of "What library should I use?" but please hear me out and understand that the main problem for my question are games. Because whenever I try to do my research I end up walking through the API of another game engine. So I hope this one gets through:
I want to write an application for presentations and knowledge management. I've already found some useful libraries for the "multi platform native UI stuff" and things but what I can't seem to find is something like a "2D Desktop Application Engine".
I am talking about a library or an engine that will help me to create a desktop-like environment. What I mean by that is e.g. that I don't want to have to take care e.g. about clicking events, window-message passing and/or window ordering and basic stuff like that. But on the other hand it should not restrict me from anything design related.
At some point I was already thinking about using a 2D game engine for such a task but I am afraid that I'd have to implement the "desktop-like-behavior" part myself and this just does not feel right in the year of 2015.
So does anybody know a library that would fulfill my needs? Best regards and thank you for any help!
Specflow or BDDfy or other
I am looking to start using BDD in my next .NET project and I was wondering if anyone has experience using Specflow, BDDfy or another similar tool and which of them would be recommended for a team that is new to BDD. This excersise will be a trial and if successful will become the BDD standard/best practice for future projects.
The team will be working with a QA and a BA, the BA will be responsible for writing user stories with the help of the QA. The QA might also help in writing the test stubs for the scenarios.
Thanks,
Chris
Define Interface Simplicity vs Implementation Simplicity
In Richard Gabriel's The Rise of ``Worse is Better'', he talks about the simplicity of interface vs the simplicity of implementation in a design.
I've never been able to quite grasp what he means and searching the web for the answer has only yielded information about Java's interfaces (the structure of classes, etc) vs the code in Java's methods and classes.
What does he mean by interface and implementation and what does simplicity mean for each of them?
How to organize remote Git branches when team does single change releases?
I am a member of a project team with somewhat unusual (or at least from my perspective) release methodology and team dynamic. The way we have been doing releases is rolling out a single functional bundle at a time, all of which, as a rule of thumb, was done by a single developer. Developers do work on their virtually independent functional areas, that are all nonetheless part of the same deployment bundle (WAR file and its corresponding Git repo), concurrently but it is not certain or clear whose change will go in in what order. It often depends on whoever finishes and gets their stuff tested first. So Dev1
may be working on Change1
within TeamProject
and Dev2
will be working on Change2
in the same application, and sometimes their changes may be interdependent (such as changing a shared API) but it is not clear when each will be rolled out to PROD.
The way we currently do Git branch management is that each change gets its own remote branch, which defacto means there is one remote branch per developer. The biggest problem I see with that is that, in order to be refreshed of your teammate's changes, you have to manually sync your branch to their branch, which is a manual and often a PIA process, excuse the term. It may be okay for the developer whose release is the very next one in line, for his branch is what the next version of the release will look like once it is rolled out (in the existing single change release setup). But it surely does not work for the developer whose release comes right after as (s)he has to build their changes on top of the first developer's changes. However, they don't want the second developer to push into the first developer's branch as to keep the change pristine and exclude it from the release. So the 2nd developer has to do the merging of the 1st developer's branch into his branch and then push his stuff into that branch on top of the 1st dev's changes. That would not be half as bad if it were clear who the 1st and who the 2nd developer is, IOW, whose changes will first be rolled out.
Now, by the nature of this post thus far, it is clear that I am not the father of this process and that I am aware of many of its inherent flaws. One notable flaw happened recently when we were promoting our changes to the TEST environment. I had been working in my dedicated branch but the version that was deployed to TEST was built out of my peer's branch (it had his changes only). I was about to push my stuff but didn't want to lose his, as I value our QAs time and wanted his and my tester to be able to work concurrently. So I synced my branch to his (cherry picked his changes into mine, after the common ancestor) so that both his and my changes were in. It worked fine. However, he wanted to push a bug fix a day later and did it out of his own branch without syncing with mine. Guess what happened: my changes were gone from the build and only his were present. Needless to say, these multiple remote branches make continuous integration (which I would like to start doing and is not presently done), difficult or virtually impossible.
Frustrated with all this, I have been working on a proposal to my team how to change this configuration. My idea is to have a SHARED REMOTE BRANCH that everyone pushes their stuff into and that is something like a work-in-progress branch that anything can go in as long as it compiles and passes tests (basically passes the build). Then there is a release branch to which stuff is not pushed in directly but is cherry-picked out of the WIP branch to correspond to what we want in the release. So if we think that Dev1's changes will go in the immediate next release, we cherry pick his changes in it. But the important thing is there is one UNIFIED branch for all developers on the team that work on the same project as opposed to them working in each one's isolated silo. This way, we could actually rebase our local branches with the remote and get our peer's changes timely as opposed to when they become part of the master (or production).
I would like to inquire about the pros and cons of my proposed methodology vs what the team is doing presently and is explained above. And generally, with the idea of the current release culture in mind, which perhaps is not within my powers of changing as it is affected by many members of the organization above me, what would be the most efficient and painless teamwork setup.
android API version distribution info in the US
the android developers page has a pie chart showing the percentages of each platform (API version) currently running android across the world:
Is there any reliable source that shows this info just for the US, or North America?
Thanks
About to have my first interview in less than 12 hours
I'm about to have my first interview related to programming. It is an internship so I don't think they'll ask advanced questions but I don't want to take any chances. What can I expect from this type of interview? I've been reading some programming questions that are asked in interviews and the questions do require some thinking but I understand the solution. Any advice would be great!
Why can we use the same name for local variable in different scopes?
I was wondering why is it possible that we can use the same name for local variable in different scopes?
Like we can have two methods which both can have variable with the same name.
What makes this possible and what happens behind the scenes?
I have a forum application that i need a customized css code to expand the replies in my forum
Hey I am new to this thing but have dabled in BASIC coding for what it is worth.
I am putting together a website for the first time through WIX. There is a forum application( Social Forum ) that I am using to communicate with my members. The forum works fine but the replies to each discussion are closed by default and I have to go through each reply and click it to open it. My goal is to have all the replies open when I open the topic.
The app , Social Forum, has an input where I can use customized CSS to modify the application but I dont know what I need to change to make this possible.
I will attach the apps default code and if someone can tell me what to change so that the replies are open by default I would be forever in your debt.
Link to My Websit: http://ift.tt/1yfSZJX
Copy of Social Forum default code : http://ift.tt/1yfSWxT
Thank you so much for taking the time to read this and if you can help I would REALLY appreciate it.
Thanks again!
Repository Pattern and custom queries/REST API. Is it the right approach?
I'm in the early stages of working on an application that is using the Repository Pattern to provide a data access abstraction. This application will have some form of a simple REST API but I'm not sure how to approach this using repositories. To illustrate this, a typical (very simplified) example of a repository is something like this:
<?php
$repo = new PostRepository(); // this would be resolved from an IoC container
$post = $repo->getByEmail('foo@wherever.com');
or maybe a little less rigid, like this:
$post = $repo->getBy('first_name', 'Bob');
But the pattern doesn't seem suited to anything more complicated like, say, the query from this url:
http://ift.tt/1zfPOX7
It seems like to handle stuff like that (let alone any much more complicated queries that many APIs support) you would pretty much end up having to reimplement the underlying ORM, or create a very leaky abstraction, neither of which seems ideal. Am I going about this wrong?
Database integration of Rails and Laravel apps
I have some very small apps on a VPS running ruby on rails and a co-worker also have some of his own apps running on laravel at another VPS. So far we dont needed to share any data among the apps, but we are currently developing something that would have some overlaping database tables like a Users
table. How would you make that integration? Create a mysql database for all apps to connect? Is there someway to "replicate" User
updates on a database to another one?
Is my boss's preference for Latin1 over UTF-8 when it comes to database configuration justified?
We are using MySQL at the company I work for, and we build both client-facing and internal applications using Rails.
When I started working here, I ran into a problem what I had never encountered before; the database on the production server is set to Latin1, meaning that the MySQL gem throws an exception whenever there is user input where the user copies & pastes UTF-8 characters.
My boss calls these "bad characters" since most of them are non-printable characters, and says that we need to strip them out. I've found a few ways to do this, but eventually we've ended up in a circumstance where a UTF-8 character was needed. Plus it's a bit of a hassle, especially since it seems like the only solution I ever read about for this issue is to just set the database to UTF-8(makes sense to me).
The only argument that I've heard for sticking with Latin1 is that allowing non-printable UTF-8 characters can mess up text/full-text searches in MySQL. Is this really true?
Aside from that point, I see no reason why we shouldn't switch to UTF-8. It's my understanding that it is superior and becoming more ubiquitous.
Which of us is right?
need help with C# gataGrid selection
I new to progrming and need help with selecting dataGridView and checking first column. When click on "checkBox1"(select all) want to select all cell(rows) and to check all checkBox in dataGrid in columns "No", for now code just select rows without checking them.
PS. Sorry For My Bad English
input file looks somting like : 900006724 00000090000698511 SAVSKI IVАN SREMSKA 101 900007054 000000ZU900006931 SAVSKI JOVАNOVIĆ 29.NOVEMBRA 504 900009856 000000Ih900009856 NOVI IVАN 29.NOVEMBRA 403
and code is:
input file looks somting like :
900006724 00000090000698511 SAVSKI IVАN SREMSKA 101 900007054 000000ZU900006931 SAVSKI JOVАNOVIĆ 29.NOVEMBRA 504 900009856 000000Ih900009856 NOVI IVАN 29.NOVEMBRA 403
and code is:
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.IO;
namespace WindowsFormsApplication1 { public partial class Form1 : Form { public Form1() { InitializeComponent();
}
private void btnload_Click(object sender, EventArgs e)
{
OpenFileDialog of = new OpenFileDialog();
of.ShowDialog();
textBox1.Text = of.FileName;
dataGridView1.DataSource = Class1.LoadUserListFromFile(textBox1.Text);
}
private void checkBox1_CheckedChanged(object sender, EventArgs e)
{
dataGridView1.SelectAll();
checkBox2.Checked = false;
checkBox1.Checked = !checkBox2.Checked;
}
private void checkBox2_CheckedChanged(object sender, EventArgs e)
{
dataGridView1.ClearSelection();
checkBox1.Checked = false;
checkBox2.Checked=!checkBox1.Checked;
}
public class Class1
{
public bool No { get; set; }
public string Id { get; set; }
public string Sity { get; set; }
public string Surname { get; set; }
public string Name { get; set; }
public string Street { get; set; }
public string PostalNo { get; set; }
public string Sity1 { get; set; }
public string Date { get; set; }
public string CardDate { get; set; }
public string PU { get; set; }
public string Password { get; set; }
public string IdentificationNo { get; set; }
public static List<Class1> LoadUserListFromFile(string path)
{
var users = new List<Class1>();
foreach (var line in File.ReadAllLines(path))
{
var columns = line.Split(delimiters, StringSplitOptions.RemoveEmptyEntries);
users.Add(new Class1
{
No = false,
Id = line.Substring(22, 12).Trim(),
Sity = line.Substring(48, 20).Trim(),
Surname = line.Substring(81, 32).Trim(),
Name = line.Substring(113, 36).Trim(),
Street = line.Substring(177, 24).Trim(),
PostalNo = line.Substring(241, 9).Trim(),
Sity1 = line.Substring(263, 20).Trim(),
Date = line.Substring(343, 12).Trim(),
CardDate = line.Substring(570, 17).Trim(),
PU = line.Substring(614, 25).Trim(),
Password = line.Substring(694, 10).Trim(),
IdentificationNo = line.Substring(710, 13).Trim(),
});
}
return users;
}
public static string input { get; set; }
public static string[] delimiters { get; set; }
}
}
}
Leaving intentional bugs in code for testers to find
We don't do this at our firm, but one of my friends says that his project manager asked every dev to add intentional bugs just before the product goes to QA. This is how it works:
- Just before the product goes to QA, the dev team adds some intentional bugs at random places in the code. They properly back up the original, working code to make sure that those bugs aren't shipped with the end product.
- Testers are also informed about this. So they will test hard, because they know there are bugs present and that not finding them might be considered as a sign of incompetence.
- If a bug (intentional or otherwise) has been found, they will be reported for the dev team to fix. The dev team then adds another intentional bug in a related section of the code just before product goes to 2nd level QA. The project manager says a tester should think like a developer and he/she should expect new bugs in sections where changes were made.
Well, this is how it goes. They say that this approach has following advantages
- Testers will be always on their toes and they will test like crazy. That helps them to also find hidden (unintentional) bugs so developers can fix them.
- Testers feed on bugs. Not finding any bugs will affect their morale. So giving them an easy one to find will help their morale.
If you ignore the scenario were one of these intentional bugs gets shipped with the final product, what are the other drawbacks we should consider before even thinking of adopting this approach?
EDIT :
It has been 2 days and there are lot of answers. But I want to make something clear.
1) They properly backup the original code (Yes, they use source control, backup was a general term)
2) When tester find out an intentional bug, dev team just ignore. If tester finds out a unintentional (original) bug, dev team first check whether it is caused by any of the intentional bug. That is, dev team first try to reproduce that on original working code, and fix it if they can.
3) Just ignore the relationship issues between QA - Dev team. I specifically asked this question on programmers not on workplace. Consider that there is good rapport between QA and Dev team and they party together after working hours. Project manager is a nice, old gentleman who is always ready to support both teams(Godsend).
Java logging dependency for a low-level library
I inherited a lower-level open source Java network library. The library is intended to be used by higher-level application protocol libraries which are in turn used by application code. My library, as left by the previous maintainer, has no dependencies and is built via Ant. The build artifact is a simple jar that others can drop into their projects.
I am in the process of converting the library to be built with Maven. As I'm doing this, I'm considering possibly adding slf4j as a dependency. Currently, when something goes wrong, stack traces or other information is spit out to System.out or System.err. I know that that's not always very helpful, but these outputs only happen at 10 to 15 places in the code and are rarely executed.
So what do you think? Keep the library simple with zero dependencies or introduce slf4j?
Making a sequence strictly increasing by joining neighboring numbers using the smallest number of moves
I've got a following problem to solve:
You are given a list of positive integers [x_1;x_2;...;x_n]. You are allowed to
change 2 integers standing next to each other to one equal to their sum. (So for
example in list [x_1;...;x_3;x_4;x_5;x_6;...;x_n] you pick x_4 and x_5 and the new list
becomes [x_1;...;x_3;(x_4+x_5);x_6;...;x_n]). Find the minimum number of such changes
needed to get a list in which integers are in strictly increasing order.
How to approach such a problem? Intuitively it looks like Dynamic Programming problem (something like multiplying matrices) but I cannot find any connected subproblems. Any idea how to solve this using something else than brute-force?
Use JSON objects or POJOs in back end service?
I'm building a back end service for mobile clients.
The requirement is that the mobile clients will pass me a token, I'll use that token to talk to other systems (behind the company firewall) in my company, and return to the user some information.
Here's a typical scenario:
A mobile client asks for some customer data and makes a call with the customers token. I use the token against the customer database system and get back the customer details. I then return the data (removing some fields that are not relevent )to the mobile client.
All data between systems (me, mobile client, customer database) use JSon.
The question is whether I should work with JSon objects throught my code or try and use POJOs?
Right now, I only need to remove some fields from the customer database before returning to the client.
The future may require more involved transformations but I can't be sure that will happen or the nature of the transformations.
Thanks
How to identify http requests made from a closed-source java app?
I am an avid Go player and play on the Kiseido Go Server.
I would like to write an open source client for this, but the KGS protocol is a well-kept secret. Is there any way to catch the http requests made by the *.jar
file to the Go server?
I know this is possible because at least one other client app (CGoban) exists.
Working remotely: choosing a technology
Is this true that C++ programming is not the best option to find a remote job? If so, which technologies would you recommend for studying to accoplish this (java? ruby?) given now I'm specializing in C++/OOP ?
Determining Use Cases Correctly
I have a project this semester to basically do everything but code a complete system; which obviously involves finding and creating use cases, and I'm having trouble figuring out a few things...
Can the system be referred to as an actor? Or involved some other way? (In the case of CRON jobs for example)
Can automated processes be considered use cases if they don't involve any human/entity?
How "deep" should I go? Such as "Add Information", "Change Information", "Delete Information" Instead of "Add/Update Information".
Am I on the right path? I have a feeling I'm doing this completely wrong.
Here's the revised use cases I just wrote, I'd be very grateful if anyone could give me some feedback...
EDIT: Pastebin for anyone not comfortable with that link http://ift.tt/16389KF
Open source editor [on hold]
I want a simple, highlighted source code editor for iOS, Mac and PC. What's my best bet? Can you recommend some portable open source editor?
Or is it easier to just build it from scratch on all three platforms? I read somewhere that iOS 7+ comes with built-in support for different colors in the editor? What about wx? Qt? Some other framework?
I'd love to hear from someone who did this already!
C++ Error:expected primary expression during building
include
float SimpleInterest(float x,float y,float z); int main() { using namespace std; cout<<"Enter a principal amount"<>x; cout<<"Enter the rate"<>y; cout<<"Enter the time period"<>z; return 0; cout<<"The Simple Interest is:"<< float SimpleInterest(float x,float y,float z)<
} float SimpleInterest(float x,float y,float z) { return xyz/100; }
When rebuilding an package from an updated repository, is there a way to skip compilation on files that haven't changed?
I know this is a bit of a shot in the dark, but when I update a repository (c, c++, and so forth) and know that only a few files have changed, it's aggrivating to have to have everything recompile on larger projects. Is there a way to skip these? For example, is there a checksum that can be done against the built object and source that will be checked upon a rebuild?
When passing dates/datetimes as url parameters in an API, which format is better - unix timestamp or date string (ISO 8601)
Interesting question came up in regards to the pros/cons of passing a date/datetime as a url parameter in an API. Is it better to pass as a unix timestamp, or as a plaintext date string (01/30/2015 04:17:57pm
, 2015-01-27T16:17:57+00:00
)?
Best Identifier for iOS device
I'm pretty new to iOS development, but I'm working on a small iPhone app for work. Every so often, the app will send an HTTP request to a server containing some information in JSON format. One of the things I would like that JSON packet to contain is an identifier so I know who sent the data to the server. I could create a login page for the app, but ideally I'd like to keep the data as anonymous as possible. I was thinking it might be better to store the device serial number (is that a thing) or MAC address or something unique about the phone as the JSON id, without resorting to someone's actual name. So, my question would be... what is the best unique identifier that I should use to keep the data psuedo anonymous. Also, I'm using Swift, so any places to look for code snippets to help me get started would be greatly appreciated. Thanks.
Is this the template method pattern?
Could someone tell me whether the following is A) a good solution to the problem of repeating code and B) an example of the template method?
Let's say I have one table, named VEHICLES, which I use to store different types of vehicles (e.g. car, van, bus). I have a bunch of repository classes which should retrieve each type of vehicle:
class CarRepository{
public function getAll(){
$sql = "select * from vehicles where type='car'";
//some code to communicate with the database
}
}
class BusRepository{
public function getAll(){
$sql = "select * from vehicles where type='bus'";
//some code to communicate with the database
}
}
As you can see, each repo has almost the same code in the getAll method, which isn't very DRY. I was thinking a better solution might be to have a common base class for the repos, like this:
abstract class VehicleRepository{
final public function getAll(){
$sql = "select * from vehicles where type='".$this->getType()."'";
echo $sql;
//code to communicate with the database
}
abstract function getType();
}
And then each repo would just need to define the getType method:
class CarRepository extends VehicleRepository{
public function getType(){
return "car";
}
}
class BusRepository extends VehicleRepository{
public function getType(){
return "bus";
}
}
Does this seem reasonable? And is this what is meant by the template method pattern?
Why are FLOSS licences applied to files instead of diffs/deltas?
In the case of open source software development, where contributions build on previous work I would find it more sensible for each copyright holder to hold copyrights on the diffs/deltas he/she contributed, instead of copyrights on files. Unless a contributor created a file, the contribution is a modification.
AFAIK, in projects with no CLAs, like the Linux kernel, copyright for contributions from different sources is still handled on a per file basis.
Implementing this concept means licensing would have to be integrated into Git/Mercurial/Bazar/Fossil/SVN, and at first it would be more complicated than adding a commented header with the license to each file.
What are the reasons (legal, technical, political, customary or otherwise) software licenses are applied to files instead of to diffs, especially now that version control systems are in wide spread use? Or is this a novel idea?
Note 1: Obviously the question does not apply in cases where there are Contributors Licence Agreements, and does not apply to non-FLOS Software.
Note 2: I mistakenly asked this on Stackoverflow and since instead of being moved here it was closed, I am asking this question here.
Is it ok for a for a View to dismiss itself?
Currently, I'm working on a project in which a view is dismissing itself.
While talking to another programmer on the team for this project, he said that it's fine (in that it behaves correctly), but that I really should be using a delegate pattern to dismiss a view.
I've been programming in Objective-C for awhile now, but am still trying to fully understand design patterns, such as delegation. Is it acceptable for a view to dismiss itself, or should I in-fact be using delegation? When is delegation not an acceptable design pattern for use?
Thanks for your help! Apologies in advance if this question is a bit unclear.f
Should refactored functions go inside the calling function?
I like to divide my functions into small parts; it tends to make the code look cleaner. In most cases, the extracted parts are only used by the 'containing' function. For example in C#:
private void MyFunction()
{
// some code
FirstStep();
SecondStep();
ThirdStep();
// some code
}
private void FirstStep()
{
Console.WriteLine("I'm first.");
// some code
}
private void SecondStep()
{
Console.WriteLine("I'm second.");
// some code
}
private void ThirdStep()
{
Console.WriteLine("I'm third.");
// some code
}
JavaScript supports defining functions inside functions. So it would make sense to define FirstStep
, SecondStep
and ThirdStep
inside MyFunction
, like so:
function myFunction() {
// some code
firstStep();
secondStep();
thirdStep();
// some code
function firstStep() {
console.log("I'm first.");
// some code
}
function secondStep() {
console.log("I'm second.");
// some code
}
function thirdStep() {
console.log("I'm third.");
// some code
}
}
However when I do this, the resulting function seems huge. Visually it looks cleaner to extract the inner functions out of the calling function.
What is the best practice regarding this? Define inner functions inside the calling function or outside of it? Also, what is more common?
MVC: How dumb should the view be?
creating an MVC structure and pondering this...
My view has an Add button. Click it and we send off a request to the controller (using pub/sub so view doesn't really know who its talking to). Having done this the view disables its Add button until it receives a "data added" event from the controller (again pub/sub so doesn't really know who from). At this points it updates its list and re-enables the add button.
My question is this. Should the view contain this logic about enabling/disabling the add button or should the controller? My thoughts so far are perhaps the controller because it is up to the controller whether multiple adds can be handled at any one time or whether they need to be serialised in the method described. however, it is easier to implement the current scheme in the view as don't have to expose so many methods to control the view.
Is there a preferred way that is the most MVC compliant? Thanks :)
jeudi 29 janvier 2015
Mysql PHP PDO Blank PAge when tried to set @varible
I got this php class from the internet which deal with mysql database:
<?php
class SSP {
static function data_output($columns, $data, $isJoin = false) {
$out = array();
for ($i = 0, $ien = count($data); $i < $ien; $i++) {
$row = array();
for ($j = 0, $jen = count($columns); $j < $jen; $j++) {
$column = $columns[$j];
// Is there a formatter?
if (isset($column['formatter'])) {
$row[$column['dt']] = ($isJoin) ? $column['formatter']($data[$i][$column['field']], $data[$i]) : $column['formatter']($data[$i][$column['db']], $data[$i]);
} else {
$row[$column['dt']] = ($isJoin) ? $data[$i][$columns[$j]['field']] : $data[$i][$columns[$j]['db']];
}
}
$out[] = $row;
}
return $out;
}
static function limit($request, $columns) {
$limit = '';
if (isset($request['start']) && $request['length'] != -1) {
$limit = "LIMIT " . intval($request['start']) . ", " . intval($request['length']);
}
return $limit;
}
static function order($request, $columns, $isJoin = false) {
$order = '';
if (isset($request['order']) && count($request['order'])) {
$orderBy = array();
$dtColumns = SSP::pluck($columns, 'dt');
for ($i = 0, $ien = count($request['order']); $i < $ien; $i++) {
// Convert the column index into the column data property
$columnIdx = intval($request['order'][$i]['column']);
$requestColumn = $request['columns'][$columnIdx];
$columnIdx = array_search($requestColumn['data'], $dtColumns);
$column = $columns[$columnIdx];
if ($requestColumn['orderable'] == 'true') {
$dir = $request['order'][$i]['dir'] === 'asc' ?
'ASC' :
'DESC';
$orderBy[] = ($isJoin) ? $column['db'] . ' ' . $dir : '`' . $column['db'] . '` ' . $dir;
}
}
$order = 'ORDER BY ' . implode(', ', $orderBy);
}
return $order;
}
static function filter($request, $columns, &$bindings, $isJoin = false) {
$globalSearch = array();
$columnSearch = array();
$dtColumns = SSP::pluck($columns, 'dt');
if (isset($request['search']) && $request['search']['value'] != '') {
$str = $request['search']['value'];
for ($i = 0, $ien = count($request['columns']); $i < $ien; $i++) {
$requestColumn = $request['columns'][$i];
$columnIdx = array_search($requestColumn['data'], $dtColumns);
$column = $columns[$columnIdx];
if ($requestColumn['searchable'] == 'true') {
$binding = SSP::bind($bindings, '%' . $str . '%', PDO::PARAM_STR);
$globalSearch[] = ($isJoin) ? $column['db'] . " LIKE " . $binding : "`" . $column['db'] . "` LIKE " . $binding;
}
}
}
// Individual column filtering
for ($i = 0, $ien = count($request['columns']); $i < $ien; $i++) {
$requestColumn = $request['columns'][$i];
$columnIdx = array_search($requestColumn['data'], $dtColumns);
$column = $columns[$columnIdx];
$str = $requestColumn['search']['value'];
if ($requestColumn['searchable'] == 'true' &&
$str != '') {
$binding = SSP::bind($bindings, '%' . $str . '%', PDO::PARAM_STR);
$columnSearch[] = ($isJoin) ? $column['db'] . " LIKE " . $binding : "`" . $column['db'] . "` LIKE " . $binding;
}
}
// Combine the filters into a single string
$where = '';
if (count($globalSearch)) {
$where = '(' . implode(' OR ', $globalSearch) . ')';
}
if (count($columnSearch)) {
$where = $where === '' ?
implode(' AND ', $columnSearch) :
$where . ' AND ' . implode(' AND ', $columnSearch);
}
if ($where !== '') {
$where = 'WHERE ' . $where;
}
return $where;
}
static function simple($request, $sql_details, $table, $primaryKey, $columns, $joinQuery = NULL, $extraWhere = '', $groupBy = '', $varDeclare = '') {
$bindings = array();
$db = SSP::sql_connect($sql_details);
// Build the SQL query string from the request
$limit = SSP::limit($request, $columns);
$order = SSP::order($request, $columns, $joinQuery);
$where = SSP::filter($request, $columns, $bindings, $joinQuery);
// IF Extra where set then set and prepare query
if ($extraWhere) {
$extraWhere = ($where) ? ' AND ' . $extraWhere : ' WHERE ' . $extraWhere;
}
// Main query to actually get the data
if ($joinQuery) {
$col = SSP::pluck($columns, 'db', $joinQuery);
$query = "$varDeclare " .
"SELECT SQL_CALC_FOUND_ROWS " . implode(", ", $col) . "
$joinQuery
$where
$extraWhere
$groupBy
$order
$limit";
} else {
$query = "SELECT SQL_CALC_FOUND_ROWS `" . implode(", ", SSP::pluck($columns, 'db')) . "`
FROM `$table`
$where
$extraWhere
$groupBy
$order
$limit";
}
$data = SSP::sql_exec($db, $bindings, $query);
// Data set length after filtering
$resFilterLength = SSP::sql_exec($db, "SELECT FOUND_ROWS()"
);
$recordsFiltered = $resFilterLength[0][0];
// Total data set length
$resTotalLength = SSP::sql_exec($db, "SELECT COUNT(`{$primaryKey}`)
FROM `$table`"
);
$recordsTotal = $resTotalLength[0][0];
/*
* Output
*/
return array(
"draw" => intval($request['draw']),
"recordsTotal" => intval($recordsTotal),
"recordsFiltered" => intval($recordsFiltered),
"data" => SSP::data_output($columns, $data, $joinQuery)
);
}
static function sql_connect($sql_details) {
try {
$db = @new PDO(
"mysql:host={$sql_details['host']};dbname={$sql_details['db']}", $sql_details['user'], $sql_details['pass'], array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION)
);
$db->query("SET NAMES 'utf8'");
} catch (PDOException $e) {
SSP::fatal(
"An error occurred while connecting to the database. " .
"The error reported by the server was: " . $e->getMessage()
);
}
return $db;
}
static function sql_exec($db, $bindings, $sql = null) {
// Argument shifting
if ($sql === null) {
$sql = $bindings;
}
$stmt = $db->prepare($sql);
//echo $sql;
// Bind parameters
if (is_array($bindings)) {
for ($i = 0, $ien = count($bindings); $i < $ien; $i++) {
$binding = $bindings[$i];
$stmt->bindValue($binding['key'], $binding['val'], $binding['type']);
}
}
// Execute
try {
$stmt->execute();
} catch (PDOException $e) {
SSP::fatal("An SQL error occurred: " . $e->getMessage());
}
// Return all
return $stmt->fetchAll();
}
static function fatal($msg) {
echo json_encode(array(
"error" => $msg
));
exit(0);
}
static function bind(&$a, $val, $type) {
$key = ':binding_' . count($a);
$a[] = array(
'key' => $key,
'val' => $val,
'type' => $type
);
return $key;
}
static function pluck($a, $prop, $isJoin = false) {
$out = array();
for ($i = 0, $len = count($a); $i < $len; $i++) {
$out[] = ($isJoin && isset($a[$i]['as'])) ? $a[$i][$prop] . ' AS ' . $a[$i]['as'] : $a[$i][$prop];
}
return $out;
}
}
Mysql query original format which I haved tested on phpmyadmin without any problem:
SET @gender = NULL;
SET @agefrom = NULL;
SET @ageto = NULL;
SET @mobile = NULL;
SET @country = NULL;
SET @state = NULL;
SET @email = TRUE;
SELECT B.BUYER_ID AS ID,
B.BUYER_NAME AS NAME,
(SELECT GR.GENDER FROM MOB_GENDER_REF GR WHERE B.BUYER_GENDER = GR.GENDER_ID) AS GENDER,
(TRUNCATE(DATEDIFF(CURDATE(), B.BUYER_DOB)/365.25,0)) AS AGE,
B.BUYER_MOBILE_NO AS MOBILE_NO,
(SELECT CR.COUNTRY_NAME FROM MOB_COUNTRY_REF AS CR WHERE CR.COUNTRY_ID = B.COUNTRY ) AS COUNTRY,
(SELECT CSR.STATE_NAME FROM MOB_COUNTRY_STATE_REF AS CSR WHERE CSR.STATE_ID = B.STATE AND CSR.COUNTRY_ID = B.COUNTRY) AS STATE,
B.BUYER_EMAIL AS EMAIL
FROM MOB_BUYER B
WHERE (
IF((@gender IS NULL) || (@gender = "") || (@gender < 0 && @gender > B.BUYER_GENDER), (B.BUYER_GENDER LIKE '%'), (B.BUYER_GENDER = @gender))
AND
IF((@agefrom IS NULL) || (@agefrom = "") || (@agefrom < 0 && @agefrom > (TRUNCATE(DATEDIFF(CURDATE(), B.BUYER_DOB)/365.25,0))), (TRUNCATE(DATEDIFF(CURDATE(), B.BUYER_DOB)/365.25,0)) LIKE '%', (TRUNCATE(DATEDIFF(CURDATE(), B.BUYER_DOB)/365.25,0)) >= @agefrom)
AND
IF((@ageto IS NULL) || (@ageto = "") || (@ageto < 0 && @ageto > (TRUNCATE(DATEDIFF(CURDATE(), B.BUYER_DOB)/365.25,0))), (TRUNCATE(DATEDIFF(CURDATE(), B.BUYER_DOB)/365.25,0)) LIKE '%', (TRUNCATE(DATEDIFF(CURDATE(), B.BUYER_DOB)/365.25,0)) <= @ageto)
AND
IF((@mobile IS NULL) || (@mobile = "") && (@mobile != TRUE && @mobile != FALSE), (B.BUYER_MOBILE_NO LIKE '%'), IF(@mobile = TRUE, (CHAR_LENGTH(B.BUYER_MOBILE_NO) >= @mobile && CAST(B.BUYER_MOBILE_NO AS UNSIGNED) > 0), (B.BUYER_MOBILE_NO = 0)))
AND
IF((@country IS NULL) || (@country = ""), (B.COUNTRY LIKE '%'), FIND_IN_SET(B.COUNTRY, @country))
AND
IF((@state IS NULL ) || (@state = ""), (B.STATE LIKE '%'), FIND_IN_SET(B.STATE, @state))
AND
IF((@email IS NULL) || (@email = "") && (@email != TRUE && @email != FALSE), (B.BUYER_EMAIL LIKE '%'), IF(@email = TRUE, (CHAR_LENGTH(B.BUYER_EMAIL) >= @email), (B.BUYER_EMAIL = "" OR B.BUYER_EMAIL IS NULL)))
)
and this is the php source code which I used to execute the sql query:
<?php
$table = 'MOB_BUYER';
$primaryKey = 'BUYER_ID';
$columns = array(
array('db' => '`B`.`BUYER_ID`', 'dt' => 'BUYER_ID', 'field' => 'ID', 'as' => 'ID'),
array('db' => '`B`.`BUYER_NAME`', 'dt' => 'BUYER_NAME', 'field' => 'NAME', 'as' => 'NAME'),
array('db' => '(SELECT `GR`.`GENDER` FROM `MOB_GENDER_REF` AS `GR` WHERE `B`.`BUYER_GENDER` = `GR`.`GENDER_ID`)', 'dt' => 'GENDER', 'field' => 'GENDER', 'as' => 'GENDER'),
array('db' => '(TRUNCATE(DATEDIFF(CURDATE(), `B`.`BUYER_DOB`)/365.25,0))', 'dt' => 'AGE', 'field' => 'AGE', 'as' => 'AGE'),
array('db' => '`B`.`BUYER_MOBILE_NO`', 'dt' => 'MOBILE_NO', 'field' => 'MOBILE_NO', 'as' => 'MOBILE_NO'),
array('db' => '(SELECT `CR`.`COUNTRY_NAME` FROM `MOB_COUNTRY_REF` AS `CR` WHERE `CR`.`COUNTRY_ID` = `B`.`COUNTRY`)', 'dt' => 'COUNTRY', 'field' => 'COUNTRY', 'as' => 'COUNTRY'),
array('db' => '(SELECT `CSR`.`STATE_NAME` FROM `MOB_COUNTRY_STATE_REF` AS `CSR` WHERE `CSR`.`STATE_ID` = `B`.`STATE` AND `CSR`.`COUNTRY_ID` = `B`.`COUNTRY`)', 'dt' => 'STATE', 'field' => 'STATE', 'as' => 'STATE'),
array('db' => '`B`.`BUYER_EMAIL`', 'dt' => 'EMAIL', 'field' => 'EMAIL', 'as' => 'EMAIL')
);
// SQL server connection information
$sql_details = array(
'user' => 'user',
'pass' => 'password',
'db' => 'test',
'host' => '127.0.0.1'
);
require('ssp.class.php' );
$joinQuery = "FROM `MOB_BUYER` AS `B`";
$extraWhere = "("
. "IF((@gender IS NULL) || (@gender = '') || (@gender < 0 && @gender > `B`.`BUYER_GENDER`), (`B`.`BUYER_GENDER` LIKE '%'), (`B`.`BUYER_GENDER` = @gender)) "
. "AND "
. "IF((@agefrom IS NULL) || (@agefrom = '') || (@agefrom < 0 && @agefrom > (TRUNCATE(DATEDIFF(CURDATE(), `B`.`BUYER_DOB`)/365.25,0))), (TRUNCATE(DATEDIFF(CURDATE(), `B`.`BUYER_DOB`)/365.25,0)) LIKE '%', (TRUNCATE(DATEDIFF(CURDATE(), `B`.`BUYER_DOB`)/365.25,0)) >= @agefrom) "
. "AND "
. "IF((@ageto IS NULL) || (@ageto = '') || (@ageto < 0 && @ageto > (TRUNCATE(DATEDIFF(CURDATE(), `B`.`BUYER_DOB`)/365.25,0))), (TRUNCATE(DATEDIFF(CURDATE(), `B`.`BUYER_DOB`)/365.25,0)) LIKE '%', (TRUNCATE(DATEDIFF(CURDATE(), `B`.`BUYER_DOB`)/365.25,0)) <= @ageto) "
. "AND "
. "IF((@mobile IS NULL) || (@mobile = '') && (@mobile != TRUE && @mobile != FALSE), (`B`.`BUYER_MOBILE_NO` LIKE '%'), IF(@mobile = TRUE, (CHAR_LENGTH(`B`.`BUYER_MOBILE_NO`) >= @mobile && CAST(`B`.`BUYER_MOBILE_NO` AS UNSIGNED) > 0), (`B`.`BUYER_MOBILE_NO` = 0))) "
. "AND "
. "IF((@country IS NULL) || (@country = ''), (`B`.`COUNTRY` LIKE '%'), FIND_IN_SET(`B`.`COUNTRY`, @country)) "
. "AND "
. "IF((@state IS NULL ) || (@state = ''), (`B`.`STATE` LIKE '%'), FIND_IN_SET(`B`.`STATE`, @state)) "
. "AND "
. "IF((@email IS NULL) || (@email = '') && (@email != TRUE && @email != FALSE), (`B`.`BUYER_EMAIL` LIKE '%'), IF(@email = TRUE, (CHAR_LENGTH(`B`.`BUYER_EMAIL`) >= @email), (`B`.`BUYER_EMAIL` = '' OR `B`.`BUYER_EMAIL` IS NULL)))"
. ")";
$groupBy = "";
$varDeclare = "SET @gender = NULL; "
. "SET @agefrom = NULL; "
. "SET @ageto = NULL; "
. "SET @mobile = NULL; "
. "SET @country = NULL; "
. "SET @state = NULL; "
. "SET @email = NULL;";
echo json_encode (
SSP::simple($_GET, $sql_details, $table, $primaryKey, $columns, $joinQuery, $extraWhere, $groupBy, $varDeclare)
);
?>
When I execute the php source it return blank page....
anyone mind lend a helping hand?
Thanks
:)