Qt - creating a complex "calculator" - c++

I am building an application that requires a graphical interface for a calculation process.
The calculation is basically a formula written by the user to be evaluated with QScriptEngine - ie, Javascript.
The thing is I'm having trouble breaking down the problem into smaller steps. The general objectives are as follows:
The values that are to be used in a formula report to properties of items. The items are already created and have a list of properties with which I populate a QTableWidget.
By dragging/droping from the table to a QTextEdit, I'm creating a string with some rich-formating to help the users read the formula more intuitively. Basically, each item on the table has a certain color, so in the QTextEdit, when an item is dropped, it gets a background-color formatting with the same color, and displays the property's name; something like: <span style='background-color:red;'> propertyName </span>
The drag/drop interface as well as the formating is coded and working as expected. But now I have a few problems:
some items have properties with the same name. If I create the formula with two different properties (from different items) that have the same name, I can't track the property's value backwards without ambiguity - I was thinking of string compare/string replace the property's name with its value and then calculate with evaluate().
I have been breaking my head on how to get around this and I thought of creating a QMultiMap to hold the item: [property, value] relationships, and then, replacing on the string that will be evaluated. But again, I would need to check form which item the property came from, and I don't know how I can do that.
I'm new to Qt/C++ and I know that most of my code has some big faulty practices, and its being done more in the way of hacking my way through the objectives I require, more than building a good structure - so every new problem gets a more complex solution each time.
Even so, how would you suggest I should tackle this problem? By this time I think it is better to not post my code just yet, because it is too long (and probably painful) to look at. If someone requires a specific portion to better understand the context of the problem, let me know and I'll post here.
Also, I have had other question here in SO when I started to think about this - might be useful to check for context: here.
UPDATE:
In reply to #Riateche's comment:
Imagine this scenario:
Item A : [property1, value1]
[property2, value2]
Item B : [property1, value3]
[property2, value4]
Now, imagine the user wants to perform ItemA.property1 * ItemB.property1:
I want him to see property1 * property1 - but notice that the background-color of each should be different;
I could place in the QTextEdit something like: <span style='background-color:red;'> property1 </span> * <span style='background-color:blue;'> property1 </span>
what I actually want to evaluate (to calculate) is: value1 * value3 - in which these represent double types.
UPDATE 2
After thinking a little bit about this, while #Riateche's approach seems simple, I wasn't able to find a way change a tag's attribute (at least in rich text, maybe there is one with QWebkit, but that is not what I need). So I was thinking if building another string (that will be evaluated), at the same time the user builds a string with drag and drop. For instance, let's imagine the user drags and drops something like:
property1 * property1
At the same time I would build other string that contained
value1 * value3
And this would be the evaluated string. Even so, the problem with the user editing the string would still be there - if the user changes the drag/drop string, I need to update the evaluation string again -requiring me to once again check the origin of the data. Any other ideas?

You should put all information important for the formula evaluation to the text edit. You can make it invisible to user. For example, you can put the following to the text edit:
<span style='background-color:red;'><a name='Item A,property1'></a>property1</span>
The Item A,property1 text will be invisible to user, but textEdit->toHtml() result will contain it.

Related

How can I dynamically create multi-level hierarchical forms in Django?

