Change name of provideCompletionItems command in VsCode Extension - json

I am creating a VsCode extension which provides inline completions. Currently, it can be accessed using the default "Trigger Suggest" command. I want it to be different, as it should be different from the default option. The main code looks like this:
import * as vscode from 'vscode';
export function activate(context: vscode.ExtensionContext) {
const command = 'getairesponse';
const files = ['c','cpp','csharp','java','javascript', 'php', 'python', 'SQL', 'HTML', 'plaintext'];
const provider1 = vscode.languages.registerCompletionItemProvider(files, {
async provideCompletionItems(document: vscode.TextDocument, position: vscode.Position, token: vscode.CancellationToken, context: vscode.CompletionContext) {
var editor = vscode.window.activeTextEditor;
if (editor){
var cursorPosition = editor.selection.active;
var input = editor.document.getText(new vscode.Range(0, 0, cursorPosition.line, cursorPosition.character));
var out = getOutput(input);
const simpleCompletion = new vscode.CompletionItem(await out);
return [simpleCompletion];
}
}
});
context.subscriptions.push(provider1);
}
I want the command for the extension to be equal to the constant command. I have also included the command in the package.json file:
"contributes": {
"commands": [
{
"command": "getairesponse",
"title": "Get AI Response"
}
]
}

Related

Building a nix derivation within a module

I created the following module services/invidious.nix
{ pkgs, stdenv, ... }:
stdenv.mkDerivation {
name = "invidious";
container = pkgs.dockerTools.buildLayeredImage {
name = "invidious";
contents = [ pkgs.busybox pkgs.bash pkgs.invidious ];
config = {
Cmd = [ "/bin/bash" ];
Env = [];
Volumes = {};
};
};
}
My eventual goal is to have several services in modules and use nix-build to build each of those services as containers, and write the resulting image names to a file:
let
config = import ./config.nix;
pkgs = config.pkgs;
invidious = import ./services/invidious.nix;
in rec {
serviceimages = pkgs.writeText "images.txt" ''
${invidious(pkgs)}
'';
}
and my config.nix just has the pkgs pinned version:
{
# nixos-22.05 / https://status.nixos.org/
pkgs = import (fetchTarball "https://github.com/NixOS/nixpkgs/archive/d86a4619b7e80bddb6c01bc01a954f368c56d1df.tar.gz") {};
}
However, when I use nix-build, I get the following error:
nix-build services.nix -A serviceimages
these 2 derivations will be built:
/nix/store/dbl3bzc05pssq3q9g8wd2i92xpmwf5bb-invidious.drv
/nix/store/4x31hx9nxcbbksi2hsim08djrsj4h1zh-images.txt.drv
building '/nix/store/dbl3bzc05pssq3q9g8wd2i92xpmwf5bb-invidious.drv'...
unpacking sources
variable $src or $srcs should point to the source
error: builder for '/nix/store/dbl3bzc05pssq3q9g8wd2i92xpmwf5bb-invidious.drv' failed with exit code 1;
last 2 log lines:
> unpacking sources
> variable $src or $srcs should point to the source
For full logs, run 'nix log /nix/store/dbl3bzc05pssq3q9g8wd2i92xpmwf5bb-invidious.drv'.
If I try to pull the full logs using the command given, I get the following:
nix log /nix/store/dbl3bzc05pssq3q9g8wd2i92xpmwf5bb-invidious.drv
error: experimental Nix feature 'nix-command' is disabled; use '--extra-experimental-features nix-command' to override
...and if I enable the experimental feature, I see the following:
nix --extra-experimental-features nix-command log /nix/store/dbl3bzc05pssq3q9g8wd2i92xpmwf5bb-invidious.drv
#nix { "action": "setPhase", "phase": "unpackPhase" }
unpacking sources
variable $src or $srcs should point to the source
If I just try to build the same service in a single file, it successfully builds the image:
let
# nixos-22.05 / https://status.nixos.org/
pkgs = import (fetchTarball "https://github.com/NixOS/nixpkgs/archive/d86a4619b7e80bddb6c01bc01a954f368c56d1df.tar.gz") {};
in rec {
docker = pkgs.dockerTools.buildLayeredImage {
name = "invidious";
contents = [ pkgs.busybox pkgs.bash pkgs.invidious ];
config = {
Cmd = [ "/bin/sh" ];
Env = [];
Volumes = {};
};
};
results = pkgs.writeText "images.txt" ''
${docker}
'';
}
What am I doing wrong with my attempt to use modules?
I figured it out. I didn't need the mkDerivation. I just need the buildLayeredImage
{ pkgs, ... }:
pkgs.dockerTools.buildLayeredImage {
name = "invidious";
contents = [ pkgs.busybox pkgs.bash pkgs.invidious ];
config = {
Cmd = [ "/bin/bash" ];
Env = [];
Volumes = {};
};
}
The service.nix and config.nix stay the same:
let
config = import ./config.nix;
pkgs = config.pkgs;
invidious = import ./services/invidious.nix;
in rec {
serviceimages = pkgs.writeText "images.txt" ''
${invidious(pkgs)}
'';
}
{
# nixos-22.05 / https://status.nixos.org/
pkgs = import (fetchTarball "https://github.com/NixOS/nixpkgs/archive/d86a4619b7e80bddb6c01bc01a954f368c56d1df.tar.gz") {};
}

