addQueue.leaseTasks(options) returns empty params [] - google-cloud-tasks

addQueue.leaseTasks(options) returns empty params []
I created a queue added data when I try to get the data out TaskHandle has a empty parms[]
//Add to queue
Queue addQueue = queueService.addQueue();
TaskHandle task = addQueue.add(mapFundToTask(fund));
private TaskOptions mapFundToTask(Fund fund){
return TaskOptions.Builder.withMethod(Method.PULL)
.tag("FundTask")
.param("ClientId", fund.getClientId())
.param("FundId", fund.getFundId())
.param("FundName", fund.getFundName());
}
// Get data from queue
Queue addQueue = queueService.addQueue();
int count = 2;
Long leaseDuration = 1000L;
LeaseOptions options = LeaseOptions.Builder
.withTag("FundTask")
.countLimit(count)
.leasePeriod(leaseDuration, TimeUnit.MILLISECONDS);
List<TaskHandle> tasks = addQueue.leaseTasks(options);

My fault, it was saving the params, but when I did taskHolder.toString() it returned params as []. But List> entries = taskHolder.extractParams(); returned a list of enties with the data I had set in the params

Related

Access the contents of the row inserted into Dynamodb using Pynamodb save method

I have the below model for a my dynamodb table using pynamodb :
from pynamodb.models import Model
from pynamodb.attributes import (
UnicodeAttribute, UTCDateTimeAttribute, UnicodeSetAttribute, BooleanAttribute
)
class Reminders(Model):
"""Model class for the Reminders table."""
# Information on global secondary index for the table
# user_id (hash key) + reminder_id+reminder_title(sort key)
class Meta:
table_name = 'Reminders'
region = 'eu-central-1'
reminder_id = UnicodeAttribute(hash_key=True)
user_id = UnicodeAttribute(range_key=True)
reminder_title = UnicodeAttribute()
reminder_tags = UnicodeSetAttribute()
reminder_description = UnicodeAttribute()
reminder_frequency = UnicodeAttribute(default='Only once')
reminder_tasks = UnicodeSetAttribute(default=set())
reminder_expiration_date_time = UTCDateTimeAttribute(null=True)
reminder_title_reminder_id = UnicodeAttribute()
next_reminder_date_time = UTCDateTimeAttribute()
should_expire = BooleanAttribute()
When i want to create a new reminder i do it through the below code :
class DynamoBackend:
#staticmethod
def create_a_new_reminder(new_reminder: NewReminder) -> Dict[str, Any]:
"""Create a new reminder using pynamodb."""
new_reminder = models.Reminders(**new_reminder.dict())
return new_reminder.save()
In this case the NewReminder is an instance of pydantic base model like so :
class NewReminder(pydantic.BaseModel):
reminder_id: str
user_id: str
reminder_title: str
reminder_description: str
reminder_tags: Sequence[str]
reminder_frequency: str
should_expire: bool
reminder_expiration_date_time: Optional[datetime.datetime]
next_reminder_date_time: datetime.datetime
reminder_title_reminder_id: str
when i call the save method on the model object i receive the below response:
{
"ConsumedCapacity": {
"CapacityUnits": 2.0,
"TableName": "Reminders"
}
}
Now my question is the save method is directly being called by a lambda function which is in turn called by an API Gateway POST endpoint so ideally the response should be a 201 created and instead of returning the consumed capacity and table name , would be great if it returns the item inserted in the database. Below is my route code :
def create_a_new_reminder():
"""Creates a new reminder in the database."""
request_context = app.current_request.context
request_body = json.loads(app.current_request.raw_body.decode())
request_body["reminder_frequency"] = data_structures.ReminderFrequency[request_body["reminder_frequency"]]
reminder_details = data_structures.ReminderDetailsFromRequest.parse_obj(request_body)
user_details = data_structures.UserDetails(
user_name=request_context["authorizer"]["claims"]["cognito:username"],
user_email=request_context["authorizer"]["claims"]["email"]
)
reminder_id = str(uuid.uuid1())
new_reminder = data_structures.NewReminder(
reminder_id=reminder_id,
user_id=user_details.user_name,
reminder_title=reminder_details.reminder_title,
reminder_description=reminder_details.reminder_description,
reminder_tags=reminder_details.reminder_tags,
reminder_frequency=reminder_details.reminder_frequency.value[0],
should_expire=reminder_details.should_expire,
reminder_expiration_date_time=reminder_details.reminder_expiration_date_time,
next_reminder_date_time=reminder_details.next_reminder_date_time,
reminder_title_reminder_id=f"{reminder_details.reminder_title}-{reminder_id}"
)
return DynamoBackend.create_a_new_reminder(new_reminder=new_reminder)
I am very new to REST API creation and best practices so would be great if someone would guide me here . Thanks in advance !

