Can I Add a Completions (Intellisense) File to a Language Support Extension? - autocomplete

I am developing a language support extension for VS Code by converting a Sublime tmBundle. I am using the bundle from siteleaf/liquid-syntax-mode. I have successfully included the following using yo code options 4 & 5 and combining the output:
Syntax File (.tmLanguage)
Snippets (.sublime-snippet)
What I would like to do is add autocomplete/Intellisense support by importing the .sublime-completions file, either directly or by rewriting it somehow.
Is it even possible to add items to the autocomplete/Intellisense in VS Code?

It looks like it is possible if I create a Language Server extension. From the site:
The first interesting feature a language server usually implements is validation of documents. In that sense, even a linter counts as a language server and in VS Code linters are usually implemented as language servers (see eslint and jshint for examples). But there is more to language servers. They can provide code complete, Find All References or Go To Definition. The example code below adds code completion to the server. It simply proposes the two words 'TypeScript' and 'JavaScript'.
And some sample code:
// This handler provides the initial list of the completion items.
connection.onCompletion((textDocumentPosition: TextDocumentPositionParams): CompletionItem[] => {
// The pass parameter contains the position of the text document in
// which code complete got requested. For the example we ignore this
// info and always provide the same completion items.
return [
{
label: 'TypeScript',
kind: CompletionItemKind.Text,
data: 1
},
{
label: 'JavaScript',
kind: CompletionItemKind.Text,
data: 2
}
]
});
// This handler resolve additional information for the item selected in
// the completion list.
connection.onCompletionResolve((item: CompletionItem): CompletionItem => {
if (item.data === 1) {
item.detail = 'TypeScript details',
item.documentation = 'TypeScript documentation'
} else if (item.data === 2) {
item.detail = 'JavaScript details',
item.documentation = 'JavaScript documentation'
}
return item;
});

Related

G-suite Forms Quiz. Random answers [duplicate]

I have to activate the properties to shuffle the question of a multiple choice type questoin, but I can't find the properties. I found this code that randomizes questions, but not the answers.
form.setShuffleQuestions(true);
Image of the visual component
Issuetracker:
This isn't currently possible. Consider adding a star (on top left) to the following feature requests for Google to prioritize the issue:
https://issuetracker.google.com/issues/36764938
https://issuetracker.google.com/issues/64134484
Partial worksround:
Partial Workaround as already mentioned in this answer is to shuffle the array creating options and setback the array using setChoiceValues(). The drawback of such server side randomizing is
It can only be done whenever the server script runs and not when client opens the form
Even if you randomize each minute, it is possible that users opening the form simultaneously will see the same order of options
Sample script:
const form = FormApp.openById('/*form id*/');
const item = form.addMultipleChoiceItem();
item.setTitle('Car or truck?');
const options = ['Truck', 'Car'];
//Durstenfeld algo
for (let i = options.length - 1; i > 0; i--) {
let rand = Math.floor(Math.random() * i);
[options[i], options[rand]] = [options[rand], options[i]];
}
item.setChoiceValues(options);
I believe that you have to randomize the options yourself with something like this:
function randomizeArray(A) {
var iA=A.slice();
var oA=[];
for(var i=0;i<A.length;i++) {
var index=Math.floor(Math.random()*iA.length);
oA.push(iA[index]);
iA.splice(index,1);
}
return oA;
}
Unfortunately, in the current sage, it seems that this cannot still be achieved by Google Forms service (FormApp).
But, On March 16, 2022, Google Forms API has been officially released. Ref By this, fortunately, I confirmed that your this question can be directly achieved using Google Forms API.
In the current stage, Google Forms API cannot be used with Advanced Google services. So it is required to do the following flow.
Usage:
1. Linking Google Cloud Platform Project to Google Apps Script Project for New IDE.
In order to use Forms API, please link Google Cloud Platform Project to Google Apps Script Project for New IDE, and please enable Forms API at the API console. Ref
When Google Forms API can be used with Advanced Google services, this process can be skipped.
2. Scope.
In order to use this sample script, please use the following scopes. Ref
https://www.googleapis.com/auth/script.external_request
https://www.googleapis.com/auth/forms
https://www.googleapis.com/auth/forms.body
When Google Forms API can be used with Advanced Google services, this process can be skipped.
3. Sample script:
Please copy and paste the following script to the script editor linked to Google Cloud Platform Project and save the script.
function myFunction() {
const formTitle = "sample"; // This is a form title.
// THis is an object for creating quizzes.
const obj = [
{ "question": "sample question 1", "answers": ["answer1", "answer2", "answer3"], "correct": ["answer1"], "point": 1, "type": "RADIO" },
];
// Create new Google Form and set as quize.
const form = FormApp.create(formTitle);
form.setIsQuiz(true).setTitle("Sample");
// form.setShuffleQuestions(true); // If you want to shuffle questions, you can use this line.
// Create request body for Google Forms API.
const url = `https://forms.googleapis.com/v1/forms/${form.getId()}:batchUpdate`;
const requests = obj.map(({ question, answers, correct, point, type }, index) => ({
createItem: {
item: {
title: question,
questionItem: { question: { choiceQuestion: { options: answers.map(value => ({ value })), shuffle: true, type }, grading: { correctAnswers: { answers: correct.map(e => ({ value: e })) }, pointValue: point } } },
}, location: { index }
}
}));
// Request to Google Forms API.
const params = {
method: "post",
contentType: "application/json",
headers: { authorization: "Bearer " + ScriptApp.getOAuthToken() },
payload: JSON.stringify({ requests }),
muteHttpExceptions: true
};
const res = UrlFetchApp.fetch(url, params);
console.log(res.getContentText())
}
When this script is run, as a sample, a new Google Form is created, and a sample question including the radio button is set. And, you can confirm that "Shuffle option order" is checked.
References:
Linking Google Cloud Platform Project to Google Apps Script Project for New IDE
Method: forms.batchUpdate

