A command for change prefix - command

I want to make a command like y!prefix [new_prefix] for servers who add my bot.
How can I do that?
Thanks!

First you have to make a json file to stock the prefix.
Next, make a command with this :
let prefixes = JSON.parse(fs.readFileSync("./JSON/prefix.json", "utf8"));
prefixes[message.guild.id] = {
prefixes: args[0]
};
fs.writeFile("./JSON/prefix.json", JSON.stringify(prefixes), (err) => {
if(err) console.log(err);
});
After, you just have to set the prefix for your commands in your main with something like this :
let prefixes = JSON.parse(fs.readFileSync("./JSON/prefix.json", "utf8"));
if (!prefixes[message.guild.id]) {
prefixes[message.guild.id] = {
prefixes: PREFIX,
};
}
let gprefix = prefixes[message.guild.id].prefixes;

Related

FileSystemProvider auto-create directory

I'm working on implementing this the File System provider functionality:
https://code.visualstudio.com/api/references/vscode-api#FileSystemProvider
I'd like the following writeFile function to automatically create any necessary parent directories as needed. Was wondering if any one else has done anything similar, or how the experts would approach it.
https://github.com/microsoft/vscode-extension-samples/blob/aa42c2ec7248059ff5903ff11aa6eeabc04329bf/fsprovider-sample/src/fileSystemProvider.ts#L80
Option 1:
change the following line to silent=true and if it returns an undefined, create the necessary directory
https://github.com/microsoft/vscode-extension-samples/blob/aa42c2ec7248059ff5903ff11aa6eeabc04329bf/fsprovider-sample/src/fileSystemProvider.ts#L199
option 2:
Extend the logic of this if statement or replace the following error with some logic to create the folders
https://github.com/microsoft/vscode-extension-samples/blob/aa42c2ec7248059ff5903ff11aa6eeabc04329bf/fsprovider-sample/src/fileSystemProvider.ts#L183
thoughts or suggestions?
I was able to get this working with the following function. I tried the follow the existing code style and approach for simplicity.
/**
* make parent directires if not present
*/
private _makePath(uri: Uri) {
// get the base directory
const dirname = uri.with({ path: path.posix.dirname(uri.path) });
// split the base directory to the folder parts
const parts = dirname.path.split('/');
// array to hold the parent folders as we create them
const fullPath: string[] = [];
// loop through folders
for ( const part of parts) {
if (!part) {
continue; // empty part, continue with loop
}
// track the folder path as we check/create them
fullPath.push(part);
// see if current folder exists
const here = this._lookup(Uri.parse(...fullPath), true);
if (!here) {
// current folder not found, so create it
this.createDirectory(Uri.parse(path.join(...fullPath)));
} else {
console.log('directory exists already: ', part);
}
}
}
Then call the function at each file creation:
writeFile(uri: vscode.Uri, content: Uint8Array, options: { create: boolean, overwrite: boolean }, id?: string): void {
console.log('writefile: ', uri);
const basename = path.posix.basename(uri.path);
// *** create dir path if not there ***
this._makePath(uri);
const parent = this._lookupParentDirectory(uri);
let entry = parent.entries.get(basename);
if (entry instanceof Directory) {
throw vscode.FileSystemError.FileIsADirectory(uri);
}
if (!entry && !options.create) {
throw vscode.FileSystemError.FileNotFound(uri);
}
if (entry && options.create && !options.overwrite) {
throw vscode.FileSystemError.FileExists(uri);
}
if (!entry) {
entry = new File(basename, id);
parent.entries.set(basename, entry);
this._fireSoon({ type: vscode.FileChangeType.Created, uri });
}
entry.mtime = Date.now();
entry.size = content.byteLength;
entry.data = content;
this._fireSoon({ type: vscode.FileChangeType.Changed, uri });
}

Listing files in folder in vscode extension