How to prevent duplicates being added to JSON object

Using Electron and electron-store to add files' simplified executable names and their full paths from showOpenDialog to config.json. Selecting the same file causes repeating entries in config.json. For some reason (or rather missing code), app thinks they're different paths.
function addTool() {
dialog.showOpenDialog({
title: 'Select tool executable.',
filters: [{
name: 'Tool start file',
extensions: ['exe', 'jar']
}],
properties: ['openFile']
},
(exeFromDialog) => {
var var_exeToolPath = exeFromDialog.join(); //removes square brackets
var var_toolName = path.basename(var_exeToolPath).split(/[/._-]/g)[0];
//path.basename removes path until file, split+regex takes only first part until first character (one of ._/)
const tools = appConfig.get('tools');
const newTool = [...(tools || []), {
"toolName": var_toolName,
"toolPath": var_exeToolPath
}];
appConfig.set('tools', newTool);
})
}
This is how config.json looks when you open the same file few times:
{
"winPosition": {
"x": 1497,
"y": 410,
"width": 203,
"height": 603
},
"exePOEPath": [
"C:\\Program Files (x86)\\Grinding Gear Games\\Path of Exile\\PathOfExile_x64.exe"
],
"tools": [
{
"toolName": "tool1",
"toolPath": "D:\\tool1.exe"
},
{
"toolName": "tool1",
"toolPath": "D:\\tool1.exe"
},
{
"toolName": "tool1",
"toolPath": "D:\\tool1.exe"
}
]
}
Ultimately it comes to the question How to remove duplicates from your array
This part of your code will always add the new value, it doesn't check for duplicates
const newTool = [...(tools || []), {
toolName: var_toolName,
toolPath: var_exeToolPath
}]
So it should be improved to something like the following:
newTool = newTool.filter((item, pos, self) =>
self.find(other => other.toolName === item.toolName) === item
)
I would prefer using [...new Set([newTool])] but you store Objects which are compared by reference thus duplicates cannot be eliminated by Set

How to load json from file and set it as global variable in Vue?

I'm new to Vue. I want to read employeeId from a login form and ust it to load some json files named according as employeeId.json like (10000001.json, 20000001.json) and set the json object as a global variable so I can easily access it in all components.
Firstly, I don't know how to dynamically load json files. Using import sees not work. Some one suggested using require should work. But there are not many examples, I don't know where to put require...
Secondly, how do I set the json as global after the employeeId props in? I'm very confused where to put it (inside the export default or not? inside methods or not? or inside created/mounted or not?) and where to use this or not...
This is the script section of my headerNav.vue file.
<script>
//**I placed them here now, it works, but employeeId is hard coded...
import json10000001 from "./json/10000001.json";
import json20000001 from "./json/20000001.json";
import json30000001 from "./json/30000001.json";
// var employeeId = employeeIdFromLogin;
var jsonForGlobal;
var employeeId = 10000001;
var jsonFileCurrentObj;
if (employeeId == "10000001") {
jsonForGlobal = jsonFileCurrentObj = json10000001;
} else if (employeeId == "20000001") {
jsonForGlobal = jsonFileCurrentObj = json20000001;
} else if (employeeId == "30000001") {
jsonForGlobal = jsonFileCurrentObj = json30000001;
}
export default {
// props:{
// employeeIdFromLogin: String,
// },
props:['employeeIdFromLogin'],
jsonForGlobal,
// employeeIdFromLogin,
data() {
return {
docked: false,
open: false,
position: "left",
userinfo: {},
jsonFileCurrent: jsonFileCurrentObj,
// employeeIdFromLogin: this.GLOBAL3.employeeIdFromLogin
// jsonFile: currentJsonFile
};
},
mounted() {
//**I tried put it here, not working well...
// var employeeId = this.employeeIdFromLogin;
// // var jsonForGlobal;
// console.log("headernav.employeeIdFromLogin="+this.employeeIdFromLogin);
// // var employeeId = 10000001;
// var jsonFileCurrentObj;
// if (employeeId == "10000001") {
// this.jsonForGlobal = this.jsonFileCurrentObj = json10000001;
// } else if (employeeId == "20000001") {
// this.jsonForGlobal = this.jsonFileCurrentObj = json20000001;
// } else if (employeeId == "30000001") {
// this.jsonForGlobal = this.jsonFileCurrentObj = json30000001;
// }
},
methods: {
switchPage(pageName) {
this.$emit("switchPage", pageName);
}
//**I don't know how to use the require...
// var employeeId = 10000001;
// getJsonFile(employeeId) {
// this.currentJsonFile = require("../assets/json/" + employeeId + ".json");
// }
}
};
You might want to use vuex to manage global store. But if you don't want includes Vuex, there is a simpler way to have global state:
Define globalStore.js
// globalStore.js
export const globalStore = new Vue({
data: {
jsonForGlobal: null
}
})
then import it and use in component:
import {globalStore} from './globalStore.js'
export default {
props: ['employeeIdFromLogin'],
data: function ()
return {
jsonLocal: globalStore.jsonForGlobal,
jsonFileCurrent: null
}
},
watch: {
employeeIdFromLogin: {
handler(newVal, oldVal) {
const data = require('./json/' + this.employeeIdFromLogin + '.json')
this.jsonFileCurrent = data
globalStore.jsonForGlobal = data
}
}
}
}

