Google Classroom: How can I get the studentSubmissionId? - google-classroom

I have the courseWorkId, the courseId, and the student email. I have verified they're correct using the API explorer to get the data. I want to get the studentSubmissionId so I can patch the grade and assign a score. I am not swift with JSON and cannot seem to parse the value I get for the response below.
function getSubmissionId(stdEmail) {
gapi.client.classroom.courses.courseWork.studentSubmissions.list({
courseId: gCourseId,
courseWorkId: gCourseWorkId,
userId:'stdEmail'
}).then(function(response) {
// response.result...??
// how to I parse this??
});
}

Check online on how to access JSON Objects:
var myObj = { "name":"John",
"age":30,
"car":{
"brand": "Ferrari"
}
};
x = myObj.age
y = myObj["car"]["brand"];
console.log(x); // returns 30
console.log(y); // returns Ferrari

This worked for me to get the studentSubmissionId.
function getSubmissionId(stdEmail) {
var gStudentSubmissionID;
gapi.client.classroom.courses.courseWork.studentSubmissions.list({
courseId: gCourseId,
courseWorkId: gCourseWorkId,
userId: stdEmail
}).then(function(response) {
gStudentSubmissionID = response.result.studentSubmissions[0].id;
//console.log(response.result.studentSubmissions[0].id);
console.log('associatedWithDeveloper: '+response.result.studentSubmissions[0].associatedWithDeveloper);
});
}

Related

How to load and save a work order record using the map reduce script

I am trying to only load and save a work order record using the map-reduce script. But I don't see logs for loaded work orders or saved work orders. the script is executing only until work_order_Id. Please Help!   
Below is my code...
function getInputData(){
var process_data =[];
try{
var workorderSearchObj = search.create({
type: "workorder",
filters:
[
["type","anyof","WorkOrd"],
"AND",
["mainline","is","T"],
"AND",
["status","anyof","WorkOrd:A","WorkOrd:B","WorkOrd:D"]
],
columns:
[
search.createColumn({name: "internalid", label: "Internal ID"}),
search.createColumn({name: "tranid", label: "Document Number"})
]
});
var searchResultCount = workorderSearchObj.runPaged().count;
log.debug("workorderSearchObj result count",searchResultCount);
workorderSearchObj.run().each(function(result){
// .run().each has a limit of 4,000 results
var work_Order = result.getValue({name:'internalid'});
var document_no = result.getValue({name:'tranid'});
process_data.push({
'work_Order':work_Order,
'document_no':document_no
});
return true;
});
}catch(error){
log.debug(error);
}
return process_data;
}
function map(context){
var process_data=JSON.parse(context.value);
log.debug('process_data',process_data);
var work_order_Id = process_data.work_Order;
log.debug("work_order_Id",work_order_Id);
var work_Order_obj = record.load({
type: record.Type.WORK_ORDER,
id: work_order_Id,
isDynamic: true
});
log.debug("work_Order_obj",work_Order_obj);
var recId=work_Order_obj.save({
enableSourcing: true,
ignoreMandatoryFields: true
});
log.debug("recId",recId);
}
I am trying to load and save work order record. But its not executing.I am trying to load and save a work order record. but it's not loading.
I usually like to simply return saved searches in getInputData because it's consistent to work with and you don't have to fuss with the going over 4k search results and having to return arrays of objects that you put together yourself. Usually transforming data to be in the format you want is best done in the map stage.
/**
* #NScriptType MapReduceScript
* #NApiVersion 2.x
*/
define(["N/search", "N/record"], function (search, record) {
function getInputData() {
// run a saved search of work orders
return search.create({
type: "workorder",
filters: [
["type","anyof","WorkOrd"],
"AND",
["mainline","is","T"],
"AND",
["status","anyof","WorkOrd:A","WorkOrd:B","WorkOrd:D"]
],
columns: [
search.createColumn({name: "internalid", label: "Internal ID"}),
search.createColumn({name: "tranid", label: "Document Number"}),
]
});
}
function map(context) {
// get the work order id
var workOrderId = JSON.parse(context.value).id;
log.debug("workOrderId", workOrderId);
// load the work order
var wordOrderRecord = record.load({
type: record.Type.WORK_ORDER,
id: work_order_Id,
isDynamic: true,
});
log.debug("wordOrderRecord", wordOrderRecord);
// save the work order
var recId = wordOrderRecord.save({
enableSourcing: true,
ignoreMandatoryFields: true
});
log.debug("recId",recId);
}
function summarize(context) {
// log any errors that might occur
context.mapSummary.errors.iterator().each(function (_, errJson) {
var error = JSON.parse(errJson);
log.error({title: error.name, details: error.message});
return true;
});
}
return {
getInputData: getInputData,
map: map,
summarize: summarize,
};
})