I'm building an advanced search page for a scientific database using Django. The goal is to be able to allow some dynamically created sophisticated searches, joining groups of search terms with and & or.
I got part-way there by following this example, which allows multiple terms anded together. It's basically a single group of search terms, dynamically created, that I can either and-together or or-together. E.g.
<field1|field2> <is|is not|contains|doesn't contain> <search term> <->
<+>
...where <-> will remove a search term row and <+> will add a new row.
But I would like the user to be able to either add another search term row, or add an and-group and an or-group, so that I'd have something like:
<and-group|or-group> <->
<field1|field2> <is|is not|contains|doesn't contain> <search term> <->
<+term|+and-group|_or-group>
A user could then add terms or groups. The result search might end up like:
and-group
compound is lysine
or-group
tissue is brain
tissue is spleen
feeding status is not fasted
Thus the resulting filter would be like the following.
Data.objects.filter(Q(compound="lysine") & (Q(tissue=brain) | Q(tissue="spleen")) & ~Q(feeding_status="fasted"))
Note - I'm not necessarily asking how to get the filter expression below correct - it's just the dynamic hierarchical construction component that I'm trying to figure out. Please excuse me if I got the Q and/or filter syntax wrong. I've made these queries before, but I'm still new to Django, so getting it right off the top of my head here is pretty much guaranteed to be zero-chance. I also skipped the model relationships I spanned here, so let's assume these are all fields in the same model, for simplicity.
I'm not sure how I would dynamically add parentheses to the filter expression, but my current code could easily join individual Q expressions with and or or.
I'm also not sure how I could dynamically create a hierarchal form to create the sub-groups. I'm guessing any such solution would have to be a hack and that there are not established mechanisms for doing something like this...
Here's a screenshot example of what I've currently got working:
UPDATE:
I got really far following this example I found. I forked that fiddle and got this proof of concept working before incorporating it into my Django project:
http://jsfiddle.net/hepcat72/d42k38j1/18/
The console spits out exactly the object I want. And there are no errors. Clicking the search button works for form validation. Any fields I leave empty causes a prompt to fill in the field. Here's a demo gif:
Now I need to process the POST input to construct the query (which I think I can handle) and restore the form above the results - which I'm not quite sure how to accomplish - perhaps a recursive function in a custom tag?
Although, is there a way to snapshot the form and restore it when the results load below it? Or maybe have the results load in a different frame?
I don't know if I'm teaching a grandmother to suck eggs, but in case not, one of the features of the Python language may be useful.
foo( bar = 27, baz = None)
can instead be coded
args = {}
a1, a2 = 'bar', 'baz'
d[a1] = 27
d[a2] = None
foo( **args )
so an arbitrary Q object specified by runtime keys and values can be constructed q1 = Q(**args)
IIRC q1 & q2 and q1 | q2 are themselves Q objects so you can build up a filter of arbitrary complexity.
I'll also include a mention of Django-filter which is usually my answer to filtering questions like this one, but I suspect in this case you are after greater power than it easily provides. Basically, it will "and" together a list of filter conditions specified by the user. The built-in ones are simple .filter( key=value), but by adding code you can create custom filters with complex Q expressions related to a user-supplied value.
As for the forms, a Django form is a linear construct, and a formset is a list of similar forms. I think I might resort to JavaScript to build some sort of tree representing a complex query in the browser, and have the submit button encode it as JSON and return it through a single text field (or just pick it out of request.POST without using a form). There may be some Javascript out there already written to do this, but I'm not aware of it. You'd need to be sure that malicious submission of field names and values you weren't expecting doesn't result in security issues. For a pure filtering operation, this basically amounts to being sure that the user is entitled to get all data in database table in any case.
There's a form JSONField in the Django PostgreSQL extensions, which validates that user-supplied (or Javascript-generated) text is indeed JSON, and supplies it to you as Python dicts and lists.

Keep a row together but break if necessary

I´m working on a project using XSL-FO to generate some PDF Files.
There are several tables with rating comparisons.
Some columns have short text and some have very long text.
Without the attribute keep-together.within-page or with keep-together.within-page='auto' the tables look very ugly because the columns break the text at the end of a page - no matter what.
So i decided to use keep-together.within-page='always' to achive a better look. If a row doesnt fit on a page, fop moves the row to a new page. beautiful.
Now the problem.
In some cases some texts are very long and the content is larger than one page. In this case i want the row to break onto 2 pages.
I was looking for something like keep-together.within-page='always if possible'
is it possible to achive this some how?
You are searching for:
keep-together.within-page='<number(1-9)>'
If you type in 'always' fop tries to fit it with any necessary method into one page. If you specify a number it is more like "I will try what I can, but if the text is to long, it will break anyways". The number you fill in, is more like a priority, in case you have many nested keep-togethers. That means that the value 1 will also do its job.

