for each group by date in coffeescript - coffeescript

which pulls data from and reformats it.
Promise = require "bluebird"
request = Promise.promisify require "request"
moment = require "moment"
cdn = require('config').server.cloudFrontDomain
toTitleCase = require "titlecase"
exports.getStocks = (path) ->
return new Promise (resolve, reject) ->
request path
.then (body) ->
germanStock = []
germanStocks = JSON.parse body.body
germanStocks.forEach (stock) ->
obj = {}
this.parsePart = (remaining) ->
value = remaining.value
dashIndex = value.lastIndexOf '-'
if dashIndex != -1
remaining.value = value.substring 0, dashIndex - 1
return value.substring(dashIndex + 1).trim()
else
return ''
remaining =
value: stock.name
size = parsePart remaining
colour = parsePart remaining
name = remaining.value
sku = stock.sku
styleId = sku.split(/-/)[0]
colorcode = /^(.*)-(.*)([0-9])$/.exec(sku)?[2]
bgStyle = "url(//#{cdn}/assets/product_shots/thumbs/#{styleId}-#{colorcode}.jpg)"
obj.id = sku
obj.name = name
obj.colorUrl = bgStyle
obj.colour = toTitleCase(colour.toLowerCase())
obj.size = size
obj.stock = stock.stock
obj.inProduction = ''
obj.office = 'DE'
stock.preorders.forEach (i, idx) ->
date = moment(i.date).format('DD-MM-YYYY')
if idx != stock.preorders.length - 1
obj.inProduction = obj.inProduction.concat i.amount + ' due on ' + date + ', '
else
obj.inProduction = obj.inProduction.concat i.amount + ' due on ' + date
germanStock.push obj
resolve germanStock
.catch (err) ->
reject err
where my data is like:
{
"id":1,
"stamp":"2014-09-25T12:55:30Z",
"name":" MENS T-SHIRT - BRIGHT BLUE - XS",
"sku":"SS01-BB0",
"stock":81,
"active":true,
"preorders":[
{
"id":92549,
"amount":160,
"date":"2016-06-19T22:00:00Z"
},
{
"id":92549,
"amount":200,
"date":"2016-06-19T22:00:00Z"
},
{
"id":92549,
"amount":1000,
"date":"2016-06-21T22:00:00Z"
}
],
"discountMatrix":0.0,
"stockNormalized":81,
"preOrdersSum":1360
},
{
"id":2,
"stamp":"2014-09-25T12:55:30Z",
"name":" MENS T-SHIRT - BRIGHT BLUE - S",
"sku":"SS01-BB1",
"stock":339,
"active":true,
"preorders":[
{
"id":92551,
"amount":240,
"date":"2016-06-19T22:00:00Z"
},
{
"id":92438,
"amount":160,
"date":"22016-06-19T22:00:00Z"
}
],
"discountMatrix":0.0,
"stockNormalized":339,
"preOrdersSum":400
},
what is the correct way to group each preorders quantity that is on the same date, so that instead of getting:
160 due on 19-06-2016, 200 due on 19-06-2016, 1000 due on 21-06-2016
i get 360 due on 19-06-2016, 1000 due on 21-06-2016
any advice much appreciated.

You could just use an object with the date as key and the total amount for the date as value.
For each preorder, add it's amount at it's date index in this object. At the end of the iteration print the content of the object:
moment = require "moment"
data = [
{
id:1
stamp: "2014-09-25T12:55:30Z"
name: " MENS T-SHIRT - BRIGHT BLUE - XS"
sku: "SS01-BB0"
stock:81
active:true
preorders:[
{
id:92549
amount:160
date: "2016-06-19T22:00:00Z"
}
{
id:92549
amount:200
date: "2016-06-19T22:00:00Z"
}
{
id:92549
amount:1000
date: "2016-06-21T22:00:00Z"
}
]
discountMatrix:0.0
stockNormalized:81
preOrdersSum:1360
}
]
obj = {}
obj.inProduction = ""
amountByDate = {}
# for each document in your data
for doc in data
# for each preorder in your document
for preorder in doc.preorders
# add it's amount in the index equals to it's date
if amountByDate[preorder.date]
amountByDate[preorder.date] += preorder.amount
else
# or create the index with the value if it doesn't exist
amountByDate[preorder.date] = preorder.amount
for date, amount of amountByDate
if obj.inProduction != ""
obj.inProduction = obj.inProduction.concat ", #{amount} due on #{moment(date).format('DD-MM-YYYY')}"
else
obj.inProduction = obj.inProduction.concat "#{amount} due on #{moment(date).format('DD-MM-YYYY')}"
console.log obj.inProduction
Result:
360 due on 20-06-2016, 1000 due on 22-06-2016

