Dynamic loading of data - vuejs - import

I have 3 different language files.
import { french } from '../fr/data.js';
import { englishUS } from '../US/data.js';
import { englishUK } from '../US/data.js';
I load them all in and then just switch in the data I need based on a global language variable. ($root.language)
mounted() {
//switch statement based on $root.language
}
Is there a better way to make this more dynamic and only import the file I need?

Related

Neovim goto definition

If I use gd or gD commands on my functions in neovim, it only jumps to my imports, not to my actual function definitions. I am using tsserver LSP for javascript. Also Treesitter for javascript has been installed.
import { mainObject, analyzeButton, saveButton, generateScriptButton } from './js_modules/utils.js'
import { renderSvgFile } from './js_modules/fileRenderer.js'
import { collectSvgElements, collectDiagramElements } from './js_modules/collectERElements.js'
import { createGraph } from './js_modules/createGraph.js'
import { generateScript } from './js_modules/generateScript.js'
renderSvgFile()
analyzeButton.addEventListener('click', function(){
mainObject.object = document.getElementById('object').contentDocument
mainObject.svg = mainObject.object.getElementsByTagName('svg')[0]
mainObject.nodesArray = mainObject.svg.childNodes
collectSvgElements(mainObject.nodesArray)
collectDiagramElements()
createGraph()
})
generateScriptButton.addEventListener('click', generateScript)
Did you configured gd to use lsp functions?
Quick and dirty way to do it - is like this:
vim.api.nvim_set_keymap("n", "gD", "<cmd>lua vim.lsp.buf.declaration()<CR>", { noremap = true, silent = true })
vim.api.nvim_set_keymap("n", "gd", "<cmd>lua vim.lsp.buf.definition()<CR>", { noremap = true, silent = true })
Although i'd recommend doing it during your language-server setup, so that buffers that don't have it, would not try to use this mapping and use the default one. Here's my part of config that does it - link

VS Code API: How do I retrieve ExtensionContext outside of extension.ts?

