The example for custom states show that metadata can be stored:
http://docs.celeryproject.org/en/latest/userguide/tasks.html#custom-states
Which API can I use to retrieve the metadata associated with a result?
The docs don't make it clear how to get the metadata from the result. Use AsyncResult.info.
>>> job = AsyncResult(job_id)
>>> print(job.info)
{'current': 2, 'total': 100}
The example given is as follows:
#app.task(bind=True)
def upload_files(self, filenames):
for i, file in enumerate(filenames):
self.update_state(state='PROGRESS',
meta={'current': i, 'total': len(filenames)})
When you setup the task, say
task = upload_files.delay(['happy.txt', 'sad.txt', ...])
You can access the meta info via task.result
Hope that helps
Related
I would like to send a POST request to an OData v4 ActionImport. How can I achieve this in an SAPUI5 environment? I had a look at the v4 ODataModel and ODataContextBinding. There are methods for execute an ActionImport but i dont know how to set the body then.
Generally asking: How should I submit OData requests that should not necessarily be bound to the UI? For example, if I just want to query a value from the backend or send a file to the backend. Right now, I create an ODataContextBinding and call the execute/requestObject method but i think that this might not be the best approach (Also i cant set the request body this way). Maybe it might be better to make a direct ajax request?
Thanks in advance!
I stumbled on your question because I had the exact same problem. I'm providing my solution in case it helps someone else.
onValidate: function(oEvent) {
var oModel = this.getModel("reportService");
var oActivityCreateContext = this.getCreateContext();
var oActionODataContextBinding = oModel.bindContext("/validateActivity(...)");
oActionODataContextBinding.setParameter("activity", oActivityCreateContext.getObject())
oActionODataContextBinding.execute().then(
function() {
var oActionContext = oActionODataContextBinding.getBoundContext();
console.table(oActionContext.getObject().value);
}.bind(this)
);
}
The model "reportService" is a sap.ui.model.odata.v4.ODataModel. The function call is unbound and is declared this way in my service.cds file:
action validateActivity(activity : Activities) returns many rm.ValidationMessage;
The oActionContext.getObject().value contains the response to my function call.
The key here is the setParameter that sets the activity on the payload. Here's what the resulting request could look like:
POST http://localhost:8080/api/ReportService/validateActivity
Content-Type: application/json
{"activity": {
"activityNumber": 1,
"report_ID": "a3558fce-76bc-49a9-ae23-bd5566fb3bc6",
"job_code": "160",
"learningPeriod": 1,
"salaryAnnex": "D3",
"workingRegion_code": "08",
"unionName": "CSD",
"local": "Local 123",
"nbWeeksWorked": 8,
"nbHourSimple": 110,
"nbHourTimeAndHalf": 5,
"nbHourDouble": 0,
"sin": "111222333",
}}
I hope this will help others who are struggling to do this.
Regards
I'm trying to add two numbers using DialogFlow.
Question: Add 5 and 6
My Ans: Result is 5+6
but I'm getting the response this one.
Ans Logic: Result is $number + $number1
https://discuss.api.ai/t/start-conversation-with-user-programatically-from-the-server-side-api-ais-side-on-a-notification/1876/2
It’s an API for creating a Natural Language Understanding model for a
conversational interface. If you have custom business logic or
platform-specific message formatting requirements then
for that you will need to turn on fulfillment and in that part get the parameters that was recognised in action and parameters using queryResult.parameters.<nameofparam> and do your task like
let num1 = parseInt(queryResult.parameters.number);
let num2 = parseInt(queryResult.parameters.number1);
let responseText = {
"fulfillmentText": "",
"fulfillmentMessages": [],
"source": "example.com",
"payload": {},
"outputContexts": [],
"followupEventInput": {}
};
responseText.fulfillmentText = "" + num1 + num2;
res.status(200).send(JSON.stringify(responseText));
If you need to perform some operations, then you need to make use of fulfillment - webhook concept. I used Django framework to capture the request and sent back the response as jsonresponse.
Below is the piece of code:
#csrf_exempt
def webhook(request):
# build a request object
req = json.loads(request.body)
# get action from json (i.e) arithmetic operation that we need to perform
action = req.get('queryResult').get('action')
#get the numbers from the json
num = req.get('queryResult').get('parameters')
n1 = int(num.get('number'))
n2 = int(num.get('number1'))
if action == 'addition':
# return a fulfillment message
fulfillmentText = {'fulfillmentText': n1+n2}
return JsonResponse(fulfillmentText, safe=False)
If you are interested to know more, please spend sometime in reading my blog which has the complete piece of code along with steps of implementation.
I am trying to fetch a json object from the mongodb using meteor, but I have no clue why I’m unable to do so.
I need it to be a JSON object only.
One of the entries of the collection looks like this:
[Image taken from Meteor Dev Tools]
Link: https://i.stack.imgur.com/BxRmS.png
I’m trying to fetch the value part by passing the name.
Code on front end:
export default withTracker(() => {
let aSub = Meteor.subscribe(‘allEntries’);
return {
aBoundaries: DataCollection.find({}).fetch()
}
})(Component Name);
The Meteor Call Statement on front-end:
dataFromDb = Meteor.call(‘functionToBeCalled’, ‘Sydney’);
Server-side Code:
Meteor.publish(‘allEntries’, function(){
return DataCollection.find();
});
Meteor.methods({
functionToBeCalled(aName){
return DataCollection.find({name: aName});
}
});
Another of my questions is:
Is there any way that we publish only all the names in the beginning and then publish the values on demand?
Thanks for your help in advance!
I have tried this as well, but it did not work:
functionToBeCalled(aName){
var query = {};
query['name'] = aName;
return DataCollection.find(query).fetch();
}
The issue seems to be with query.
Collection.find() returns data with cursor.
To get an array of objects, use Collection.find().fetch(). The jsons are returned as collection of array like [{json1}, {json2}].
If there is a single document, you can access the json using Collection.find().fetch()[0]. Another alternative is to use findOne. Example - Collection.findOne(). This will return a single JSON object.
use Meteor.subscribe('allEntries'), do not assign it to a variable.
Meteor.subscribe is asynchronous, it's best you ensure that your subscriptions are ready before you fetch data.
Log DataCollection.find({}).fetch() to your console
Check this official reference https://docs.meteor.com/api/pubsub.html#Meteor-subscribe.
Your second question isn't that clear.
Just in case anyone comes here to look for the answer ~~~
So... I was able to make it work with this code on the server:
Meteor.methods({
functionToBeCalled(aName){
console.log(aName);
return DataCollection.findOne({name: aName});
}
});
And this on the client:
Meteor.call('functionToBeCalled', nameToBePassed, (error,response) => {
console.log(error, "error");
console.log(response, "response"); //response here
})
Thanks for the help!
I have a REST client that returns me a list of systems.
I need this list to be as a parameter for a jenkins job.
I think I need Actice Choices Parameter plugin with Groovy and HTTPBuilder in order to do that.
What do you guys think?
I did not find a way to install HTTPBuilder into Jenkins.
Is there any other way that you guys think it is possible?
I have run into the same problem trying to parse parameters via groovy script. Arun's answer did not work for me. However, I have managed to get it to work using the following:
import java.io.BufferedReader
import java.io.InputStreamReader
import java.io.OutputStreamWriter
import java.net.URL
import java.net.URLConnection
import groovy.json.JsonSlurper
def choices = []
def url = new URL("some.data.url")
def conn = url.openConnection()
conn.setDoOutput(true)
def reader = new BufferedReader(new InputStreamReader(conn.getInputStream()))
def results = new JsonSlurper().parseText(reader.getText());
reader.close()
results.each { data -> choices.push(data.field) }
return choices.sort()
First paste the JSON body snapshot output -or whatever your REST client is going to return. That'll help.
For ex: if it'll return a JSON object then you can use Active Choice Parameter's Groovy script step - OR Scriptler script (within the Active Choice Parameter plugin). PS: Scriptler script runs in the same JVM of Jenkins process so it has access to Jenkins/etc object for free. You don't need HTTPBuilder or anything. See the code sample below.
Assuming if your REST client is returning a JSON object and from that object if you want to list hostname of the system or some field name then replace the following variable with that and you'll get it listed while doing "Build with parameters" from Jenkins job's dashboard.
import groovy.json.JsonSlurper
//this will be your URL which will return something, tweak it if you want to pass parameters or username/password acc.
def SOME_URL = "https://koba.baby.com/some_url"
// now connect to the URL and create a connection variable 'conn'
def conn = SOME_URL.toURL().openConnection()
// create a list variable 'servernames'
def servernames = []
// if connection response was successful i.e. http protocol return code was 200, then do the following
if( conn.responseCode == 200 ) {
// get the results / output of the URL connection in a variable 'results'
def results = new JsonSlurper().parseText(conn.content.text)
// to see results variable output uncomment the next line
//println results
// now read each element in the 'results' variable and pick servername/somefield variable into the list variable 'servernames'
results.each { id, data -> servernames.push(data.someField_or_HostName) }
}
return servernames.sort().unique()
// return servernames.sort()
I use rt:activeUsers metric to get active users on website for realtime data.
I want to get active users in real time for a specific page (path or url), not the whole website. Is there a way to implement it? I went through API Explorer but gain no success.
For anybody else looking for this below is an example of how I accomplished this in javascript.
I started with the sample at: https://ga-dev-tools.appspot.com/embed-api/third-party-visualizations/
That sample uses a extension to the embed api to get active users: active-users.js
I didn't know where to get that active-users.js file so I just used the developer tools in Chrome and grabbed it that way. Saved it locally and linked to it in my page. If anyone knows a official location to get that please comment below. Thx.
If you look at the source to that file, I modifed the pollActiveUsers function to add a filters parameter like so:
pollActiveUsers_: function () {
var t = this.get(),
i = 1e3 * (t.pollingInterval || 5);
if (isNaN(i) || i < 5e3)
throw new Error("Frequency must be 5 seconds or more.");
this.polling_ = !0,
gapi.client.analytics.data.realtime.get({
ids: t.ids,
metrics: "rt:activeUsers",
filters: t.filters
}).then(function (t) {
var e = t.result,
s = e.totalResults ? +e.rows[0][0] : 0,
n = this.activeUsers;
this.emit("success", {
activeUsers: this.activeUsers
}),
s != n && (this.activeUsers = s, this.onChange_(s - n)),
1 == this.polling_ && (this.timeout_ = setTimeout(this.pollActiveUsers_.bind(this), i))
}
.bind(this))
},
Now in my page javascript I can call it like so:
var activeUsers = new gapi.analytics.ext.ActiveUsers({
container: 'active-users-container',
pollingInterval: 5,
filters: "rt:pagePath==/somepath/somepage/",
ids: "ga:<yourviewid>"
});
Hope that helps somebody.
While the Real-time API is very limited it does allow you to use filters. Filters are a kind of where clause.
The real-time documentation is also very limited but you can look at the documentation for filters on the core reporting API it works the same
filters=ga:browser%3D~%5EFirefox
I think you should check out the dimension rt:pagePath its probably what you are looking for.