How to document functions within a module using jsdoc? - documentation

/**
* Displays the list of autolab commands along with their functions.
* #module lib/help
*/
var Table = require('cli-table');
var chalk = require('chalk');
var helpjson = {
'init' : 'Initializes local repository and authenticates',
'exit' : 'Wipes off the credentials from the system',
'git create' : 'Creates a repository on Gitlab',
'git delete' : 'Deletes the specified repository from Gitlab',
'git changeserver' : 'To change the host of Gitlab',
'git changelang' : 'To change the language of the code submission',
'git push' : 'Adds, commits, pushes the code',
'submit' : 'To submit the code to JavaAutolab and fetch the results',
'help' : 'Print help manual'
};
module.exports = function() {
/**
* Displays the list of autolab commands along with their functions.
* #function
* #param {null}
*/
console.log('\n' + chalk.blue('Usage:') + ' autolab [OPTIONS]');
var table = new Table({
head: ['Options:', ''],
colWidths: [20,70]
});
for (var key in helpjson)
table.push(
[key,helpjson[key]]
);
console.log(table.toString());
};
I tried this but the html page only shows lib/help and then a blank page. I also wanted to use #exports to mention what the module exports. Also is there a way to document the purpose and overview of the object in JSDoc.

JSDoc comment block should be before your function declaration...
/**
* Displays the list of autolab commands along with their functions.
* #module lib/help
*/
var Table = require('cli-table');
var chalk = require('chalk');
var helpjson = {
'init': 'Initializes local repository and authenticates',
'exit': 'Wipes off the credentials from the system',
'git create': 'Creates a repository on Gitlab',
'git delete': 'Deletes the specified repository from Gitlab',
'git changeserver': 'To change the host of Gitlab',
'git changelang': 'To change the language of the code submission',
'git push': 'Adds, commits, pushes the code',
'submit': 'To submit the code to JavaAutolab and fetch the results',
'help': 'Print help manual'
};
/**
* Displays the list of autolab commands along with their functions.
* #function
* #param {null}
*/
module.exports = function () {
console.log('\n' + chalk.blue('Usage:') + ' autolab [OPTIONS]');
var table = new Table({
head: ['Options:', ''],
colWidths: [20, 70]
});
for (var key in helpjson)
table.push(
[key, helpjson[key]]
);
console.log(table.toString());
};
Also is there a way to document the purpose and overview of the object in JSDoc
The #file tag provides a description for a file. Use the tag in a JSDoc comment at the beginning of the file.
Try to get familiar with JSDoc by reading a bit more of documentation.

Related

Drupal 8: When I update the node field to a specific value, how to call my module (managefinishdate.module) to update another field?