How to convert duration to seconds in Google Sheets which uses IMPORTRANGE

I have copied the data from Googlesheet1 to Googlesheet2 using the below query
=IMPORTRANGE("url","!A2:H")
Which has copied the data from Googlesheet1 to Googlesheet2.
In that sheet, I am having a duration column like the below image
When i used the app script to copy the data to the firestore instead of saving the duration it saves the data in DateTime format like below.
Is there any way to convert the given duration to seconds in Google sheet.
I have tried using =value(G2*24*3600) but it didn't work in the Googlesheet2 since that sheet is a clone of Googlesheet1
App script Logic:
function firestore() {
// Firestore setup
const email = "//client-email";
const key = "//client-key";
const projectId = "timesheet-aog";
var firestore = FirestoreApp.getFirestore (email, key, projectId);
// get document data from ther spreadsheet
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheetname = "timesheet";
var sheet = ss.getSheetByName(sheetname);
// get the last row and column in order to define range
var sheetLR = sheet.getLastRow(); // get the last row
var sheetLC = sheet.getLastColumn(); // get the last column
var dataSR = 2; // the first row of data
// define the data range
var sourceRange = sheet.getRange(2,1,sheetLR-dataSR+1,sheetLC);
// get the data
var sourceData = sourceRange.getValues();
// get the number of length of the object in order to establish a loop value
var sourceLen = sourceData.length;
console.log('sourceLen is', sourceLen);
// Loop through the rows
for (var i=0;i<sourceLen;i++){
var data = {};
console.log('data is', sourceData);
data.date = sourceData[i][0];
data.name = sourceData[i][1];
data.workFrom = sourceData[i][2];
data.project = sourceData[i][3];
data.phase = sourceData[i][4];
data.task = sourceData[i][5];
data.totalHrs = sourceData[i][6];
data.comments = sourceData[i][7];
firestore.createDocument("timesheet",data);
}
}
Here is the formula for A1 cell of the second sheet:
={
IMPORTRANGE("url","!A2:F"),
ARRAYFORMULA(
IF(
IMPORTRANGE("url","!G2:G") = "",
"",
N(IMPORTRANGE("url","!G2:G")) * 24 * 3600
)
),
IMPORTRANGE("url","!H2:H")
}
Try using named ranges for columns (A2:F, G2:G, H2:H) in the original sheet, and import them by those names so you won't need to adjust the formula where exact column names are used.

How Do I Get The Hisory Of A LinearState

