Is it possible to stack only some data series? - flot

I have a chart with 3 stacked lines. The area below each line is filled.
Now I want to add two further non-stacked lines.
Currently, I have
this.flotOptions.series.stack = true;
and use another y-axis (with the same range) for the two new lines.
However, they the all lines still are stacked.
Is it possible to specify which data series shall be stacked?

Of course you can. Since you provided no code for us to look at (not a good idea, in my view), I'm going to have to guess you are just using an array of data points for a series and passing an array of those series to $.plot. Flow actually allows for an array of series objects, of which only one property is the data, the other properties allow you to configure the plot for that series in any way you like.
For example, here's a jsFiddle that shows how it can be done. The relevant code is
$.plot("#chart", [
{ data: series1, lines: {fill: true}, label: "one" },
{ data: series2, lines: {fill: true}, label: "two" },
{ data: series3, lines: {fill: false}, label: "three" },
{ data: series4, lines: {fill: false}, label: "four" }
]);

Related

Format column as Zip Code when exporting from ag-grid

I am exporting to Excel using the Enterprise Ag-Grid built in solutions. Whenever I export a zipcode, any zipcode that begins with 0 loses that in the Excel file. I know that Excel supports a special Zip Code format, however, I keep striking out on my attempts.
{
headerName: 'ZIP',
type: 'zip code',
filter: 'number',
unSortIcon: true,
field: 'Zip',
filterParams: {
filterOptions: this.filterOption,
clearButton: true,
applyButton: true
},
minWidth: 120
}
That is how the column is currently defined within the columnDefs of the gridOptions.
Thank you in advance for any assistance or insight you may have.
Regards,
Youssef
You can format the required cells in your spreadsheet as "00000" which will show the required formatting. Format cells->Special->Zip Code.

formatting text output in terminals

I'm currently writing a command line tool for myself, that needs to print some information on the terminal. I'm a little annoyed of the whole formatting. Here is my example.
formatter = logging.Formatter(fmt = '%(message)s')
console_logger = logging.getLogger("console_logger")
console_logger.setLevel(logging.DEBUG)
console_logger_handler = logging.StreamHandler()
console_logger_handler.setFormatter(formatter)
console_logger.addHandler(console_logger_handler)
console_logger.propagate = False
here goes some further code and then I have the printing function
for element in open_orders:
console_logger.info("Type: {}, Rate: {}, amount: {}, state: {}, pair: {}/{}, creation: {}, id: {}".format(element.type,
element.rate,
element.amount,
element.state,
element.currency_pair.get_base_currency().upper(),
element.currency_pair.get_quote_currency().upper(),
creation_time,
element.order_id))
I rather would like to have this as a column where the output is aligned at the colon. after each element a line of underscores or minusses would be nice as well, this should respect terminal width. I know this can be hardcoded in some manner, but isn't there a better way? Some kind of templating engine that can handle multiline output?
EDIT:
So here is an example:
Type : buy
Rate : 1234
amount : 1
state : active
pair : usd/eur
creation : 2017.12.12
I know this can be printed line by line with format but I need to determine the length of the longest string on my own and I was wondering if there isn a framework or something more elegant doing this for me.
id : 123456
Use format, add with your data :
for element in open_orders:
console_logger.info("Type: {:25s}, Rate: {:25s}, amount: {:07.2f}, state: {:25s}, pair: {:25s}/{:25s}, creation: {:25s}, id: {:25s}".format(element.type,
element.rate,
element.amount,
element.state,
element.currency_pair.get_base_currency().upper(),
element.currency_pair.get_quote_currency().upper(),
creation_time,
element.order_id))
You can also visit this site : https://pyformat.info/
In addition, you could try to use Colorama.
You have to install it, tipically, from pypi.
It allows you to handle cursor positioning, so you can control in which position at the screen (terminal) you want to print data, using "coordinates". Also, you can apply colors to text, which could give you a cleaner and prettier look if you want to.
So what I finally found which helps a lot at least in case of lists and formatting of them is this
terminaltable

Data structure / data model for multi-language phrasebook

We want create a multi-language phrasebook / dictionary for a specific
area.
And now I'm thinking about the best data structure / data model for that.
Since it should be more phrasebook than dictionary we want to keep the data model / structure first simple. It should be only used for fast translation: i.e. user selects two languages, types a word and gets translation. The article and description parts are just for displaying, not for search.
There are some specific cases I'm thniking about:
One term can be expressed with several (1..n) words in any language
Any term can also be translated into several (1..m) words in another language
In some languages the word's articel could be important to know
For some words description could be important (e.g. for words from dialects etc.)
I'm not sure about one point: do I reinvent the wheel creating a data model by myself? But I couldn't find any solutions.
I've just created a json data model I'm not sure about if it good enough or not:
[
{
wordgroup-id: 1,
en: [
{word: 'car', plural: 'cars'},
{word: 'auto', plural: 'autos'},
{word: 'vehicle', plural: 'vehicles'},
],
de: [
{word: 'Auto', article: 'das', description: 'Some explanation eg. when to use this word', plural: 'Autos'},
{word: 'Fahrzeug', article: 'das', plural: 'Fahrzeuge'}
],
ru: [...],
...
},
{
wordgroup-id: 2,
...
},
...
]
I also thought about some "corner" cases #triplee wrote about. I thought to solve them with some kind of redundance. Only the word group id and the word within a language should be unique.
I would be very thankfull for any feedback to the first draft of the data model.

how should i store a price in mongoose?