I am having a node type with machine name to_do_item, and I want to create a module called managefinishdate to update the node: when a user edit the node's field (field_status) to "completed" and click "save", then the module will auto update the field_date_finished to current date.
I have tried to create the module and already success to install in "Extend":
function managefinishdate_todolist_update(\Drupal\Core\Entity\EntityInterface $entity) {
...
}
however, I am not sure is this module being called, because whatever I echo inside, seems nothing appeared.
<?php
use Drupal\Core\Entity\EntityInterface;
use Drupal\node\Entity\Node;
/** * Implements hook_ENTITY_TYPE_update().
* If a user update status to Completed,
* update the finished date as save date
*/
function managefinishdate_todolist_update(\Drupal\Core\Entity\EntityInterface $entity) {
$node = \Drupal::routeMatch()->getParameter('node');
print_r($node);
//$entity_type = 'node';
//$bundles = ['to_do_item'];
//$fld_finishdate = 'field_date_finished';
//if ($entity->getEntityTypeId() != $entity_type || !in_array($entity->bundle(), $bundles)) {
//return;
//}
//$current_date=date("Y-m-d");
//$entity->{$fld_finishdate}->setValue($current_date);
}
Following Drupal convention, your module named 'manage_finish_date' should contain a 'manage_finish_date.module file that sits in the root directory that should look like this:
<?php
use Drupal\node\Entity\Node;
/**
* Implements hook_ENTITY_TYPE_insert().
*/
function manage_finish_date_node_insert(Node $node) {
ManageFinishDate::update_time();
}
/**
* Implements hook_ENTITY_TYPE_update().
*/
function manage_finish_date_node_update(Node $node) {
ManageFinishDate::update_time();
}
You should also have another file called 'src/ManageFinishDate.php' that should look like this:
<?php
namespace Drupal\manage_finish_date;
use Drupal;
use Drupal\node\Entity\Node;
class ManageFinishDate {
public static function update_time($node, $action = 'create') {
// Entity bundles to act on
$bundles = array('to_do_item');
if (in_array($node->bundle(), $bundles)) {
// Load the node and update
$status = $node->field_status->value;
$node_to_update = Node::load($node);
if ($status == 'completed') {
$request_time = Drupal::time();
$node_to_update->set('field_date_finished', $request_time);
$node_to_update->save();
}
}
}
}
The code is untested, but should work. Make sure that the module name, and namespace match as well as the class filename and class name match for it to work. Also, clear you cache once uploaded.
This will handle newly created and updated nodes alike.
Please look after this sample code which may help you:
function YOUR_MODULE_entity_presave(Drupal\Core\Entity\EntityInterface $entity) {
switch ($entity->bundle()) {
//Replace CONTENT_TYPE with your actual content type
case 'CONTENT_TYPE':
$node = \Drupal::routeMatch()->getParameter('node');
if ($node instanceof \Drupal\node\NodeInterface) {
// Set the current date
}
break;
}
}

Behat (+ Mink) Check for some text followed by some text (in sibling elements)

The I should see... function is an essential feature of Behat but I regularly find myself wanting to write something like this in my scenarios:
Then I should see "Session ID" followed by "3"
Which is my humanly-parsable way of describing 2 pieces of text next to each other in the content. That is to say the first string is the content of any element and the second is the content of it's next immediate sibling.
This would be useful for checking label - value type layouts:
Or if I want to check header - cell value type layouts in tabulated data:
Or even definition title - definition.
Obviously I could add 'id' attributes to every element I want to test but in a complicated page where many parts of the content need testing this starts to feel like I am bloating the markup with single-use attributes.
To be able to use...
Then I should see "Session ID" followed by "3"
Add the following methods to your FeatureContext.php file:
/**
* #Then I should see :textA followed by :textB
*/
public function iShouldSeeFollowedBy($textA, $textB)
{
$content = $this->getSession()->getPage()->getContent();
// Get rid of stuff between script tags
$content = $this->removeContentBetweenTags('script', $content);
// ...and stuff between style tags
$content = $this->removeContentBetweenTags('style', $content);
$content = preg_replace('/<[^>]+>/', ' ',$content);
// Replace line breaks and tabs with a single space character
$content = preg_replace('/[\n\r\t]+/', ' ',$content);
$content = preg_replace('/ {2,}/', ' ',$content);
if (strpos($content,$textA) === false) {
throw new Exception(sprintf('"%s" was not found in the page', $textA));
}
$seeking = $textA . ' ' . $textB;
if (strpos($content,$textA . ' ' . $textB) === false) {
// Be helpful by finding the 10 characters that did follow $textA
preg_match('/' . $textA . ' [^ ]+/',$content,$matches);
throw new Exception(sprintf('"%s" was not found, found "%s" instead', $seeking, $matches[0]));
}
}
/**
* #param string $tagName - The name of the tag, eg. 'script', 'style'
* #param string $content
*
* #return string
*/
private function removeContentBetweenTags($tagName,$content)
{
$parts = explode('<' . $tagName, $content);
$keepers = [];
// We always want to keep the first part
$keepers[] = $parts[0];
foreach ($parts as $part) {
$subparts = explode('</' . $tagName . '>', $part);
if (count($subparts) > 1) {
$keepers[] = $subparts[1];
}
}
return implode('', $keepers);
}

TYPO3 6.2 - how to create FileReference in frontend (FE)?