I am creating a vscode extension that does some custom auto-completing of files paths.
I want to take what the user has typed, and if that value resolves to a folder in the workspace, I want to list all the files in that folder for auto-complete.
For example, given:
a workspace located at: /home/me/my-vs-project
with files:
/home/me/my-vs-project/assets/dog.png
/home/me/my-vs-project/assets/cat.jpeg
If I type in 'assets' or './assets' into vscode, the extension should be able to provide me an autocomplete list of:
'./assets/dog.png'
'./assets/cat.png'
Here's a snippet of the code that doesn't work (returns 0 results)..
let inputAsWorkspaceRelativeFolder = getInput(document, position); // for example, would return: '/home/me/my-vs-project/assets' for input of './assets'
let glob = inputAsWorkspaceRelativeFolder + '/*';
vscode.workspace.findFiles(glob, null, 100).then((uris: vscode.Uri[] ) => {
uris.forEach((uri: vscode.Uri) => {
console.log(uri);
});
});
For some reason, the above code is returning 0 uris though. Thoughts on how I have to format the glob to make this happen? and/or if there is a better approach?
I was able to do this using vscode.RelativePattern -- I'm sure I could've done it using generic GlobPatterns but im still not clear what the findFiles(..) consider the 'root' when matching files; RelativePattern is explicitly relative to the workspace root.
let workspaceFolder: vscode.WorkspaceFolder | undefined = vscode.workspace.getWorkspaceFolder(document.uri);
if (!workspaceFolder || document.isUntitled) {
return undefined;
}
// Workspace folder: /home/me/my-project
let workspaceFolderPath: string = workspaceFolder.uri.path;
let relativeSearchFolderPrefix = path.normalize(path.dirname(document.uri.path) + '/' + searchText);
relativeSearchFolderPrefix = path.relative(workspaceFolderPath, relativeSearchFolderPrefix);
let relativePattern: vscode.RelativePattern = new vscode.RelativePattern(
workspaceFolderPath,
relativeSearchFolderPrefix + '/**/*.{png,jpeg,jpg,gif}');
return vscode.workspace.findFiles(globPattern, null, 50).then((uris: vscode.Uri[] ) => {
let relativePaths: string[] = [];
uris.forEach((uri: vscode.Uri) => {
relativePaths.push(path.relative(current, uri.path));
});
// trivial custom function that turns an array of strings into CompletionItems
return getCompletionItems(relativePaths, vscode.CompletionItemKind.File);
});
😊👋🏻
I think you wronged the glob.
I found this intresting wiki about Glob pattern composition.
let inputAsWorkspaceRelativeFolder = 'asset'; // for example, would return: '/home/me/my-vs-project/assets' for input of './assets'
//https://github.com/ev3dev/vscode-ev3dev-browser/wiki/Glob-Patterns
let glob = '**/'+inputAsWorkspaceRelativeFolder+'/*.*';//or +'/{*.png,*.jpeg}';
Or you can use the node built-in fs
import * as fs from 'fs';
fs.readdir(inputAsWorkspaceRelativeFolder, (err, files: string[]) => {
files.forEach((file: path) => {
const uri = vscode.Uri.file(file);
console.log(uri);
});
});
More simple, if you want to get all the files in the asset folder and don't want to filter for extension.

how to put verification in pageobject model in protractor

I have a code (credit to #kishanpatel) Traverse-through-each-row-for-a-column-text which will verify whether the value is added in grid or not. i want to put this in my page object. i was thinking to add the elements into page object and the if condition in a different helper file similar to selenium but i am not sure is that the right appraoch. see the details below.
if I call the mo.helper in spec.ts, it says gridcheck.ispresent() is not a function. How to handle this scenario?
code:
it('verify the grid that master obligation is added', function () {
var testvar = "'test_protractor'";
var row_check = element(by.xpath("//div[contains(text()," + testvar + ")]"));
if (row_check.isPresent()) {
row_check.getText().then(function (msg) {
if (row_check.isPresent()) {
console.log("Grid contains========== " + msg);
}
});
}
});
i have the below method in mo.ts(page object page):
this.grid = function (value) {
// var testvar = "'test_protractor'";
var row_check = element(by.xpath("//div[contains(text()," + value + ")]"));
return require('./mohelper.ts')
}
}
mohelper.ts:
require('../page/mo.ts')
var mohelper = function () {
this.gridvaluepresent = function () {
require('../page/mo.ts')
var gridcheck = mo.grid();
if(gridcheck.isPresent()) {
gridcheck.getText().then(function (msg) {
if (gridcheck.isPresent()) {
console.log("Grid contains========== " + msg);
}
})
}
}
}
module.exports = new mohelper();
spec.ts:
it('go to corresponding module and verify whether the master obligation is added ', function () {
browser.sleep(10000);
taxhome.selectmodule;
taxhome.selectmoduledropdown(1);
mo.grid("test_protractor");
mohelper.gridvaluepresent();
});
Couple of things here to be considered -
1) Most of the protractor's api methods are asynchronous i.e. they return promises you have to resolve/reject them to perform actions.
isPresent() also returns a promise, you need to resolve it-
var row_check = element(by.xpath("//div[contains(text()," + value + ")]"));
row_check.isPresent().then(function(present) {
if(present) { // it returns a boolean value
row_check.getText().then(function (msg) {
console.log("Grid contains========== " + msg);
});
}
});
2) Since you are using TypeScript , use its syntax rather than conventional js-
let row_check = element(by.xpath("//div[contains(text()," + value + ")]")); // Block scoped variable using 'let'
row_check.isPresent().then((present) => { // notice the thick arrow
if(present) {
row_check.getText().then((msg) => {
console.log("Grid contains========== " + msg);
});
}
});
3) Maintain Page Objects efficiently and readable-
All the helper methods, elements etc. for a single page should go in a single page object. Write them in separate classes, typescript uses the concept of classes and transpiles them to global functions.
moHelper.ts
import {ElementFinder, element} from 'protractor';
export class MoHelper {
public row_check: ElementFinder; // its of element finder type
gridValueCheck(value : string) {
row_check = element(by.xpath("//div[contains(text()," + value + ")]")); // please use Css selectors instead of Xpath!
row_check.isPresent().then((present) => {
if(present) {
row_check.getText().then((msg) => {
return msg; // here you are returning the msg of the row from your page!
});
}
});
}
}
Your spec.ts should validate that row msg!
import {MoHelper} from './moHelper.ts'
let mo: MoHelper = new MoHelper();
it('go to corresponding module and verify whether the master obligation is added ', () => {
browser.sleep(10000); // please refrain from using sleeps instead use Expected Conditions
taxhome.selectmodule;
taxhome.selectmoduledropdown(1);
expect(mo.gridValueCheck("test_protractor")).toEqual("Your Expected Message");
});
Please find the links for your reference to understand the above in more detail-
isPresent
Getting started with typescript
Using page objects in protractor/style guide
Expected Conditions