I'm using mongoose schemas for node.js along with express-validator (which has node-validator santiziations and validators).
What's a good way to store price for an item?
I currently have
var ItemSchema = new Schema({
name : { type: String, required: true, trim: true }
, price : Number
});
Price is optional, so I have:
if ( req.body.price ) {
req.sanitize('price').toFloat();
req.assert('price', 'Enter a price (number only)').isFloat();
}
express-validator gives me isNumeric (allows 0 padding), isDecimal, and isInt...I'd rather just convert to decimal and strip all characters, so I'm always inserting 42.00 into db.
I want to allow them to enter $42.00, $42, 42, 42.00 and just store 42.00. How can I accomplish this? and still validate that I'm seeing something resembling a number, for example if they enter 'abc' I want to throw an error back to the form using req.assert.
Also, I suppose currency will eventually become an issue...
Update, I found this post which says to store price as integer in cents, so 4200
https://dba.stackexchange.com/questions/15729/storing-prices-in-sqlite-what-data-type-to-use
I just need a way to convert 4200 to $42.00 when I call item.price and also sanitize and convert the input into 4200.
This is what I ended up doing...
I stored price as cents in database, so it is 4999 for 49.99 as described here: https://dba.stackexchange.com/questions/15729/storing-prices-in-sqlite-what-data-type-to-use
the getPrice will convert it back to readable format, so I can use item.price in my views w/o modifying it.
the setPrice converts it to cents.
model:
var ItemSchema = new Schema({
name : { type: String, required: true, trim: true }
, price : {type: Number, get: getPrice, set: setPrice }
});
function getPrice(num){
return (num/100).toFixed(2);
}
function setPrice(num){
return num*100;
}
I opted to only allow digits and decimal in price field, without $.
So they can enter 49, 49.99, 49.00, but not 49.0 or $49
validation using regex:
if ( req.body.price ) {
req.assert('price', 'Enter a price (numbers only)').regex(/^\d+(\.\d{2})?$/);
}
I wish there was a way to allow the $ because I think its a usability issue, just let the user enter it, but strip it off. I'm not sure how to do that and still validate that we have a price and not a bunch of letters for example.
Hint: The method described here is basically just another implementation of chovy's answer.
Workaround for Mongoose 3 & 4:
If you have trouble to define getters and setters directly in the schema, you could also use the schema.path() function to make this work:
var ItemSchema = new Schema({
name: String,
price: Number
});
// Getter
ItemSchema.path('price').get(function(num) {
return (num / 100).toFixed(2);
});
// Setter
ItemSchema.path('price').set(function(num) {
return num * 100;
});
A bit late but...
The answer of chovy almost worked for me – I just needed to add
{ toJSON: { getters: true }} as an options parameter in the schema declaration.
Example:
import mongoose from 'mongoose'
const productosSchema = new mongoose.Schema(
{
name: String,
price: {
type: Number,
get: v => (v/100).toFixed(2),
set: v => v*100
}
},
{
toJSON: { getters: true } //this right here
}
);
export default mongoose.model('productos', productosSchema)
This works on Mongoose 6.0.14.
References: https://mongoosejs.com/docs/api.html#document_Document-toJSON
Adds schema type "Currency" to mongoose for handling money. Strips out common characters automatically (",", "$" and alphabet chars)
https://github.com/paulcsmith/mongoose-currency
What it does:
Saves a String as an integer (by stripping non digits and multiplying by 100) to prevent rounding errors when performing calculations (See gotchas for details)
Strips out symbols from the beginning of strings (sometimes users include the currency symbol)
Strips out commas (sometimes users add in commas or copy paste values into forms, e.g. "1,000.50)
Only save from two digits past the decimal point ("$500.559" is converted to 50055 and doesn't round)
Strips [a-zA-Z] from strings
Pass in a string or a number. Numbers will be stored AS IS.
Assumes that if you set the value to an integer you have already done the conversion (e.g. 50000 = $500.00)
If a floating point number is passed in it will round it. (500.55 -> 501). Just pass in integers to be safe.
Hope it helps some1.
I've been researching for a while on this topic, because I want to store not only price, but version, which both may have trailing 0s that get chopped off when stored as a number. As far as I know, Mongoose/MongoDB can't save a number with trailing zeroes.
Unless you save the number as a string.
Aside from storing numbers in tens or thousands and dividing or parsing, you can also store it as a string. This means, you can always just print it out when you need to show "1.0" or "1.00" by just using the variable without any conversion. Due to JavaScript being untyped, you can still compare it to numbers (make sure it's on the left hand side). Var < 10, for example, will return the right evaluation, even when var is a string. If you're comparing two variables, you'd need to make sure that they're both numbers, though. When you need a number, you can multiply the string by one (var * 1 < var2 * 1), which will ensure that JavaScript treats the var as a number, although it will lose the trailing zeros.
On the one hand, storing it as a string means you need to do a conversion every time you want to use the variable as a number. On the other hand, you would presumably be doing a numeric conversion anyway (var / 100) every time you want to use a cents number as a dollar amount. This option would depend on how frequently you need to your value as a number. Also it may cause bigger bugs if you forget that your variable is a string than if you forget that your variable is in cents.
(However, it's a great fit for version numbers that would only ever be used for display and comparison.)
The numeral module will accomplish that:
http://numeraljs.com/
https://www.npmjs.com/package/numeral

How to find all documents containing a certain value with MongoDB

I'm using nodejs and mongodb.
x is a variable containing a string (certain color). now, I would like to create a query (in nodejs) that retrieves all docs which their colors field (which is a list of strings, in this case a list of colors) contains the string x.
How should I write it in nodejs?
Your question is a bit confusing, because in the first paragraph you are asking for an OR relation, but your example describes an AND relation.
When you want to find all documents which have red OR green, you have to use the $in operator:
db.collection.find({ colors: { $in:[ "red", "green" ]} });
When you want to find all documents which have red AND green (and maybe also others), you have to use $all:
db.collection.find({ colors: { $all:[ "red", "green" ]} });
Source: http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries

Resources