I have the hypothetical Zoo extension in which I've Animal model with photo field and FrontEnd (FE) plugin with typical CRUD actions. photo field is typical FAL's FileReference and it works perfectly in backend (BE) with common TCA IRRE config.
I'm able to successful upload the file to the storage, it's visible in the Filelist module, and I can use it in BE during my Animal editing, anyway I can't create FileReference within my FE plugin.
My current approach looks like this:
/**
* #param \Zoo\Zoo\Domain\Model\Animal $animal
*/
public function updateAction(\Zoo\Zoo\Domain\Model\Animal $animal) {
// It reads proper uploaded `photo` from form's $_FILES
$file = $this->getFromFILES('tx_zoo_animal', 'photo');
if ($file && is_array($file) && $file['error'] == 0) {
/** #type $storageRepository \TYPO3\CMS\Core\Resource\StorageRepository */
$storageRepository = GeneralUtility::makeInstance('\TYPO3\CMS\Core\Resource\StorageRepository');
$storage = $storageRepository->findByUid(5); // TODO: make target storage configurable
// This adds uploaded file to the storage perfectly
$fileObject = $storage->addFile($file['tmp_name'], $storage->getRootLevelFolder(), $file['name']);
// Here I stuck... below line doesn't work (throws Exception no. 1 :/)
// It's 'cause $fileObject is type of FileInterface and FileReference is required
$animal->addPhoto($fileObject);
}
$this->animalRepository->update($animal);
$this->redirect('list');
}
anyway attempt to create reference by this line throws exception:
$animal->addPhoto($fileObject);
How can I resolve this?
Checked: DataHandler approach (link) won't work also, as it's unavailable for FE users.
TL;DR
How to add FileReference to Animal model from existing (just created) FAL record?
You need to do several things. This issue on forge is where I got the info, and some stuff is taken out of Helmut Hummels frontend upload example (and the accompanying blogpost) which #derhansen already commented.
I'm not entirely sure if this is everything you need, so feel free to add things. This does not use a TypeConverter, which you should probably do. That would open further possibilities, for example it would be easily possible to implement deletion and replacement of file references.
You need to:
Create a FAL file reference object from the File object. This can be done using FALs resource factory.
Wrap it in a \TYPO3\CMS\Extbase\Domain\Model\FileReference (method ->setOriginalResource)
EDIT: This step is unnecessary as of TYPO3 6.2.11 and 7.2, you can directly use the class \TYPO3\CMS\Extbase\Domain\Model\FileReference.
But, because the extbase model misses a field ($uidLocal) in 6.2.10rc1, that won't work. You need to inherit from the extbase model, add that field, and fill it. Don't forget to add a mapping in TypoScript to map your own model to sys_file_reference.
config.tx_extbase.persistence.classes.Zoo\Zoo\Domain\Model\FileReference.mapping.tableName = sys_file_reference
The class would look like this (taken from the forge issue):
class FileReference extends \TYPO3\CMS\Extbase\Domain\Model\FileReference {
/**
* We need this property so that the Extbase persistence can properly persist the object
*
* #var integer
*/
protected $uidLocal;
/**
* #param \TYPO3\CMS\Core\Resource\ResourceInterface $originalResource
*/
public function setOriginalResource(\TYPO3\CMS\Core\Resource\ResourceInterface $originalResource) {
$this->originalResource = $originalResource;
$this->uidLocal = (int)$originalResource->getUid();
}
}
Add this to the TCA of the image field, in the config-section (adapt to your table and field names of course):
'foreign_match_fields' => array(
'fieldname' => 'photo',
'tablenames' => 'tx_zoo_domain_model_animal',
'table_local' => 'sys_file',
),
EDIT: Use \TYPO3\CMS\Extbase\Domain\Model\FileReference in this step if on TYPO3 6.2.11 or 7.2 or above.
So at the end add the created $fileRef instead of $fileObject
$fileRef = GeneralUtility::makeInstance('\Zoo\Zoo\Domain\Model\FileReference');
$fileRef->setOriginalResource($fileObject);
$animal->addPhoto($fileRef);
Don't tell anyone what you have done.
Here is the complete function to upload file in TYPO3 using FAL and create filereference
/**
* Function to upload file and create file reference
*
* #var array $fileData
* #var mixed $obj foreing model object
*
* #return void
*/
private function uploadAndCreateFileReference($fileData, $obj) {
$storageUid = 2;
$resourceFactory = \TYPO3\CMS\Core\Resource\ResourceFactory::getInstance();
//Adding file to storage
$storage = $resourceFactory->getStorageObject($storageUid);
if (!is_object($storage)) {
$storage = $resourceFactory->getDefaultStorage();
}
$file = $storage->addFile(
$fileData['tmp_name'],
$storage->getRootLevelFolder(),
$fileData['name']
);
//Creating file reference
$newId = uniqid('NEW_');
$data = [];
$data['sys_file_reference'][$newId] = [
'table_local' => 'sys_file',
'uid_local' => $file->getUid(),
'tablenames' => 'tx_imageupload_domain_model_upload', //foreign table name
'uid_foreign' => $obj->getUid(),
'fieldname' => 'image', //field name of foreign table
'pid' => $obj->getPid(),
];
$data['tx_imageupload_domain_model_upload'][$obj->getUid()] = [
'image' => $newId,
];
$dataHandler = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance(
'TYPO3\CMS\Core\DataHandling\DataHandler'
);
$dataHandler->start($data, []);
}
where $filedata =
$this->request->getArgument('file_input_field_name');
And
$obj = //Object of your model for which you are creating file
reference
This example does not deserve a beauty prize but it might help you. It works in 7.6.x
private function uploadLogo(){
$file['name'] = $_FILES['logo']['name'];
$file['type'] = $_FILES['logo']['type'];
$file['tmp_name'] = $_FILES['logo']['tmp_name'];
$file['size'] = $_FILES['logo']['size'];
// Store the image
$resourceFactory = \TYPO3\CMS\Core\Resource\ResourceFactory::getInstance();
$storage = $resourceFactory->getDefaultStorage();
$saveFolder = $storage->getFolder('logo-companies/');
$newFile = $storage->addFile(
$file['tmp_name'],
$saveFolder,
$file['name']
);
// remove earlier refereces
$GLOBALS['TYPO3_DB']->exec_DELETEquery('sys_file_reference', 'uid_foreign = '. $this->getCurrentUserCompanyID());
$addressRecord = $this->getUserCompanyAddressRecord();
// Create new reference
$data = array(
'table_local' => 'sys_file',
'uid_local' => $newFile->getUid(),
'tablenames' => 'tt_address',
'uid_foreign' => $addressRecord['uid'],
'fieldname' => 'image',
'pid' => $addressRecord['pid']
);
$GLOBALS['TYPO3_DB']->exec_INSERTquery('sys_file_reference', $data);
$newId = $GLOBALS['TYPO3_DB']->sql_insert_id();
$where = "tt_address.uid = ".$addressRecord['uid'];
$GLOBALS['TYPO3_DB']->exec_UPDATEquery('tt_address', $where, array('image' => $newId ));
}

