Best JavaScript code snippet using best
extension.ts
Source:extension.ts
1// The module 'vscode' contains the VS Code extensibility API2// Import the module and reference it with the alias vscode in your code below3import * as vscode from 'vscode';4import * as Octokit from "@octokit/rest";5import { RemoteHubApi } from './remotehubApi';6type Commit = {7 oid: string8 authoredDate: string9 message: string10 url: string11 author: {12 name: string13 user: {14 url: string15 avatarUrl: string16 }17 }18};19type BlameResult = {20 repository: {21 object: {22 blame: {23 ranges: {24 startingLine: number25 endingLine: number26 age: number27 commit: {28 oid: string,29 message: string30 authoredDate: string31 url: string32 author: {33 name: string34 user: {35 url: string36 avatarUrl: string37 }38 }39 }40 }[]41 }42 }43 }44};45const makeQuery = (name: string, owner: string, ref: string, path: string) => `46query {47 repository(name: "${name}", owner:"${owner}") {48 object(expression: "${ref}") {49 ... on Commit {50 blame(path: "${path}") {51 ranges {52 startingLine53 endingLine54 age55 commit {56 oid57 message58 authoredDate59 url60 author {61 name62 user {63 url64 avatarUrl65 }66 }67 }68 }69 }70 }71 }72 }73}`;74const cache: Map<string, Promise<BlameResult | undefined>> = new Map();75const getBlameForUri = async (uri: vscode.Uri, cancellation?: vscode.CancellationToken): Promise<BlameResult | undefined> => {76 const cacheKey = uri.toString();77 if (cache.has(cacheKey)) { return cache.get(cacheKey); }78 const resolver = new Promise<BlameResult | undefined>(async (c, e) => {79 try {80 const token = await vscode.authentication.getSession('github', ['repo'], { createIfNone: true });81 if (cancellation?.isCancellationRequested) { return undefined; }82 const octokit = new Octokit.Octokit({ auth: token?.accessToken });83 const remotehub = (await vscode.extensions.getExtension('github.remotehub')?.activate()) as RemoteHubApi;84 const meta = await remotehub.getMetadata(uri);85 const revision = await meta?.getRevision() as { revision: string };86 if (cancellation?.isCancellationRequested) { return undefined; }87 const providerUri = remotehub.getProviderUri(uri);88 const [_, owner, repo, path] = /^\/([^/]*)\/([^/]*)\/(.*)$/.exec(providerUri.path)!;89 const query = makeQuery(repo, owner, revision.revision, path,);90 const data: BlameResult = await octokit.graphql(query);91 if (data.repository.object.blame.ranges) {92 cache.set(cacheKey, Promise.resolve(data));93 c(data);94 }95 } catch (err) {96 cache.delete(cacheKey);97 e(err);98 }99 });100 cache.set(cacheKey, resolver);101 return resolver;102};103export async function activate(context: vscode.ExtensionContext) {104 let dis = false;105 const remotehub = (await vscode.extensions.getExtension('github.remotehub')?.activate()) as RemoteHubApi;106 vscode.languages.registerHoverProvider({ scheme: 'vscode-vfs' }, {107 async provideHover(document, position, token) {108 if (!dis) { return undefined; }109 const data = await getBlameForUri(document.uri, token);110 if (!data) { return undefined; }111 const range = data.repository.object.blame.ranges.find((range) =>112 range.startingLine <= position.line && range.endingLine >= position.line113 );114 const providerUri = remotehub.getProviderUri(document.uri);115 const [_, owner, repo, path] = /^\/([^/]*)\/([^/]*)\/(.*)$/.exec(providerUri.path)!;116 const renderCommit = (commit: Commit) => {117 let str = `[${commit.author.name}](${commit.author.user.url}) *[(${commit.oid.slice(0, 6)})](${commit.url})*: ${commit.message}`;118 str = str.replace(/#(\d+)/g, (_, num) => `[#${num}](https://github.com/${owner}/${repo}/issues/${num})`);119 return str;120 };121 if (range) {122 return {123 contents: [new vscode.MarkdownString(renderCommit(range.commit))]124 };125 }126 }127 });128 const colors = [129 '#ff941a',130 '#f0843d',131 '#e07352',132 '#d06266',133 '#bd5175',134 '#a94285',135 '#7c21a6',136 '#5910b2',137 '#953295',138 '#0000c2',139 '#000000',140 ];141 const decorations = Array.from({ length: 11 }).map((_, i) =>142 vscode.window.createTextEditorDecorationType({ overviewRulerLane: vscode.OverviewRulerLane.Right, overviewRulerColor: colors[i], rangeBehavior: vscode.DecorationRangeBehavior.ClosedClosed })143 );144 const showHeatForEditor = async (e: vscode.TextEditor) => {145 if (!dis) {146 for (const [i, dec] of Object.entries(decorations)) {147 e.setDecorations(decorations[+i], []);148 }149 return undefined;150 }151 if (e) {152 const data = await getBlameForUri(e.document.uri);153 if (!data) { return undefined; }154 const editorDecorations: { line: number }[][] = Array.from({ length: 11 }).map(() => []);155 data.repository.object.blame.ranges.forEach(range => {156 for (let line = range.startingLine - 1; line <= range.endingLine - 1; line++) {157 editorDecorations[range.age]?.push({ line });158 }159 });160 for (const [i, dec] of Object.entries(editorDecorations)) {161 e.setDecorations(decorations[+i], dec.map(d => new vscode.Range(d.line, 0, d.line, 10000)));162 }163 }164 };165 // vscode.window.166 vscode.window.onDidChangeActiveTextEditor(async (e) => {167 if (e) {168 showHeatForEditor(e);169 }170 });171 context.subscriptions.push(...[172 vscode.commands.registerCommand('remote-blame.showBlame', async () => {173 dis = true;174 const e = vscode.window.activeTextEditor;175 if (e) { await showHeatForEditor(e); }176 vscode.commands.executeCommand('setContext', 'blameShowing', true);177 }),178 vscode.commands.registerCommand('remote-blame.hideBlame', async () => {179 dis = false;180 const e = vscode.window.activeTextEditor;181 if (e) { await showHeatForEditor(e); }182 vscode.commands.executeCommand('setContext', 'blameShowing', false);183 }),184 { dispose() { cache.clear(); } }]);185}...
slow_train_remote.js
Source:slow_train_remote.js
1/*2 *3 * This example allows you to connect Vernie and a Powered UP Remote Control to your laptop, and enables the control of Vernie with the Remote.4 *5 */6const PoweredUP = require("/usr/local/lib/node_modules/node-poweredup");7const poweredUP = new PoweredUP.PoweredUP();8poweredUP.scan(); // Start scanning9console.log("Looking for train and remote...");10const TRAIN_LED_COLOR = PoweredUP.Consts.Color.PURPLE;11let trainHub = null;12let trainMotor = null;13let remoteHub = null;14let remoteButtonLeft = null;15let remoteButtonRight = null;16let currentSpeed = 0;17poweredUP.on("discover", async (hub) => { // Wait to discover Vernie and Remote18 if (hub.type === PoweredUP.Consts.HubType.HUB) {19 console.log("hub found. connecting...");20 trainHub = hub;21 await trainHub.connect();22 console.log("connected. waiting for LED device...");23 const led = await trainHub.waitForDeviceByType(PoweredUP.Consts.DeviceType.HUB_LED);24 console.log("found. waiting for motor device...");25 trainMotor = await trainHub.waitForDeviceByType(PoweredUP.Consts.DeviceType.TRAIN_MOTOR);26 console.log("found. setting LED color...");27 led.setColor(TRAIN_LED_COLOR);28 console.log(`Connected to train (${trainHub.name})!`);29 if (trainHub && remoteHub) {30 console.log("You're now ready to go!");31 }32 } else if (hub.type === PoweredUP.Consts.HubType.REMOTE_CONTROL) {33 remoteHub = hub;34 await remoteHub.connect();35 const led = await remoteHub.waitForDeviceByType(PoweredUP.Consts.DeviceType.HUB_LED);36 remoteButtonLeft = await remoteHub.waitForDeviceAtPort("LEFT");37 remoteButtonRight = await remoteHub.waitForDeviceAtPort("RIGHT");38 led.setColor(TRAIN_LED_COLOR);39 remoteButtonLeft.on("remoteButton", ({ event }) => {40 if (trainMotor) {41 if (event === PoweredUP.Consts.ButtonState.UP) {42 currentSpeed += 10;43 } else if (event === PoweredUP.Consts.ButtonState.DOWN) {44 currentSpeed -= 10;45 } else if (event === PoweredUP.Consts.ButtonState.STOP) {46 currentSpeed = 0;47 }48 trainMotor.setPower(currentSpeed);49 }50 });51 remoteButtonRight.on("remoteButton", ({ event }) => {52 if (trainMotor) {53 if (event === PoweredUP.Consts.ButtonState.UP) {54 currentSpeed += 1;55 } else if (event === PoweredUP.Consts.ButtonState.DOWN) {56 currentSpeed -= 1;57 } else if (event === PoweredUP.Consts.ButtonState.STOP) {58 currentSpeed = 0;59 }60 trainMotor.setPower(currentSpeed);61 }62 });63 console.log(`Connected to remote (${remoteHub.name})!`);64 if (trainHub && remoteHub) {65 console.log("You're now ready to go!");66 }67 } else {68 console.log(`hub type of ${hub.type} found`);69 }70 ...
remoteRepositories.ts
Source:remoteRepositories.ts
1/* --------------------------------------------------------------------------------------------2 * Copyright (c) Microsoft Corporation. All rights reserved.3 * Licensed under the MIT License. See License.txt in the project root for license information.4 * ------------------------------------------------------------------------------------------ */5import { Extension, extensions, Uri, workspace } from 'vscode';6export interface RemoteHubApi {7 getProviderUri(uri: Uri): Uri;8 getProviderRootUri(uri: Uri): Uri;9 getVirtualUri(uri: Uri): Uri;10 getVirtualWorkspaceUri(uri: Uri): Uri | undefined;11 loadWorkspaceContents?(workspaceUri: Uri): Promise<boolean>;12}13namespace RemoteRepositories {14 let remoteHub: Extension<RemoteHubApi> | undefined;15 function getRemoteExtension(): Extension<RemoteHubApi> {16 if (remoteHub !== undefined) {17 return remoteHub;18 }19 remoteHub = extensions.getExtension<RemoteHubApi>('ms-vscode.remote-repositories')20 ?? extensions.getExtension<RemoteHubApi>('GitHub.remoteHub')21 ?? extensions.getExtension<RemoteHubApi>('GitHub.remoteHub-insiders');22 if (remoteHub === undefined) {23 throw new Error(`No Remote repository extension found.`);24 }25 return remoteHub;26 }27 export function getApi(): Thenable<RemoteHubApi> {28 return getRemoteExtension().activate();29 }30}...
Using AI Code Generation
1var request = require('request');2var xml2js = require('xml2js');3var fs = require('fs');4var async = require('async');5var csv = require('csv');6var _ = require('underscore');7var Q = require('q');8var xml2js = require('xml2js');
Using AI Code Generation
1var request = require('request');2var fs = require('fs');3request(url, function(err, resp, body){4 if(err){5 console.log(err);6 }7 else{8 var data = JSON.parse(body);9 var stores = data.stores;10 var storeList = [];11 for(var i=0; i<stores.length; i++){12 var store = stores[i];13 var storeInfo = {14 };15 storeList.push(storeInfo);16 }17 fs.writeFile('stores.json', JSON.stringify(storeList), function(err){18 if(err){19 console.log(err);20 }21 else{22 console.log('file saved');23 }24 });25 }26});
Using AI Code Generation
1const rp = require('request-promise');2const cheerio = require('cheerio');3rp(url)4 .then(function(html){5 let $ = cheerio.load(html);6 console.log($('title').text());7 })8 .catch(function(err){9 console.log(err);10 });11const rp = require('request-promise');12const cheerio = require('cheerio');13rp(url)14 .then(function(html){15 let $ = cheerio.load(html);16 console.log($('title').text());17 })18 .catch(function(err){19 console.log(err);20 });21const rp = require('request-promise');22const cheerio = require('cheerio');23rp(url)24 .then(function(html){25 let $ = cheerio.load(html);26 console.log($('title').text());27 })28 .catch(function(err){29 console.log(err);30 });31const rp = require('request-promise');32const cheerio = require('cheerio');33rp(url)34 .then(function(html){35 let $ = cheerio.load(html);36 console.log($('title').text());37 })38 .catch(function(err){39 console.log(err);40 });41const rp = require('request-promise');42const cheerio = require('cheerio');43rp(url)44 .then(function(html){
Using AI Code Generation
1var BestRemote = require('best-remote');2var myRemote = new BestRemote();3myRemote.remoteHub('A', 1, function(err, result){4 if(err){5 console.log('Error: ' + err);6 }else{7 console.log('Result: ' + result);8 }9});10var BestRemote = require('best-remote');11var myRemote = new BestRemote();12myRemote.remoteHub('A', 2, function(err, result){13 if(err){14 console.log('Error: ' + err);15 }else{16 console.log('Result: ' + result);17 }18});19var BestRemote = require('best-remote');20var myRemote = new BestRemote();21myRemote.remoteHub('A', 3, function(err, result){22 if(err){23 console.log('Error: ' + err);24 }else{25 console.log('Result: ' + result);26 }27});28var BestRemote = require('best-remote');29var myRemote = new BestRemote();30myRemote.remoteHub('A', 4, function(err, result){31 if(err){32 console.log('Error: ' + err);33 }else{34 console.log('Result: ' + result);35 }36});37var BestRemote = require('best-remote');38var myRemote = new BestRemote();39myRemote.remoteHub('B', 0, function(err, result){40 if(err){41 console.log('Error: ' + err);42 }else{43 console.log('Result: ' + result);44 }45});46var BestRemote = require('best-remote');47var myRemote = new BestRemote();48myRemote.remoteHub('B', 1, function(err, result){49 if(err){50 console.log('Error: ' + err);51 }else{52 console.log('Result: ' + result);53 }54});
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!