Related

Tags format on Packer ec2-ami deployment

I'm trying out to create an amazon ec2 ami for the 1st time using Hashicorp Packer, however getting this failure on the tag creation, I already tried some retries on trial and error test for the format but still unlucky
[ec2-boy-oh-boy#ip-172-168-99-23 pogi]$ packer init .
Error: Missing item separator
on variables.pkr.hcl line 28, in variable "tags":
27: default = [
28: "environment" : "testing"
Expected a comma to mark the beginning of the next item.
My code ec2.pkr.hcl looks like this:
[ec2-boy-oh-boy#ip-172-168-99-23 pogi]$ cat ec2.pkr.hcl
packer {
required_plugins {
amazon = {
version = ">= 0.0.2"
source = "github.com/hashicorp/amazon"
}
}
}
source "amazon-ebs" "ec2" {
ami_name = "${var.ami_prefix}-${local.timestamp}"
instance_type = "t2.micro"
region = "us-east-1"
vpc_id = "${var.vpc}"
subnet_id = "${var.subnet}"
security_group_ids = ["${var.sg}"]
ssh_username = "ec2-boy-oh-boy"
source_ami_filter {
filters = {
name = "amzn2-ami-hvm-2.0*"
root-device-type = "ebs"
virtualization-type = "hvm"
}
most_recent = true
owners = ["12345567896"]
}
launch_block_device_mappings = [
{
"device_name": "/dev/xvda",
"delete_on_termination": true
"volume_size": 10
"volume_type": "gp2"
}
]
run_tags = "${var.tags}"
run_volume_tags = "${var.tags}"
}
build {
sources = [
"source.amazon-ebs.ec2"
]
}
[ec2-boy-oh-boy#ip-172-168-99-23 pogi]$
Then my code variables.pkr.hcl looks like this:
[ec2-boy-oh-boy#ip-172-168-99-23 pogi]$ cat variables.pkr.hcl
locals {
timestamp = regex_replace(timestamp(), "[- TZ:]", "")
}
variable "ami_prefix" {
type = string
default = "ec2-boy-oh-boy"
}
variable "vpc" {
type = string
default = "vpc-asd957d"
}
variable "subnet" {
type = string
default = "subnet-asd957d"
}
variable "sg" {
type = string
default = "sg-asd957d"
}
variable "tags" {
type = map
default = [
environment = "testing"
type = "none"
production = "later"
]
}
Your default value for the tags variable is of type list(string). Both the run_tags and run_volume_tags directives expect type map[string]string.
I was able to make the following changes to your variables file and run packer init successfully:
variable "tags" {
default = {
environment = "testing"
type = "none"
production = "later"
}
type = map(string)
}

How to make A Weather command? (Discord.py)

So I made this weather command down below, but for some reason, it only says the bot is typing, and there gives a error. This is the code:
import requests
#client.command()
async def weather(ctx, *, city: str):
city_name = city
complete_url = base_url + "appid=" + api_key + "&q=" + city_name
response = requests.get(complete_url)
x = response.json()
channel = ctx.message.channel
if x["cod"] != "404":
async with channel.typing():
y = x["main"]
current_temperature = y["temp"]
current_temperature_celsiuis = str(round(current_temperature - 273.15))
current_pressure = y["pressure"]
current_humidity = y["humidity"]
z = x["weather"]
weather_description = z[0]["description"]
weather_description = z[0]["description"]
embed = discord.Embed(title=f"Weather in {city_name}",
color=ctx.guild.me.top_role.color,
timestamp=ctx.message.created_at,)
embed.add_field(name="Descripition", value=f"**{weather_description}**", inline=False)
embed.add_field(name="Temperature(C)", value=f"**{current_temperature_celsiuis}°C**", inline=False)
embed.add_field(name="Humidity(%)", value=f"**{current_humidity}%**", inline=False)
embed.add_field(name="Atmospheric Pressure(hPa)", value=f"**{current_pressure}hPa**", inline=False)
embed.set_thumbnail(url="https://i.ibb.co/CMrsxdX/weather.png")
embed.set_footer(text=f"Requested by {ctx.author.name}")
await channel.send(embed=embed)
else:
await channel.send("City not found.")
But the error I get from this is saying 'main' is a keyerror

Drools comparing objects in working memory

I am trying to accumulate similar objects in working memory and set actions based on object attributes. My Rule: 3 or more procedures done on the same date for a patient by the same provider. Condition: Same date of service and same provider ID Action: 100% for 1st procedure, 50% for 2nd procedure and 25% for remaining. Each line item contains details about the procedure.
My Model object:
public class LineItem {
private Date dateOfService;
private String procedureCode;
private String providerID;
private double billedAmount;
private double allowableAmount;
//getters and setters
}
Drools Rule:
**rule "Multiple Procedures done on the same day by Same Provider"**
lock-on-active true
when
$lineItem1 : LineLevelData ( $dateOfService : dateOfService , $providerId : providerId, reasonCode == null, $lineNumber : lineNumber )
and
$lineItem2 : LineLevelData ( lineNumber!= $lineNumber , dateOfService == $dateOfService , providerId == $providerId, reasonCode == null )
and
accumulate( $lineItem: LineLevelData( dateOfService == $dateOfService , providerId == $providerId, reasonCode == null );
$list: collectList( $lineItem ) )
then
System.out.println("List size: " + $list.size () );
for ( int i = 0; i < $list.size(); i++ ){
LineLevelData lineItem = (LineLevelData)$list.get(i);
if(i == 0){
modify(lineItem){ setReimbursementAmount(0.8* ( lineItem.getBilledAmount() ) )
};
System.out.println("Line Number: " + lineItem.getLineNumber() );
}
else if(i == 1){
modify(lineItem) { setReimbursementAmount(0.5* (lineItem.getBilledAmount() ) )
};
System.out.println("Line Number: " + lineItem.getLineNumber() );
}
else {
modify(lineItem ){ setReimbursementAmount(0.25* (lineItem.getBilledAmount() ) )
};
System.out.println("Line Number: " + lineItem.getLineNumber() );
}
}
Java code:
LineLevelData line1Item = new LineLevelData();
line1Item.setLineNumber(1);
line1Item.setProcedureCode("99201");
line1Item.setDateOfService(new GregorianCalendar(2017, 9, 15).getTime());
line1Item.setBilledAmount(1000);
line1Item.setProviderId("670112");
billLineItems.add(line1Item);
LineLevelData line2Item = new LineLevelData();
line2Item.setLineNumber(2);
line2Item.setProcedureCode("99205");
**line2Item.setDateOfService(new GregorianCalendar(2017, 8, 20).getTime());
line2Item.setProviderId("670118");**
line2Item.setBilledAmount(1500);
billLineItems.add(line2Item);
LineLevelData line3Item = new LineLevelData();
line3Item.setLineNumber(3);
line3Item.setProcedureCode("99049");
**line3Item.setDateOfService(new GregorianCalendar(2017, 8, 20).getTime());
line3Item.setProviderId("670118");**
line3Item.setBilledAmount(1000);
billLineItems.add(line3Item);
LineLevelData line4Item = new LineLevelData();
line4Item.setLineNumber(4);
line4Item.setProcedureCode("99058");
**line4Item.setDateOfService(new GregorianCalendar(2017, 8, 20).getTime());**
line4Item.setBilledAmount(520);
**line4Item.setProviderId("670118");**
billLineItems.add(line4Item);
//Inserting facts in working memory
for(LineLevelData billLineItem : buildBillLineItems()){
kSession.insert(billLineItem);
log.info("Inserted Line Item : " + billLineItem.getLineNumber());
}
int rulesFired = kSession.fireAllRules(new RuleNameEqualsAgendaFilter("Multiple Procedures done on the same day by Same Provider"));
According to my test above line items with line number 2 , 3 and 4 should be updated. Instead I am getting line number 1, 3 and 4.
Rule Output:
List size: 3
Line Number: 4
Line Number: 3
Line Number: 1
Multiple Procedures rule is fired...Wed Sep 20 00:00:00 CDT 2017
===========Rule Fired============ : MULTIPLE PROCEDURES DONE ON THE SAME DAY BY SAME PROVIDER
No. of Rules fired: 1
Line Item Number: 1
Billed amount: 1500.0
Reimbursable amount: 375.0
Reason Code: CHI
Message: Coverage for all subsequent procedures is 25%
Line Item Number: 4
Billed amount: 520.0
Reimbursable amount: 416.0
Reason Code: NR
Message: Submit to Nurse Review. 100% of UCR at 80th percentile.
Line Item Number: 3
Billed amount: 1000.0
Reimbursable amount: 500.0
Reason Code: PHY
Message: Manual review is required. 50% coverage for secondary procedure.
**Line Item Number: 2
Billed amount: 1000.0
Reimbursable amount: 0.0
Reason Code: null
Message: null**

Cannot resolve element with ID while signing a part of SOAP REQUEST X509

I had the following error while trying to sign a part of SOAP Request :
org.apache.xml.security.utils.resolver.ResourceResolverException: Cannot resolve element with ID _53ea293168db637b15e2d4d7894
at org.apache.xml.security.utils.resolver.implementations.ResolverFragment.engineResolve(ResolverFragment.java:86)
at org.apache.xml.security.utils.resolver.ResourceResolver.resolve(ResourceResolver.java:279)
at org.apache.xml.security.signature.Reference.getContentsBeforeTransformation(Reference.java:417)
at org.apache.xml.security.signature.Reference.dereferenceURIandPerformTransforms(Reference.java:597)
at org.apache.xml.security.signature.Reference.calculateDigest(Reference.java:689)
at org.apache.xml.security.signature.Reference.generateDigestValue(Reference.java:396)
at org.apache.xml.security.signature.Manifest.generateDigestValues(Manifest.java:206)
at org.apache.xml.security.signature.XMLSignature.sign(XMLSignature.java:595)
It comes from the resolution of the URI declared on the reference tag.
Here is the java code i'm using for signing via X509 :
KeyStore.PrivateKeyEntry pke = ISKeyStoreManager.getInstance().getPrivateKeyEntry(keyStoreAlias, keyAlias);
AlgorithmStrings algStrings = AlgorithmStrings.getAlgDSStrings( pke.getPrivateKey(), signatureAlgorithmString, digestAlgorithmString);
String resultantXPath = StringUtils.join(xpaths, '|');
Transforms transforms = new Transforms(originalDocument);
NodeList targetDocumentList = obtainNodesForXPath(originalDocument, resultantXPath, nc);
if(targetDocumentList != null && targetDocumentList.getLength() > 0)
{
if(targetDocumentList.item(0).hasAttributes()){
Node attrId = targetDocumentList.item(0).getAttributes().getNamedItem("Id");
if(attrId != null && !attrId.getNodeValue().equals("")){
uri = new StringBuilder().append('#').append(attrId.getNodeValue()).toString();
}
else{
((Element) targetDocumentList.item(0)).setAttribute("xmlns:wsu", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd");
((Element) targetDocumentList.item(0)).setAttribute("wsu:Id", idForXmlObject);
}
}
else{
((Element) targetDocumentList.item(0)).setAttribute("xmlns:wsu", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd");
((Element) targetDocumentList.item(0)).setAttribute("wsu:Id", idForXmlObject);
}
}else{
log.debug("Target not found in the original document with xpath: " + resultantXPath);
}
transforms.addTransform("http://www.w3.org/2000/09/xmldsig#enveloped-signature");
if (resultantXPath != null) {
log.debug("Instantiation XPATHContainer");
XPathContainer xpathC = new XPathContainer(originalDocument);
xpathC.setXPath(resultantXPath);
if ((ncMap != null) && (!ncMap.isEmpty())) {
for (Map.Entry<String,String> e : ncMap.entrySet()) {
log.debug("Adding namespace to XPATH Container: " + e.getKey() + " -> " + e.getValue());
xpathC.setXPathNamespaceContext(e.getKey(), e.getValue());
}
}
transforms.addTransform("http://www.w3.org/TR/1999/REC-xpath-19991116", xpathC.getElement());
}
log.debug("Instantiation Signature");
XMLSignature sig = new XMLSignature(originalDocument, null, algStrings.signatureAlgorithm, canonicalizationAlg);
sig.setFollowNestedManifests(true);
log.debug("Ajout des assertions de transformation");
sig.addDocument("", transforms, algStrings.digestMethod);
if (idAttrForSignature != null) {
sig.setId(idAttrForSignature);
}
log.debug("DOMToString: " + serializeDOMToString(originalDocument));
// signature node insertion
NodeList nodeList = obtainNodesForXPath(originalDocument, insertSignatureAtXPath, nc);
if(nodeList != null && nodeList.getLength() > 0){
Node nodeSignature = nodeList.item(0);
Node childNode = nodeSignature.getFirstChild();
if (childNode != null) {
if (addSignatureAsLastElement)
nodeSignature.appendChild(sig.getElement());
else
nodeSignature.insertBefore(sig.getElement(), childNode);
}
else nodeSignature.appendChild(sig.getElement());
}
else{
throw new ServiceException("INVALID_SIGNATURE_NODE_SELECTOR_XPATH");
}
// Public key insertion
//X509Data x509Data = getX509Data(includeCertChain, certificateData, originalDocument, pke);
//KeyInfoReference kir = new KeyInfoReference(x509Data.getDocument());
SecurityTokenReference str = new SecurityTokenReference(sig.getKeyInfo().getDocument());
str.setKeyIdentifier(ISKeyStoreAccessorUtil.getIaikCertificate(pke.getCertificate()));
sig.getKeyInfo().getElement().appendChild(str.getElement());
log.debug("DOMToString: " + serializeDOMToString(originalDocument));
//sig.getSignedInfo().addResourceResolver(new ResolverXPointer());
((Element)(sig.getSignedInfo().getElement().getElementsByTagNameNS("http://www.w3.org/2000/09/xmldsig#", "Reference").item(0))).setAttribute("URI", uri);
log.debug("DOMToString: " + serializeDOMToString(originalDocument));
//sig.addDocument(uri, trans);
// Signature generation
sig.sign(pke.getPrivateKey());
Do you have any proposition of workaround ? or another way to set URI attribute ?
Thank you for helping !
I found it.
I added InclusiveNamespaces so that the sign method can figure out that ID is on a specific namespace defined attribute.

Error when trying to run sails server after updating nodeJS version

I am working on a Sails Project. I just updated my version of nodeJS to v5.0.0 and now when I run sails lift on my app. I get :
/Users/davidgeismar/wefootpostgres/node_modules/bindings/bindings.js:83
throw e
^
Error: Module version mismatch. Expected 47, got 46.
at Error (native)
at Object.Module._extensions..node (module.js:450:18)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:311:12)
at Module.require (module.js:366:17)
at require (module.js:385:17)
at bindings (/Users/davidgeismar/wefootpostgres/node_modules/bindings/bindings.js:76:44)
at Object. (/Users/davidgeismar/wefootpostgres/node_modules/bcrypt/bcrypt.js:3:35)
at Module._compile (module.js:425:26)
at Object.Module._extensions..js (module.js:432:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:311:12)
at Module.require (module.js:366:17)
at require (module.js:385:17)
at Object. (/Users/davidgeismar/wefootpostgres/api/services/PaiementService.js:2:14)
at Module._compile (module.js:425:26)
the binding.js file looks like this :
/**
* Module dependencies.
*/
var fs = require('fs')
, path = require('path')
, join = path.join
, dirname = path.dirname
, exists = fs.existsSync || path.existsSync
, defaults = {
arrow: process.env.NODE_BINDINGS_ARROW || ' → '
, compiled: process.env.NODE_BINDINGS_COMPILED_DIR || 'compiled'
, platform: process.platform
, arch: process.arch
, version: process.versions.node
, bindings: 'bindings.node'
, try: [
// node-gyp's linked version in the "build" dir
[ 'module_root', 'build', 'bindings' ]
// node-waf and gyp_addon (a.k.a node-gyp)
, [ 'module_root', 'build', 'Debug', 'bindings' ]
, [ 'module_root', 'build', 'Release', 'bindings' ]
// Debug files, for development (legacy behavior, remove for node v0.9)
, [ 'module_root', 'out', 'Debug', 'bindings' ]
, [ 'module_root', 'Debug', 'bindings' ]
// Release files, but manually compiled (legacy behavior, remove for node v0.9)
, [ 'module_root', 'out', 'Release', 'bindings' ]
, [ 'module_root', 'Release', 'bindings' ]
// Legacy from node-waf, node <= 0.4.x
, [ 'module_root', 'build', 'default', 'bindings' ]
// Production "Release" buildtype binary (meh...)
, [ 'module_root', 'compiled', 'version', 'platform', 'arch', 'bindings' ]
]
}
/**
* The main `bindings()` function loads the compiled bindings for a given module.
* It uses V8's Error API to determine the parent filename that this function is
* being invoked from, which is then used to find the root directory.
*/
function bindings (opts) {
// Argument surgery
if (typeof opts == 'string') {
opts = { bindings: opts }
} else if (!opts) {
opts = {}
}
opts.__proto__ = defaults
// Get the module root
if (!opts.module_root) {
opts.module_root = exports.getRoot(exports.getFileName())
}
// Ensure the given bindings name ends with .node
if (path.extname(opts.bindings) != '.node') {
opts.bindings += '.node'
}
var tries = []
, i = 0
, l = opts.try.length
, n
, b
, err
for (; i<l; i++) {
n = join.apply(null, opts.try[i].map(function (p) {
return opts[p] || p
}))
tries.push(n)
try {
b = opts.path ? require.resolve(n) : require(n)
if (!opts.path) {
b.path = n
}
return b
} catch (e) {
if (!/not find/i.test(e.message)) {
throw e
}
}
}
err = new Error('Could not locate the bindings file. Tried:\n'
+ tries.map(function (a) { return opts.arrow + a }).join('\n'))
err.tries = tries
throw err
}
module.exports = exports = bindings
/**
* Gets the filename of the JavaScript file that invokes this function.
* Used to help find the root directory of a module.
* Optionally accepts an filename argument to skip when searching for the invoking filename
*/
exports.getFileName = function getFileName (calling_file) {
var origPST = Error.prepareStackTrace
, origSTL = Error.stackTraceLimit
, dummy = {}
, fileName
Error.stackTraceLimit = 10
Error.prepareStackTrace = function (e, st) {
for (var i=0, l=st.length; i<l; i++) {
fileName = st[i].getFileName()
if (fileName !== __filename) {
if (calling_file) {
if (fileName !== calling_file) {
return
}
} else {
return
}
}
}
}
// run the 'prepareStackTrace' function above
Error.captureStackTrace(dummy)
dummy.stack
// cleanup
Error.prepareStackTrace = origPST
Error.stackTraceLimit = origSTL
return fileName
}
/**
* Gets the root directory of a module, given an arbitrary filename
* somewhere in the module tree. The "root directory" is the directory
* containing the `package.json` file.
*
* In: /home/nate/node-native-module/lib/index.js
* Out: /home/nate/node-native-module
*/
exports.getRoot = function getRoot (file) {
var dir = dirname(file)
, prev
while (true) {
if (dir === '.') {
// Avoids an infinite loop in rare cases, like the REPL
dir = process.cwd()
}
if (exists(join(dir, 'package.json')) || exists(join(dir, 'node_modules'))) {
// Found the 'package.json' file or 'node_modules' dir; we're done
return dir
}
if (prev === dir) {
// Got to the top
throw new Error('Could not find module root given file: "' + file
+ '". Do you have a `package.json` file? ')
}
// Try the parent dir next
prev = dir
dir = join(dir, '..')
}
}
Do you know what is going wrong here ?