The output of one of my flows is a LinearState that has been "modified" over time by various flows.
Is there an API to get the previous versions of this state in the order that they were created/modified?
I can query the vault like this:
val linearIdCriteria = QueryCriteria.LinearStateQueryCriteria(linearId = listOf(outputState.linearId), status = ALL)
val states = myNode.services.vaultService.queryBy<MyState>(linearIdCriteria).states
However, the SQL generated by hibernate doesn't have an Order By clause so the order of the states in the list cannot be guaranteed.
The states returned don't have any timestamp on them so I can't see how to order the list.
The time that the state was saved is available as a sorting option (Sort.VaultStateAttribute.RECORDED_TIME) which should guarantee the order of the vault query.
//Get all versions of the State by its LinearId
val linearIdCriteria = QueryCriteria.LinearStateQueryCriteria(linearId = listOf(outputState.linearId), status = ALL)
//Add sorting by recorded date
val sortByRecordedDate = SortColumn(SortAttribute.Standard(Sort.VaultStateAttribute.RECORDED_TIME), Sort.Direction.ASC)
val sorting = Sort(listOf(sortByRecordedDate))
val states = myNode.services.vaultService.queryBy<MyState>(linearIdCriteria, sorting).states
Unconsumed and consumed states can be sorted in ascending/descending alphabetical order using the following code -
Vault.StateStatus status = Vault.StateStatus.CONSUMED;
#SuppressWarnings("unchecked")
Set<Class<LinearState>> contractStateTypes = new HashSet(singletonList(LinearState.class));
QueryCriteria vaultCriteria = new VaultQueryCriteria(status, contractStateTypes);
List<UniqueIdentifier> linearIds = singletonList(ids.getSecond());
QueryCriteria linearCriteriaAll = new LinearStateQueryCriteria(null, linearIds, Vault.StateStatus.UNCONSUMED, null);
QueryCriteria dealCriteriaAll = new LinearStateQueryCriteria(null, null, dealIds);
QueryCriteria compositeCriteria1 = dealCriteriaAll.or(linearCriteriaAll);
QueryCriteria compositeCriteria2 = compositeCriteria1.and(vaultCriteria);
PageSpecification pageSpec = new PageSpecification(DEFAULT_PAGE_NUM, MAX_PAGE_SIZE);
Sort.SortColumn sortByUid = new Sort.SortColumn(new SortAttribute.Standard(Sort.LinearStateAttribute.UUID), Sort.Direction.DESC);
Sort sorting = new Sort(ImmutableSet.of(sortByUid));
Vault.Page<LinearState> results = vaultService.queryBy(LinearState.class, compositeCriteria2, pageSpec, sorting);
OR
val sortAttribute = SortAttribute.Custom(CustomerSchema.CustomerEntity.class,
"changeDate")
val sorter = Sort(setOf(Sort.SortColumn(sortAttribute, Sort.Direction.DESC)))
val constraintResults = vaultService.queryBy<LinearState>(constraintTypeCriteria, sorter)
Following are the URLs for reference:
URL1: https://docs.corda.net/api-vault-query.html
URL2: https://github.com/corda/corda/issues/5060
URL3: https://github.com/manosbatsis/vaultaire
URL4: https://r3-cev.atlassian.net/browse/CORDA-2247

In Corda, how can I query the vault for all states recorded after a specific state?

I have the StateRef for a state that was recorded by my node. How can I get a stream of all the states recorded by my node since that StateRef was recorded?
You need to do two things:
Identify when the StateRef you have was recorded
Start streaming updates from after that time
Here's an example RPC client that would do this:
fun main(args: Array<String>) {
// Getting an RPC connection to the node.
require(args.size == 1) { "Usage: ExampleClientRPC <node address>" }
val nodeAddress = NetworkHostAndPort.parse(args[0])
val client = CordaRPCClient(nodeAddress)
val rpcOps = client.start("user1", "test").proxy
// Change this to an actual StateRef.
val dummyStateRef = StateRef(SecureHash.zeroHash, 0)
// Getting the time the state was recorded.
val queryByStateRefCriteria = VaultQueryCriteria(stateRefs = listOf(dummyStateRef))
val queryByStateRefResults = rpcOps.vaultQueryBy<ContractState>(queryByStateRefCriteria)
val queryByStateRefMetadata = queryByStateRefResults.statesMetadata
val dummyStateRefRecordedTime = queryByStateRefMetadata.single().recordedTime
// Getting the states recorded after that time.
val queryAfterTimeExpression = TimeCondition(
RECORDED, BinaryComparison(BinaryComparisonOperator.GREATER_THAN_OR_EQUAL, dummyStateRefRecordedTime))
val queryAfterTimeCriteria = VaultQueryCriteria(
status = ALL,
timeCondition = queryAfterTimeExpression)
val queryAfterTimeResults = rpcOps.vaultTrackBy<ContractState>(queryAfterTimeCriteria)
val afterTimeStates = queryAfterTimeResults.states
}

neo4j query to return node with collection item

I have some nodes in Neo4J database with array attribute. Something like:
Node (name = firstNode, array = [fist, second])
Node (name = secondNode, array = [second, third])
I want write query to return this combination:
name = firstNode, arrayItem = first
name = firstNode, arrayItem = second
name = secondNode, arrayItem = second
Name = secondNode, arrayItem = third
Anyone some suggestion?
UNWIND is for splitting up an array into multiple lines:
match (n:MyLabel)
unwind n.array as ele
return n.name, ele
(This assumes your nodes have a MyLabel label.)

Resources