Predicting the placeholder for a dynamic placeholder

I am using the Dynamic Placeholders from Fortis, but need to setup a page template where the Dynamic Placeholders contains renderings. I am setting the page template up, by setting layout detail on the standard values of the page template.
I have been unable to succeed in this, since the dynamic placeholder is postfixed by a GUID which is generated. Is there a way to predict this GUID? According to the documentation, the GUID is generated using the following logic:
Dynamic Placeholders simply use the rendering ID to create a unique placeholder name. If more than one dynamic placeholder with the same name is in a rendering it will also append on an incrementing number
I tried another approach, by using a home brewed dynamic placeholder library, which just prepended the dynamic placeholder with a sequential number, e.g. row1, row2, row3. But this approach makes the content editors unable to move rows in the experience editor, since the content inside the row is tied to a fixed number, which changes when the rows are moved.
As this question have been answered on sitecore.stackexchange.com, I want to bring the answer here as well. Big credit to Richard Seal and Thomas D.
Thomas D:
You can try to open the standard values item with the Experience Editor and add the renderings you like.
Richard Seal:
This is an alternative to the method mentioned by Thomas D.
The Fortis solution uses the UID for the rendering attached to the placeholder key that you enter. You can get this by changing to Raw Values view and copying the xml out of the renderings or final renderings field.
Find the rendering that contains your placeholder. There will be an xml element like this:
<r id="{CA76EB6F-2934-4B8A-BB6A-508A8E44A7C5}"
ph="body"
uid="{0FD41EBD-43CF-4647-8A0F-F1F1D2E00CCD}" />
There may be other fields too. The 2 that are important are id, which is the item id of your rendering item and uid, this is the unique rendering id that is added to your placeholder key.
The key is built like this: string.Format("{0}_{1}", placeholderName, renderingId);
So if you have a placeholder key called title, the key for the above xml snippet would be: title_{0FD41EBD-43CF-4647-8A0F-F1F1D2E00CCD}

How to determine if a given word or phrase from a list is within an anchor tag?