I'm using VS Code API's ExtensionContext.globalState() to count the number of the times the sidebar of our extension has been opened. This is inside a command a handler in extension.ts and it counts the number of opens on local storage as expected.
I want to retrieve that count on a .js file where we are using JQuery to append components to the UI of the sidebar. However, I don't know how to retrieve ExtensionContext.globalState outisde of extension.ts
This is how I'm getting and updating the value of the count on extension.ts
const retrievedOpeningCountValue = context.globalState.get<Number>("sidebarOpeningCount");
// If show hasn't been called yet, retrieve 0, then increase it to 1 to store such value
let retrievedValue = retrievedOpeningCountValue?.valueOf() || 0;
let increasedValue = retrievedValue + 1;
context.globalState.update("sidebarOpeningCount", increasedValue);
And then I need to retrieve that number on my JQuery file. I can't do import * as vscode from "vscode"; because it't not a TS file. Even if it was, context: vscode.ExtensionContext can only be passed as a parameter to the activate function on extension.ts.
But basically I wanna do something like const retrievedOpeningCountValue = context.globalState.get<Number>("sidebarOpeningCount");on a js file. How do I do that?
You could simply assign context to some global / shared resource, and import it on any other .js/.ts file.
Something like:
extension.ts
export async function activate(context: vscode.ExtensionContext) {
Container.context = context;
container.ts
import { ExtensionContext } from "vscode";
export class Container {
private static _extContext: ExtensionContext;
public static get context(): ExtensionContext {
return this._extContext;
}
public static set context(ec: ExtensionContext) {
this._extContext = ec;
}
}
yourotherfile.ts
import { Container } from "../container";
...
const retrievedOpeningCountValue = Container.context.globalState.get<Number>("sidebarOpeningCount");

Wagtail - how to get tags to work with `telepath` (tags in streamfield)?

I can use tags in regular page fields without any issue. When using tags within blocks (within a streamfield), the UI works and the tags are saved BUT the current page tags do not show up when loading the page in the admin. That's because the current value is not in the template anymore, it's in a JSON loaded via telepath.
I can confirm that the tags are saved and present in the data passed to initBlockWidget in the page source but these are ignored. Also, if I used a regular text field instead of the tag-widget, I can see the saved-values in the admin.
This is the code I have (which used to be enough before the refactor with telepath).
from wagtail.admin.widgets import AdminTagWidget
class TagBlock(TextBlock):
#cached_property
def field(self):
field_kwargs = {"widget": AdminTagWidget()}
field_kwargs.update(self.field_options)
return forms.CharField(**field_kwargs)
I think the following link is what I need to complete somehow to get it to work: https://docs.wagtail.io/en/stable/reference/streamfield/widget_api.html#form-widget-client-side-api
I've tried with this:
class AdminTagWidgetAdapter(WidgetAdapter):
class Media:
js = [
"wagtailadmin/js/vendor/tag-it.js",
"js/admin/admin-tag-widget-adapter.js",
]
register(AdminTagWidgetAdapter(), AdminTagWidget)
And under js/admin/admin-tag-widget-adapter.js:
console.log("adapter"); // this shows up in the console
class BoundWidget { // copied from wagtail source code
constructor(element, name, idForLabel, initialState) {
var selector = ':input[name="' + name + '"]';
this.input = element.find(selector).addBack(selector); // find, including element itself
this.idForLabel = idForLabel;
this.setState(initialState);
}
getValue() {
return this.input.val();
}
getState() {
return this.input.val();
}
setState(state) {
this.input.val(state);
}
getTextLabel(opts) {
const val = this.getValue();
if (typeof val !== 'string') return null;
const maxLength = opts && opts.maxLength;
if (maxLength && val.length > maxLength) {
return val.substring(0, maxLength - 1) + '…';
}
return val;
}
focus() {
this.input.focus();
}
}
// my code here:
class AdminTagWidget {
constructor(html, idPattern) {
this.html = html;
this.idPattern = idPattern;
}
boundWidgetClass = BoundWidget;
render(placeholder, name, id, initialState) {
console.log("RENDER", placeholder, name, id, initialState); // this does not show
var html = this.html.replace(/__NAME__/g, name).replace(/__ID__/g, id);
var idForLabel = this.idPattern.replace(/__ID__/g, id);
var dom = $(html);
$(placeholder).replaceWith(dom);
// eslint-disable-next-line new-cap
return new this.boundWidgetClass(dom, name, idForLabel, initialState);
}
}
console.log("here") // does show in the console
// variants I've tried:
//window.telepath.register('wagtail.admin.widgets.tags.AdminTagWidget', AdminTagWidget);
//window.telepath.register('wagtail.widgets.AdminTagWidget', AdminTagWidget);
window.telepath.register('path.where.its.used.AdminTagWidget', AdminTagWidget)
The log from my custom render method does not show. It seems that I'm not calling the right path within window.telepath.register but I don't know how what the string is supposed to be...
I'm not even sure if this is the right way forward.
Notes:
it works in regular field, the question is about tags in blocks
I'm using Wagtail version 2.13.2 but I've also tried with 2.15 without any difference.
In the console, I can log window.telepath and see my custom widget. It's just not "applied" to anything
Your WidgetAdapter class needs a js_constructor attribute:
class AdminTagWidgetAdapter(WidgetAdapter):
js_constructor = 'myapp.widgets.AdminTagWidget'
class Media:
js = [
"wagtailadmin/js/vendor/tag-it.js",
"js/admin/admin-tag-widget-adapter.js",
]
Any string value will work here - it just needs to uniquely identify the class, so it's recommended to use a dotted module-like path to avoid colliding with others. This then matches the string you pass to window.telepath.register on the Javascript side:
window.telepath.register('myapp.widgets.AdminTagWidget', AdminTagWidget)

How to import sub-routes from other packages

Instead of writing every route under main(), like
func main() {
e := echo.New()
e.GET("/api", sayHello)
e.GET("/api/music", getMusic)
e.GET("/api/user/:id", getDetail)
e.POST("/api/user", addUser)
// ...
}
How can I import these all sub-routes from a file called api.go, and use those in the main function? Similar to
import "./API"
func main() {
e := echo.New()
e.UseSubroute(API.Routes) // <-- similar to this
// ...
}
What you can do is use the echo.Group and pass it to the api package, and initialize the routes handler there.
package api
import (
"github.com/labstack/echo"
)
func UseSubroute(group *echo.Group) {
group.GET("/", sayHello)
group.GET("/music", getMusic)
group.GET("/user/:id", getDetail)
group.POST("/user", addUser)
}
and in the main you can just import your api package.
package main
import (
"github.com/labstack/echo"
"your-repo/path-to/api" // your api package
)
func main() {
e := echo.New()
apiGroup := e.Group("/api")
api.UseSubroute(apiGroup)
// ...
}
The Echo object does not have this method. I think you need the code?
API.go:
package main
import "github.com/labstack/echo"
func UseSubroute(echo *echo.Echo) {
echo.GET("/api", sayHello)
echo.GET("/api/music", getMusic)
echo.GET("/api/user/:id", getDetail)
echo.POST("/api/user", addUser)
}
main.go:
package main
import "github.com/labstack/echo"
func main() {
e := echo.New()
UseSubroute(e)
}
These two files need to be placed in the same directory.
Do you need it?
Based on #Andy 's idea, I come up with a solution, that supports detachable nested routes.
The current folder structure is as follows:
.
├── routes
│ ├── index.go
│ └── music.go
└── server.go
...where server.go is the project main entry, belongs to the main package, while index.go and music.go belong to routes package.
The endpoints are
"/api" -> index.go
"/api/music" -> music.go
First in index.go we define a function for using routes at this level.
func UseRoute(group *echo.Group, routes func(group *echo.Group)) {
routes(group)
}
Then,
in server.go
func main() {
e := echo.New()
apiGroup := e.Group("/api")
routes.ActivateIndex(mainGroup)
}
in index.go
var mainGroup *echo.Group
func ActivateIndex(g *echo.Group) {
mainGroup = g
UseRoute(mainGroup, IndexRoutes)
// sub routes
musicGroup := mainGroup.Group("/music")
ActivateMusic(musicGroup)
}
and in music.go
var musicGroup *echo.Group
func ActivateMusic(g *echo.Group) {
musicGroup = g
UseRoute(musicGroup, MusicRoutes)
}
Note: IndexRoutes, MusicRoutes etc. are functions that specify endpoints at this level.
e.g.
func IndexRoutes(group *echo.Group) {
group.GET("/", sayHello)
group.GET("/user/:id", getDetail)
group.POST("/user", addUser)
}
In this way, the routes can be defined in different .go files, making the business logic clearer.
For example, to extend the nested level, we can create another ActivateHiphop function in hiphop.go, also import the new sub-routes at ActivateMusic function from music.go, so that "/api/music/hiphop" can be pointed to hiphop.go.
p.s. To add more routes in /api level, just create more endpoints in IndexRoutes function.

Creating a chart in apache poi

I need to create in java a microsoft word document containing charts. I'm trying out the Apache POI but haven't found a way to do it. Are there any examples of how to do this?
you can create chart using Temp Ms-Word file.
just create charts in your Temp Ms-Word File and read using customised POI jar and write back to your actual Ms-word File
https://github.com/sandeeptiwari32/POI_ENHN/blob/master/POI3.14.jar.
You can get this code in official poi version 4.0
code Example:
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.poi.POIXMLDocumentPart;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.xwpf.usermodel.XWPFChart;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.openxmlformats.schemas.drawingml.x2006.chart.CTChart;
import org.openxmlformats.schemas.drawingml.x2006.chart.CTTitle;
import org.openxmlformats.schemas.drawingml.x2006.chart.CTTx;
import org.openxmlformats.schemas.drawingml.x2006.main.CTRegularTextRun;
import org.openxmlformats.schemas.drawingml.x2006.main.CTTextBody;
import org.openxmlformats.schemas.drawingml.x2006.main.CTTextParagraph;
public class TestXWPFChart {
public static void main(String[] args) throws Exception {
FileInputStream inpuFile=new FileInputStream("input.docx");
FileOutputStream outFile = new FileOutputStream("output.docx");
#SuppressWarnings("resource")
XWPFDocument document = new XWPFDocument(inpuFile);
XWPFChart chart=null;
for (POIXMLDocumentPart part : document.getRelations()) {
if (part instanceof XWPFChart) {
chart = (XWPFChart) part;
break;
}
}
//change chart title from "Chart Title" to XWPF CHART
CTChart ctChart = chart.getCTChart();
CTTitle title = ctChart.getTitle();
CTTx tx = title.addNewTx();
CTTextBody rich = tx.addNewRich();
rich.addNewBodyPr();
rich.addNewLstStyle();
CTTextParagraph p = rich.addNewP();
CTRegularTextRun r = p.addNewR();
r.addNewRPr();
r.setT("XWPF CHART");
//write modified chart in output docx file
document.write(outFile);
}
}