Get pdf-attachments from Gmail as text

I searched around the web & Stack Overflow but didn't find a solution. What I try to do is the following: I get certain attachments via mail that I would like to have as (Plain) text for further processing. My script looks like this:
function MyFunction() {
var threads = GmailApp.search ('label:templabel');
var messages = GmailApp.getMessagesForThreads(threads);
for (i = 0; i < messages.length; ++i)
{
j = messages[i].length;
var messageBody = messages[i][0].getBody();
var messageSubject = messages [i][0].getSubject();
var attach = messages [i][0].getAttachments();
var attachcontent = attach.getContentAsString();
GmailApp.sendEmail("mail", messageSubject, "", {htmlBody: attachcontent});
}
}
Unfortunately this doesn't work. Does anybody here have an idea how I can do this? Is it even possible?
Thank you very much in advance.
Best, Phil
Edit: Updated for DriveApp, as DocsList deprecated.
I suggest breaking this down into two problems. The first is how to get a pdf attachment from an email, the second is how to convert that pdf to text.
As you've found out, getContentAsString() does not magically change a pdf attachment to plain text or html. We need to do something a little more complicated.
First, we'll get the attachment as a Blob, a utility class used by several Services to exchange data.
var blob = attachments[0].getAs(MimeType.PDF);
So with the second problem separated out, and maintaining the assumption that we're interested in only the first attachment of the first message of each thread labeled templabel, here is how myFunction() looks:
/**
* Get messages labeled 'templabel', and send myself the text contents of
* pdf attachments in new emails.
*/
function myFunction() {
var threads = GmailApp.search('label:templabel');
var threadsMessages = GmailApp.getMessagesForThreads(threads);
for (var thread = 0; thread < threadsMessages.length; ++thread) {
var message = threadsMessages[thread][0];
var messageBody = message.getBody();
var messageSubject = message.getSubject();
var attachments = message.getAttachments();
var blob = attachments[0].getAs(MimeType.PDF);
var filetext = pdfToText( blob, {keepTextfile: false} );
GmailApp.sendEmail(Session.getActiveUser().getEmail(), messageSubject, filetext);
}
}
We're relying on a helper function, pdfToText(), to convert our pdf blob into text, which we'll then send to ourselves as a plain text email. This helper function has a variety of options; by setting keepTextfile: false, we've elected to just have it return the text content of the PDF file to us, and leave no residual files in our Drive.
pdfToText()
This utility is available as a gist. Several examples are provided there.
A previous answer indicated that it was possible to use the Drive API's insert method to perform OCR, but it didn't provide code details. With the introduction of Advanced Google Services, the Drive API is easily accessible from Google Apps Script. You do need to switch on and enable the Drive API from the editor, under Resources > Advanced Google Services.
pdfToText() uses the Drive service to generate a Google Doc from the content of the PDF file. Unfortunately, this contains the "pictures" of each page in the document - not much we can do about that. It then uses the regular DocumentService to extract the document body as plain text.
/**
* See gist: https://gist.github.com/mogsdad/e6795e438615d252584f
*
* Convert pdf file (blob) to a text file on Drive, using built-in OCR.
* By default, the text file will be placed in the root folder, with the same
* name as source pdf (but extension 'txt'). Options:
* keepPdf (boolean, default false) Keep a copy of the original PDF file.
* keepGdoc (boolean, default false) Keep a copy of the OCR Google Doc file.
* keepTextfile (boolean, default true) Keep a copy of the text file.
* path (string, default blank) Folder path to store file(s) in.
* ocrLanguage (ISO 639-1 code) Default 'en'.
* textResult (boolean, default false) If true and keepTextfile true, return
* string of text content. If keepTextfile
* is false, text content is returned without
* regard to this option. Otherwise, return
* id of textfile.
*
* #param {blob} pdfFile Blob containing pdf file
* #param {object} options (Optional) Object specifying handling details
*
* #returns {string} id of text file (default) or text content
*/
function pdfToText ( pdfFile, options ) {
// Ensure Advanced Drive Service is enabled
try {
Drive.Files.list();
}
catch (e) {
throw new Error( "To use pdfToText(), first enable 'Drive API' in Resources > Advanced Google Services." );
}
// Set default options
options = options || {};
options.keepTextfile = options.hasOwnProperty("keepTextfile") ? options.keepTextfile : true;
// Prepare resource object for file creation
var parents = [];
if (options.path) {
parents.push( getDriveFolderFromPath (options.path) );
}
var pdfName = pdfFile.getName();
var resource = {
title: pdfName,
mimeType: pdfFile.getContentType(),
parents: parents
};
// Save PDF to Drive, if requested
if (options.keepPdf) {
var file = Drive.Files.insert(resource, pdfFile);
}
// Save PDF as GDOC
resource.title = pdfName.replace(/pdf$/, 'gdoc');
var insertOpts = {
ocr: true,
ocrLanguage: options.ocrLanguage || 'en'
}
var gdocFile = Drive.Files.insert(resource, pdfFile, insertOpts);
// Get text from GDOC
var gdocDoc = DocumentApp.openById(gdocFile.id);
var text = gdocDoc.getBody().getText();
// We're done using the Gdoc. Unless requested to keepGdoc, delete it.
if (!options.keepGdoc) {
Drive.Files.remove(gdocFile.id);
}
// Save text file, if requested
if (options.keepTextfile) {
resource.title = pdfName.replace(/pdf$/, 'txt');
resource.mimeType = MimeType.PLAIN_TEXT;
var textBlob = Utilities.newBlob(text, MimeType.PLAIN_TEXT, resource.title);
var textFile = Drive.Files.insert(resource, textBlob);
}
// Return result of conversion
if (!options.keepTextfile || options.textResult) {
return text;
}
else {
return textFile.id
}
}
The conversion to DriveApp is helped with this utility from Bruce McPherson:
// From: http://ramblings.mcpher.com/Home/excelquirks/gooscript/driveapppathfolder
function getDriveFolderFromPath (path) {
return (path || "/").split("/").reduce ( function(prev,current) {
if (prev && current) {
var fldrs = prev.getFoldersByName(current);
return fldrs.hasNext() ? fldrs.next() : null;
}
else {
return current ? null : prev;
}
},DriveApp.getRootFolder());
}