Too tidious hooks when querying in REST. Any ideas?

I've just started using feathers to build REST server. I need your help for querying tips. Document says
When used via REST URLs all query values are strings. Depending on the service the values in params.query might have to be converted to the right type in a before hook. (https://docs.feathersjs.com/api/databases/querying.html)
, which puzzles me. find({query: {value: 1} }) does mean value === "1" not value === 1 ? Here is example client side code which puzzles me:
const feathers = require('#feathersjs/feathers')
const fetch = require('node-fetch')
const restCli = require('#feathersjs/rest-client')
const rest = restCli('http://localhost:8888')
const app = feathers().configure(rest.fetch(fetch))
async function main () {
const Items = app.service('myitems')
await Items.create( {name:'one', value:1} )
//works fine. returns [ { name: 'one', value: 1, id: 0 } ]
console.log(await Items.find({query:{ name:"one" }}))
//wow! no data returned. []
console.log(await Items.find({query:{ value:1 }})) // []
}
main()
Server side code is here:
const express = require('#feathersjs/express')
const feathers = require('#feathersjs/feathers')
const memory = require('feathers-memory')
const app = express(feathers())
.configure(express.rest())
.use(express.json())
.use(express.errorHandler())
.use('myitems', memory())
app.listen(8888)
.on('listening',()=>console.log('listen on 8888'))
I've made hooks, which works all fine but it is too tidious and I think I missed something. Any ideas?
Hook code:
app.service('myitems').hooks({
before: { find: async (context) => {
const value = context.params.query.value
if (value) context.params.query.value = parseInt(value)
return context
}
}
})
This behaviour depends on the database and ORM you are using. Some that have a schema (like feathers-mongoose, feathers-sequelize and feathers-knex), will convert values like that automatically.
Feathers itself does not know about your data format and most adapters (like the feathers-memory you are using here) do a strict comparison so they will have to be converted. The usual way to deal with this is to create some reusable hooks (instead of one for each field) like this:
const queryToNumber = (...fields) => {
return context => {
const { params: { query = {} } } = context;
fields.forEach(field => {
const value = query[field];
if(value) {
query[field] = parseInt(value, 10)
}
});
}
}
app.service('myitems').hooks({
before: {
find: [
queryToNumber('age', 'value')
]
}
});
Or using something like JSON schema e.g. through the validateSchema common hook.

Create a dynamic array for use in grunt concat

I need to concatenate a set files based on variables I have defined my package.json.
// package.json
...
"layouts": [
{
"page": "home",
"version": "a"
},
{
"page": "about",
"version": "a"
},
{
"page": "contact",
"version": "b"
}
]
...
In grunt I am then building these into a JSON array and pumping it into the src parameter in my grunt-concat-contrib task.
// gruntfile.js
...
var package = grunt.file.readJSON('package.json'),
targets = package.layouts,
paths = [];
for (var target = 0; target < targets.length; target++) {
paths.push("layouts/" + targets[target]['page'] + "/" + targets[target]['version'] + "/*.php");
};
var paths = JSON.stringify(paths);
grunt.log.write(paths); // Writing this to console for debugging
grunt.initConfig({
concat: {
build: {
src: paths,
dest: 'mysite/Code.php',
options: {
separator: '?>\n\n'
}
}
}
});
...
My issue is that the paths variable is not working inside of the initConfig when it is assigned to JSON.stringify(paths).
If I manually input the array like the following that I copied from where I logged the paths variable to the console, it works!
var paths = ["layouts/home/a/*.php","layouts/about/a/*.php","layouts/contact/b/*.php"];
What am I missing?
Derp. I fixed it, I didn't need to JSON.stringify() the array.
Final working gruntfile is below:
// gruntfile.js
...
var package = grunt.file.readJSON('package.json'),
targets = package.layouts,
paths = [];
for (var target = 0; target < targets.length; target++) {
paths.push("layouts/" + targets[target]['page'] + "/" + targets[target]['version'] + "/*.php");
};
grunt.initConfig({
concat: {
build: {
src: paths,
dest: 'mysite/Code.php',
options: {
separator: '?>\n\n'
}
}
}
});
...