Strapi custom service overwrite find method

I'm using strapi v4 and I want to populate all nested fields by default when I retrieve a list of my objects (contact-infos). Therefore I have overwritten the contact-info service with following code:
export default factories.createCoreService('api::contact-info.contact-info', ({ strapi }): {} => ({
async find(...args) {
let { results, pagination } = await super.find(...args)
results = await strapi.entityService.findMany('api::contact-info.contact-info', {
fields: ['locale'],
populate: {
sections: {
populate: { link: true }
}
}
})
return { results, pagination }
},
}));
That works well, but I execute a find all entries on the database twice, I guess, which I want to avoid, but when I try to return the result from the entityService directly I'm getting following response:
data": null,
"error": {
"status": 404,
"name": "NotFoundError",
"message": "Not Found",
"details": {}
}
also, I have no idea how I would retrieve the pagination information if I don't call super.find(). Is there any way to find all contents with the option to populate nested objects?
the recommended way of doing this, would be a middleware (do it once apply for all controllers). There would be an video Best Practice Session 003 where it's describes exactly this scenario (Not sure if it's discord only, but on moment of writing this it wasn't yet published).
So regarding rest of your question:
async find(...args) {
let { results, pagination } = await super.find({...args, populate: {section: ['link']})
}
should be sufficient to fix that up in one query
custom pagination example:
async findOne(ctx) {
const { user, auth } = ctx.state;
const { id } = ctx.params;
const limit = ctx.query?.limit ?? 20;
const offset = ctx.query?.offset ?? 0;
const logs = await strapi.db.query("api::tasks-log.tasks-log").findMany({
where: { task: id },
limit,
offset,
orderBy: { updatedAt: "DESC" },
});
const total = await strapi.db
.query("api::tasks-log.tasks-log")
.count({ where: { task: id } });
return { data: logs, meta: { total, offset, limit } };
}
one small addition to the accepted answer, the answer didn't work completely since args is an array with an object inside, so I had to do it like this:
async find(...args) {
const argsObj = args[0]
let { results, pagination } = await super.find({...argsObj, populate: {section: ['link']})
}

Shopify storefront API GraphQL: How to get specific product data?

Note: I'm new to GraphQL.
Challenge: I use the Shopify Storefront API to create a selectbox of all our products. When a user selects a product in this selectbox, its metafields should be displayed on the page.
I managed to create that selectbox. But how would i display the product-specific data when a choice was made in the selectbox? See current code:
function apiCall(productQuery) {
return fetch('https://store//api/2022-04/graphql.json',
{
method: 'POST',
headers: {
'Content-Type': 'application/graphql',
'X-Shopify-Storefront-Access-Token': "xxx"
},
"body": productQuery
}
)
.then(
response => response.json()
);
}
function getProducts() {
const productQuery = `{ products(first: 250) { edges { node { id handle title } } } }`;
return apiCall(productQuery);
}
$(document).ready(function() {
const product_selector_container = $('.product_selector_container');
getProducts().then(response => {
product_selector_container.prepend("<select name='product_compatibility_selector' id='product_compatibility_selector'></select>");
const productSelect = $('#product_compatibility_selector');
const productSelectResult = $("#product_compatibility_result");
response.data.products.edges.forEach(product => {
const optionValues = `<option value="${product.node.handle}">${product.node.title}<option>`;
productSelect.append(optionValues);
});
$("#product_compatibility_selector").on('change', function() {
var selected = $(this).find('option:selected').text();
var selectedVal = $(this).find('option').val();
$(".chosen_product_title").text(selected);
response.data.products.edges.forEach(product => {
// HOW DO I REFERENCE THE CURRENT CHOSEN PRODUCT TO OUTPUT VARIOUS NODES?
const compatibility_result = `${product.node.title}`;
productSelectResult.append(compatibility_result);
});
});
});
});
Now that you have the handle of the selected produt to retrieve all the metafields of that produt you need to run another query, using the "query" parameter, something like this
{
products(first: 1, query:"handle:your-handle"){
edges{
node{
metafields(first:10){
edges{
node{
value
key
}
}
}
}
}
}
}
or
{
product(handle:"your_handle"){
title
metafield(key:"your_key", namespace:"your_space"){
value
}
}
}
If you want to parametrize your handle you may want to introduce variables in your query, like this
query($handle:String){
product(handle:$handle){
title
metafield(key:"x",namespace:"y"){
id
value
}
}
}
and with the variable object being like
{"handle":"your-handle"}
In the request instead of just sending the query you send an object like
{"query" : your-query, "variables" : variable-object}

Trouble with an undefined object in Alexa Skills Custom Intents

I am currently attempting to make an Alexa skill that will issue a "Find my iPhone" alert to my apple devices when I give alexa the correct prompts. I am quite new to developing for the alexa skill set and coding at that (especially in node.js). Here is my quote:
var phoneId = "I have my values here";
var ipadId = "I have my values here";
var macId = "I have my values here";
var deviceId = "";
var APP_ID = ''; //replace with "amzn1.echo-sdk-ams.app.[your-unique-value-here]";
var AlexaSkill = require('./AlexaSkill');
var alexaResponse;
//Import Apple.js
var Apple = require('./Apple');
var apple = new Apple();
var alertSuccess = "Alert sent to Kenny's phone";
var alertFailed = "Alert couldn't be sent to Kenny's phone. Good luck finding it.";
var FindDevice = function () {
AlexaSkill.call(this, APP_ID);
};
// Extend AlexaSkill
FindDevice.prototype = Object.create(AlexaSkill.prototype);
FindDevice.prototype.constructor = FindDevice;
FindDevice.prototype.eventHandlers.onSessionStarted = function (sessionStartedRequest, session) {
console.log("Quote onSessionStarted requestId: " + sessionStartedRequest.requestId
+ ", sessionId: " + session.sessionId);
// any initialization logic goes here
};
FindDevice.prototype.eventHandlers.onLaunch = function (launchRequest, session, response) {
console.log("Quote onLaunch requestId: " + launchRequest.requestId + ", sessionId: " + session.sessionId);
getWelcomeResponse(response);
};
FindDevice.prototype.eventHandlers.onSessionEnded = function (sessionEndedRequest, session) {
console.log("Quote onSessionEnded requestId: " + sessionEndedRequest.requestId
+ ", sessionId: " + session.sessionId);
// any cleanup logic goes here
};
FindDevice.prototype.intentHandlers = {
// register custom intent handlers
"FindDeviceIntent": function (intent, session, response) {
determineDevice(intent, session, response);
}
};
/**
* Returns the welcome response for when a user invokes this skill.
*/
function getWelcomeResponse(response) {
// If we wanted to initialize the session to have some attributes we could add those here.
var speechText = "Welcome to the Lost Device. Which device shall I find?";
var repromptText = "<speak>Please choose a category by saying, " +
"iPhone <break time=\"0.2s\" /> " +
"Mac <break time=\"0.2s\" /> " +
"iPad <break time=\"0.2s\" /></speak>";
var speechOutput = {
speech: speechText,
type: AlexaSkill.speechOutputType.PLAIN_TEXT
};
var repromptOutput = {
speech: repromptText,
type: AlexaSkill.speechOutputType.SSML
};
response.ask(speechOutput, repromptOutput);
}
function determineDevice(intent, session, response) {
var deviceSlot = intent.slots.Device;
if (deviceSlot == "iPhone") {
deviceId = phoneId;
pingDevice(deviceId);
} else if (deviceSlot == "iPad") {
deviceId = ipadId;
pingDevice(deviceId);
} else if (deviceSlot == "Mac") {
deviceId = macId;
pingDevice(deviceId);
} else {
var speechText = "None of those are valid devices. Please try again.";
speechOutput = {
speech: speechText,
type: AlexaSkill.speechOutputType.PLAIN_TEXT
};
response.tell(speechOutput);
}
}
function pingDevice(deviceId) {
apple.sendAlert(deviceId, 'Glad you found your phone.', function(success, result){
if(success){
console.log("Alert Sent Successfully");
var speechOutput = alertSuccess;
response.tell(speechOutput);
} else {
console.log("Alert Unsuccessful");
console.log(result);
var speechOutput = alertFailed;
response.tell(speechOutput);
}
});
}
// Create the handler that responds to the Alexa Request.
exports.handler = function (event, context) {
// Create an instance of the FindDevice skill.
var findDevice = new FindDevice();
findDevice.execute(event, context);
};
Here is the error from lambda:
{
"errorMessage": "Cannot read property 'PLAIN_TEXT' of undefined",
"errorType": "TypeError",
"stackTrace": [
"getWelcomeResponse (/var/task/index.js:87:42)",
"FindDevice.eventHandlers.onLaunch (/var/task/index.js:58:5)",
"FindDevice.LaunchRequest (/var/task/AlexaSkill.js:10:37)",
"FindDevice.AlexaSkill.execute (/var/task/AlexaSkill.js:91:24)",
"exports.handler (/var/task/index.js:137:16)"
]
}
I understand that there is an undefined object here, but for the life of me I can't figure out where the code is going wrong. I am trying to take the Slot from my intent and then change the device to ping based on the slot word used. Also because I am so new to this a lot of the coding is just being done by patching things together. I did find that when I removed the .PLAIN_TEXT lines all together the code ran in lambda, but then broke in the alexa skills test area. I get the hunch I don't understand how the slots from intents are passed, but I am having trouble finding material I can understand on that matter. Any help would be fantastic!
Within the determineDevice function, you're accessing the "Device" slot object directly, rather than the actual value passed in, therefore it will never match your pre-defined set of device names.
A slot object has a name and a value - if you take a look at the Service Request JSON in the Service Simulator within the Developer Console when you're testing your Alexa skill, you'll see something like the following:
{
"session": {
"sessionId": "SessionId.dd05eb31-ae83-4058-b6d5-df55fbe51040",
"application": {
"applicationId": "amzn1.ask.skill.61dc6132-1727-4e56-b194-5996b626cb5a"
},
"attributes": {
},
"user": {
"userId": "amzn1.ask.account.XXXXXXXXXXXX"
},
"new": false
},
"request": {
"type": "IntentRequest",
"requestId": "EdwRequestId.6f083909-a831-495f-9b55-75be9f37a9d7",
"locale": "en-GB",
"timestamp": "2017-07-23T22:14:45Z",
"intent": {
"name": "AnswerIntent",
"slots": {
"person": {
"name": "person",
"value": "Fred"
}
}
}
},
"version": "1.0"
}
Note I have a slot called "person" in this case, but to get the value in the slot, you need to access the "value" property. In your example, you would change the first line of the determineDevice function to:
var deviceSlot = intent.slots.Device.value;
As an aside, I've found the Alexa-cookbook Github repository an essential resource for learning how to work with the Alexa SDK, there are examples in there for most scenarios.

Filter Parse.Object properties that should get saved to the server

I have this Parse.Object that I want to save to the server, but I'd like to whitelist the attributes of this object that get saved.
Parse.Object.extend('someObject', {
defaults: {
foo: 1,
bar: 2,
computedProperty: function() {
return this.get('foo') + this.get('bar')
}
},
get: function(attr) {
var value = Parse.Object.prototype.get.call(this, attr)
return _.isFunction(value) ? value.call(this) : value
}
})
As you can see, this object has a computed property among its attributes. I would like to filter out the computedProperty when I save this Parse.Object. Is that possible?
So, we've figured out a way to filter the list of attributes that get saved.
If you wanna do it, you have to override a private, undocumented method on the Parse.Object called _getSaveJSON, so the complete model above would be:
Parse.Object.extend('someObject', {
defaults: {
foo: 1,
bar: 2,
computedProperty: function() {
return 1+2
}
},
get: function(attr) {
var value = Parse.Object.prototype.get.call(this, attr)
return _.isFunction(value) ? value.call(this) : value
},
_getSaveJSON: function() {
var model = this
var json = _.clone(_.first(this._opSetQueue))
Parse._objectEach(json, function(op, key) {
json[key] = op.toJSON();
});
var whitelistedAttributes = ['foo', 'bar']
return _.pick(json, whitelistedAttributes)
}
})

Resources