Fiddler: Programmatically add word to Query string

Please be kind, I'm new to Fiddler
My purpose:I want to use Fiddler as a Google search filter
Summary:
I'm tired of manually adding "dog" every time I use Google.I do not want the "dog" appearing in my search results.
For example:
//www.google.com/search?q=cat+-dog
//www.google.com/search?q=baseball+-dog
CODE:
dog replaced with -torrent-watch-download
// ==UserScript==
// #name Tamper with Google Results
// #namespace http://superuser.com/users/145045/krowe
// #version 0.1
// #description This just modifies google results to exclude certain things.
// #match http://*.google.com
// #match https://*.google.com
// #copyright 2014+, KRowe
// ==/UserScript==
function GM_main () {
window.onload = function () {
var targ = window.location;
if(targ && targ.href && targ.href.match('https?:\/\/www.google.com/.+#q=.+') && targ.href.search("/+-torrent/+-watch/+-download")==-1) {
targ.href = targ.href +"+-torrent+-watch+-download";
}
};
}
//-- This is a standard-ish utility function:
function addJS_Node(text, s_URL, funcToRun, runOnLoad) {
var D=document, scriptNode = D.createElement('script');
if(runOnLoad) scriptNode.addEventListener("load", runOnLoad, false);
scriptNode.type = "text/javascript";
if(text) scriptNode.textContent = text;
if(s_URL) scriptNode.src = s_URL;
if(funcToRun) scriptNode.textContent = '(' + funcToRun.toString() + ')()';
var targ = D.getElementsByTagName('head')[0] || D.body || D.documentElement;
targ.appendChild(scriptNode);
}
addJS_Node (null, null, GM_main);
At first I was going to go with Tampermonkey userscripts,Because I did not know about Fiddler
==================================================================================
Now,lets focus on Fiddler
Before Request:
I want Fiddler to add text at the end of Google Query string.
Someone suggested me to use
static function OnBeforeRequest(oSession: Session) {
if (oSession.uriContains("targetString")) {
var sText = "Enter a string to append to a URL";
oSession.fullUrl = oSession.fullUrl + sText;
}
}
Before Response:
This is where my problem lies
I totally love the HTML response,Now I just want to scrape/hide the word in the search box without changing the search results.How can it be done? Any Ideas?
http://i.stack.imgur.com/4mUSt.jpg
Can you guys please take the above information and fix the problem for me
Thank you
Basing on goal definition above, I believe you can achieve better results with your own free Google custom search engine service. In particular, because you have control over GCSE fine-tuning results, returned by regular Google search.
Links:
https://www.google.com/cse/all
https://developers.google.com/custom-search/docs/structured_search