How do I use jest with coffeescript and ES6/ES2015 (e.g. via Babel)?

My team has been using both coffeescript and ES6/ES2015 (via Babel) in our project. Since the files are ultimately compatible due to Babel, it's been working great. But I can't figure out how we can write a jest test that allows both.
I've found examples of how to use jest with coffee, or ES6 features, but not both:
Example with coffeescript
Another example with coffeescript
Example with Babel
Somewhere someone suggested to set the preprocessor as babel-jest, which works fine for me if I only use it with ES6.
These all work. But again, I can't figure out how to combine them
What I've tried
I tried my own solution:
In package.json I have:
"jest": {
"scriptPreprocessor": "<rootDir>/jest-script-preprocessor",
"unmockedModulePathPatterns": [
"<rootDir>/node_modules/react",
"<rootDir>/node_modules/react-dom",
"<rootDir>/node_modules/react-addons-test-utils",
"<rootDir>/node_modules/fbjs"
],
"testFileExtensions": ["coffee", "cjsx", "js", "jsx"],
"moduleFileExtensions": ["coffee", "cjsx", "js", "jsx"]
}
In jest-script-preprocessor.js, I have:
var coffee = require('coffee-react');
var transform = require('coffee-react-transform');
var babelJest = require("babel-jest");
module.exports = {
process: function(src, path) {
if (coffee.helpers.isCoffee(path)) {
console.log(path);
return coffee.compile(transform(src), {
'bare': true
});
} else {
console.log(path);
return babelJest.process(src, {
filename: path,
stage: 0
});
}
}
};
If I run a test like npm test __tests__/sometest.jsx, it loads the ES6 test file fine. That test file will import the module under test, which is also ES6, and THAT'S where it blows up. It simply says Unexpected reserved word as soon as it hits an ES6-only syntax, like import, export, etc. There is no additional line information, but I know it's ES6 that causes the problem because if I change the module under test to be ONLY export default 'mystring', it blows up, and if I change it to non-ES6 syntax like var q = 5 + 5; module.exports = q;, it imports the module fine. (Of course, that's not really a testable module, but it doesn't need to be for this proof-of-concept.)
Note the console.log() lines in there. I never see them. So one reason this has been so tricky to track down is I can't put any of my own debug logic in. I'm sure these lines run, because if I throw in some random syntax on those lines, it'll choke. But no console output.
I've tried jest-webpack-alias, which is officially recommended by jest, and it sounds great in theory: you use jest with webpack, which then allows you to use whatever preprocessors you've already set up. It gives me the same error of Unexpected reserved word. I wrote up an issue on their github repo.
Notes
I found jestpack, but I don't want to use it as it requires Node >= 5, and I want to use Node 4.2.3. It also doesn't work with Jest >= 0.8, and I want to use Jest 0.8, as it's currently the latest and I assume has the best chance of being in sync with the live docs and react version (0.14.6).
Here's what I'm doing that's working for me.
npm install --save-dev babel-jest
npm install --save-dev coffee-react
In package.json:
"jest": {
"scriptPreprocessor": "<rootDir>/jest-script-preprocessor",
"unmockedModulePathPatterns": [
"<rootDir>/node_modules/."
],
"testFileExtensions": ["coffee", "cjsx", "js", "jsx"],
"moduleFileExtensions": ["coffee", "cjsx", "js", "jsx"]
}
Take note of the unmockedModulePathPatterns. I set it to match everything in node_modules. You might not want that, but if you start getting errors like Error: Failed to get mock metadata:..., consider it, as recommended here.
In jest-script-preprocessor.js:
var babelJest = require('babel-jest');
var coffee = require('coffee-react');
module.exports = {
process: function(src, filename) {
if (filename.indexOf('node_modules') === -1) {
if (filename.match(/\.coffee|\.cjsx/)) {
src = coffee.compile(src, {bare: true});
} else {
src = babelJest.process(src, filename);
}
}
return src;
}
};