CoffeeScript code-complete for Web IDE

Is there a web based code-complete API/IDE for coffee script?
Ace Editor and CodeMirror have good syntax highlighting and lint-based syntax support, and what I would like to add to my app (Node-WebKit-REPL) is code-complete support
Unfortunately neither CodeMirror nor Ace have autocompleters specially for coffeescript, but they both have an api to add a completer.
here's a simple example to show how do it for ace
var lang = require("ace/lib/lang")
var languageTools = require("ace/ext/language_tools")
editor = ace.edit("editor")
editor.setOptions({
enableBasicAutocompletion: true,
enableLiveAutocompletion: true, // this does not work very well atm
mode: "ace/mode/coffee"
})
var evalCompleter = {
getCompletions: function(editor, session, pos, prefix, callback) {
var completions = [];
var props = Object.keys(window);
props.forEach(function(key){
completions.push({
value: key,
meta: 'window',
type: 'eval',
score: 1000
});
})
callback(null, completions)
},
getDocTooltip: function(item) {
if (item.type == 'eval' && !item.docHTML) {
var o = window[item.value]
var type = typeof o
item.docHTML = "<b>" + type + "</b><br>"
+ lang.escapeHTML(o + "");
}
}
}
editor.completers = [evalCompleter, languageTools.keyWordCompleter,
languageTools.snippetCompleter, languageTools.textCompleter
];
of course in a real application you will need some kind of parser to get the expression before the . to evaluate
http://sevin7676.github.io/Ace.Tern/demo.html also can be useful.

Unable to write to file with phonegap

Using the methods found on the phonegap api I'm trying to write to a file. This works in Android, but on an iOS device the writer is returning an error. Whenever I call writeFile() it returns an error, and the param passed into writeFail is -1. I cannot see why -1 is being passed into the error function, or why it's even failing to begin with. Has anyone else used the fileWriter on an iOS device, or can you see what I might be doing wrong?
function writeFile() {
var paths = navigator.fileMgr.getRootPaths();
var writer = new FileWriter(paths[0] + "write.txt");
writer.onwrite = writeSuccess;
writer.onerror = writeFail;
writer.write("some sample text");
// The file is now 'some sample text'
}
function writeSuccess() {
console.log("Write has succeeded");
}
function writeFail(evt) {
console.log(evt);
console.log(evt.target.error.code);
}
I had the same problem but I crawled through the mailing list and finally found the solution:
var writer = new FileWriter("write.txt");
This is it. Simply don't prepend the "Documents"-path. The documentation is wrong on that (still).
And don't forget to not use "readAsDataURL" as it would silently not work (on iOS). Hope I could help you.
If you want to write to a file this is the function(phonegap 2.5)
function fileWrite(filePath, text) {
var onFSWin = function(fileSystem) {
fileSystem.root.getFile(filePath, {create: true, exclusive: false}, onGetFileWin, onFSFail);
}
var onGetFileWin = function(fileEntry) {
fileEntry.createWriter(gotFileWriter, onFSFail);
}
var gotFileWriter = function(writer) {
writer.write(text);
}
var onFSFail = function(error) {
console.log(error.code);
}
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, onFSWin, onFSFail);
}