We have a ColdFusion based site that involves a large number of 'document authors' that have little or no knowledge of HTML. The 'documents' they create are comprised of HTML stored in a table in the database. They use a CKEDITOR interface. The content that they create is output into specific area of the page. The document frequently has tons of technical terms that readers may not be familiar with that we would like to have tooltips automatically show up for.
I and the other programmer want to have some code insert 'tooltip' code into the page based on a list of words in a table on our SQL server. The 'dictionary' table in our database has a unique ID, the word/phrase we will look for and a corresponding definition that would be displayed in the tooltip.
For instance, one of the word/phrases we will be looking for is 'Scrum Master'. If it occurs in the document area, we need to insert code around the words to create a tooltip. To do that, we need to see if certain conditions exist. Are the words within an anchor tag? If yes, is there already a title value for the tag (title is used to contain the info to be displayed in a tooltip)? If a title tag exists, don't do anything. If the words are not in an anchor tag, then we would put anchor tags around the words along with the title that will contain the definition.
The tooltip code we use is via jQuery (http://jqueryui.com/tooltip/). It is quick and simple to use. We just need to figure out how to use it dynamically based on our dictionary table.
Do you have any suggestions of how to go about this?
I was hoping that jSoup might have a function that I could use, but that doesn't seem to be the right technology for what I want to do, but I could be wrong and I am happy to be corrected!
We have a large number of these documents and so manually inserting and maintaining the tooltip code is just not an option.
Update you content with something like:
strOut = ReplaceList(strIn, ValueList(qryTT.find), ValueList(qryTT.replace));
Since words are delimited by spaces, the qryTT.find needs to have spaces. The replace column is going to need to include some of the original content. You are going to have to be careful with words followed by a comma or a period too.
I would cache the results because I would expect it to be memory intensive.

Oracle ApexCreate Time field HH:MM

I am having difficulty with a duration field on my form/table.
The users need to indicate in HH:MM how long a meeting took.
What datatype should the column have in the Table. Currently it is TIMESTAMP
How can I make the field have an input mask of 'HH:MM'. What I would like is for the user to be able to type '0130' and the field format it to '01:30' immediately.
Reporting on these times is required so I assume that entering the data as VARCHAR will not help.
Honestly, this is not such an easy subject as people might think it is, and probably more from a user interface point of view than technically.
The easiest way out? The apex datetimepicker. And honestly, if you're new to the technology I'd advise you to use this, especially if you want to steer clear from javascript/jquery initially.
Let's put it this way: the datepicker is fine and works good, but time is really not that fantastic.
Not all that hot right. The value in the input item does not change until you hit 'Close'. The time component seems like a last second sloppy addition honestly. It works, however. (But I'd still set the field to readonly so that a user can not enter text directly.)
Allowing text to be entered means it needs to be validated according to the correct format mask. And format masks differ between those in jQuery (the datepicker) and those in Oracle, and it might be possible that your oracle format mask is not possible in the datepicker, adding even more complexity. There is also no 'live' date validation (nor datetime), there is only the builtin item validation which will check the format mask and which fires on submit.
Anyway, I'd say take a look at it. Set your item to be displayed as a Date Picker, and use the format mask under settings to get the datetime picker:
Now you can push it further of course, though it'll cost some effort. There are several options though.
Personally, when I've implemented date+time I've always split the date from the time in 2 fields. 1 with the date component, and one with the time component, while keeping the item with the original value hidden (so 3 items total). I then use the datepicker on the date item, and use jquery timepicker plugins on the time item. On submit I then add the 2 values together and parse them in a date, and put this value in the original item again (to allow the standard processing to work on items with source set to database column).
One example of a timepicker is here, another one here. They're both not that hard to implement. They have good documentation too. I don't want to dive in the implementation of it here though, I advise you take a look at it first and see how much it scares you. (I'd set up an apex demo but am a bit pressed for time at the moment).
For example, using Trent's (second link) plugin:
put the js file in the apex images directory. I made a folder "/custom" in my case
add the required js files to the page (assuming apex 4.2, put this in javascript file urls)
#IMAGE_PREFIX#libraries/jquery-ui/1.8.22/ui/jquery.ui.slider.js
#IMAGE_PREFIX#custom/jquery-ui-timepicker-addon.js
use onload code such as this to initialize a field
$("#P95_DEPARTURE_TIME").timepicker({hourGrid: 4,minuteGrid: 10});
It'll end up looking as this:
Any further interaction between pickers will need to be handled in javascript code if you want it live. Don't forget server validations.
As for items, my hidden date item has format mask DD-MON-YYYY HH24:MI. Format masks are important, because items are bind variables, and bind variables are varchar2. The value in the html form is also just that, text.
For example, this is on my displayed date item, with a similar setup for the time item:
Then in an after-submit computation I glue the values together again and put them in the m that'll save the value to the database:
:P95_DEPARTURE_DATE_DISP||' '||:P95_DEPARTURE_TIME
This is just a short guide on the setup though, but might be interesting once you're a bit more familiar with the product.
There are also 2 timepicker plugins on apex-plugin, but honestly I don't find them interesting at all when compared to these already existing fine jquery plugins.
Give it some thought and look at it.
If quarters are enough..
item: text field with autocomplete
SELECT ss|| ':' || dd ss_dd
FROM
(SELECT to_char(trunc(sysdate)+(level - 1)/ 24,'HH24')ss
FROM dual CONNECT BY level <= 24),
(SELECT lpad(mod(15 * level, 60), 2, '0') dd
FROM dual CONNECT BY level <= 4)
APEX 4.2: Just to shed some light for any future viewings; now there are loads of Apex plugins for the purpose of picking Date/Time or both returning variations of date time formats as you would required. For e.g. as in your case HH:MM or HH24:MI.
I have personally used TimePicker plugin from http://www.apex-plugin.com which I have no problem in recommending.