How to add custom javascript code to validate field in contacts module in sugarcrm

I want custom code to be made on onblur of first_name field in sugarcrm.
The code should also be upgrade safe.
Please help!
Copy modules/Contacts/metadata/editviewdefs.php
into
custom/modules/Contacts/metadata/editviewdefs.php
(if it does not already exist. If so, use the existing one)
All your changes in this file are upgrade safe. Now open your new file, and you'll see one big array containing everything that's in the EditView of the Contacts-module.
Add the following inside the "templateMeta" array, for instance, right after "form".
'includes'=> array(
array('file'=>'custom/modules/Contacts/EditView.js'),
),
This includes the file custom/modules/Contacts/EditView.js, in which you are free to write all the javascript you feel like!
Remember to do a Quick Repair & Rebuild when you are done.
I don't know which version of SugarCRM you uses, but in SugarCRM 7, the following works:
Create a file 'record.js' in /custom/modules/Contacts/clients/base/views/record/. In that file, you can add custom validation.
Some code you could use is:
({
extendsFrom: 'YourModuleRecordView',
initialize: function (options) {
app.error.errorName2Keys['field_error'] = 'This is an error message';
this._super('initialize', [options]);
this.model.addValidationTask('check_field', _.bind(this._doValidateField, this));
},
_doValidateField: function(fields, errors, callback) {
if (this.model.get('myField') .... ) {
errors['myField'] = errors['myField'] || {};
errors['myField'].field_error = true;
}
callback(null, fields, errors);
}
});
Don't forget to change the fields names like you named them!
This result is only for edit mode. To add this validation to the creation mode, add the file 'create_actions.js' to /custom/modules/Contacts/clients/base/views/create_actions/
Enter the folling code in your 'create_actions.js':
({
extendsFrom: 'CreateActionsView',
initialize: function (options) {
app.error.errorName2Keys['field_error'] = 'Thsis is an error message';
this._super('initialize', [options]);
this.model.addValidationTask('check_field', _.bind(this._doValidateField, this));
},
_doValidateField: function(fields, errors, callback) {
if (.....) {
errors['myField'] = errors['myField'] || {};
errors['myField'].field_error = true;
}
callback(null, fields, errors);
}
});
Perform a repair/rebuild when you added this files with the right code.
You can customize this code to your own needs.

Field validations in sugarcrm

I just started using SugarCRM CE for the first time (Version 6.5.15 (Build 1083)). I'm quite impressed with the ease of use when adding new fields or modules, but there's one quite indispensable thing that seems to be missing: Validation of user input.
I would for example like to check a lot of things:
Check if a emailadres has a valid format, using some regular expression
Check if a postalcode exists (maybe do a webswervice call to validate it)
Do a calculation to see if a citizen service number is valid
etc.
The only thing I seem to be able to do in studio is make a field required or not, there doesn't seem to be any standard way to execute a validation on a field.
All I can find when I google on it is lots of ways to hack into the source code, like this one: http://phpbugs.wordpress.com/2010/01/22/sugarcrm-adding-javascript-validation-on-form-submit/ And even then I don't find any examples that actually do a validation.
Am I just missing something? Or is editing source code the only way to add this?
I don't think the "standard" validations are available in the CE edition.
What surprises me is that you can't define a validation somewhere and attach it to a field. I kind of expected this, since the rest of the system is very well structured (modules, packages, etc..)
I now for instance created a 11-check, this is a very specific check for a dutch bank account number. to get this to work, I did the following (based upon examples I found googling around):
I added the bank account to contacts in studio and after that edited \custom\modules\Contacts\metadata\editviewdefs.php
I added the following snippets:
'includes'=> array(
array('file'=>'custom/modules/Contacts/customJavascript.js')),
array (
0 =>
array(
'customCode' =>
'<input title="Save [Alt+S]" accessKey="S" onclick="this.form.action.value=\'Save\'; return check_custom_data();" type="submit" name="button" value="'.$GLOBALS['app_strings']['LBL_SAVE_BUTTON_LABEL']>',
),
1 =>
array(
'customCode' =>
'<input title="Cancel [Alt+X]" accessKey="X" onclick="this.form.action.value=\'index\'; this.form.module.value=\''.$module_name.'\'; this.form.record.value=\'\';" type="submit" name="button" value="'.$GLOBALS['app_strings']['LBL_CANCEL_BUTTON_LABEL'].'">'
)
),
And in customJavascript.js i placed this code:
function check_custom_data()
{
if (!eleven_check(document.getElementById("bankaccount_c").value)){
alert ('Bank account not valid');
return false;
} else {
return check_form('EditView');
}
function eleven_check(bankaccount) {
bankaccount=bankaccount.replace(/\D/, "");
charcount=bankaccount.length;
var som=0;
for (i=1; i<10; i++) {
getal=bankaccount.charAt(i-1);
som+=getal*(10-i);
}
if (som % 11==0 && charcount==9) {
return true
} else {
return false
}
}
}
This check now works the way I want it to work, but I'm wondering if this is the best way to add a validation. this way of adding a validation doesn't however accommodate PHP validations, for instance, if I want to validate against some data in the database for one or another reason, I would have to use ajax calls to get that done.
Email validation is in the pro edition, I had assumed it was in CE as well but I'm not 100% sure.
The other 2 are a lot more specific - postcode validation would depend upon your country so would be difficult to roll out. For these you will need to write your own custom validation.
I know its late, but maybe still someone needs this.
You can just add your custom javascript validation as a callback in your vardefs like this:
'validation' =>
array (
'type' => 'callback',
'callback' => 'function(formname,nameIndex){if($("#" + nameIndex).val()!=999){add_error_style(formname,nameIndex,"Only 999 is allowed!"); return false;}; return true;}',
),
I documented it here as its not well documented elsewhere:
https://gunnicom.wordpress.com/2015/09/21/suitecrm-sugarcrm-6-5-add-custom-javascript-field-validation/
You can add custom validation code to the following file: ./custom/modules/.../clients/base/views/record/record.js
There you can add validation code. In this example, I will validate if the phone_number is not empty when an accounts has a customer-type:
EXAMPLE CODE IN RECORD.JS:
({
extendsFrom: 'RecordView',
initialize: function (options) {
app.view.invokeParent(this, {type: 'view', name: 'record', method: 'initialize', args:[options]});
//add validation
this.model.addValidationTask('check_account_type', _.bind(this._doValidateCheckType, this));
},
_doValidateCheckType: function(fields, errors, callback) {
//validate requirements
if (this.model.get('account_type') == 'Customer' && _.isEmpty(this.model.get('phone_office')))
{
errors['phone_office'] = errors['phone_office'] || {};
errors['phone_office'].required = true;
}
callback(null, fields, errors);
}
})
Don't forget to repair en rebuild!
The full documentation can be found here

Incrementally update Kendo UI autocomplete

I have a Kendo UI autocomplete bound to a remote transport that I need to tweak how it works and am coming up blank.
Currently, I perform a bunch of searches on the server and integrate the results into a JSON response and then return this to the datasource for the autocomplete. The problem is that this can take a long time and our application is time sensitive.
We have identified which searches are most important and found that 1 search accounts for 95% of the chosen results. However, I still need to provide the data from the other searches. I was thinking of kicking off separate requests for data on the server and adding them the autocomplete as they return. Our main search returns extremely fast and would be the first items added to the list. Then as the other searches return, I would like them to add dynamically to the list.
Our application uses knockout.js and I thought about making the datasource part of our view model, but from looking around, Kendo doesn't update based on changes to your observables.
I am currently stumped and any advice would be welcomed.
Edit:
I have been experimenting and have had some success simulating what I want with the following datasource:
var dataSource = new kendo.data.DataSource({
transport: {
read: {
url: window.performLookupUrl,
data: function () {
return {
param1: $("#Input").val()
};
}
},
parameterMap: function (options) {
return {
param1: options.param1
};
}
},
serverFiltering: true,
serverPaging: true,
requestEnd: function (e) {
if (e.type == "read") {
window.setTimeout(function() {
dataSource.add({ Name: "testin1234", Id: "X1234" })
}, 2000);
}
}
});
If the first search returns results, then after 2 seconds, a new item pops into the list. However, if the first search fails, then nothing happens. Is it proper to use (abuse??) the requestEnd like this? My eventual goal is to kick off the rest of the searches from this function.
I contacted Telerik and they gave me the following jsbin that I was able to modify to suit my needs.
http://jsbin.com/ezucuk/5/edit