Jupyterlab load model fromJSON issue - jupyter-notebook

I am developing notebook syncronization mechanism using websockets between jupyterlab users editing same notebook, here is what i am doing:
// having notebook instance as a NotebookPanel
// I am merging UI cell data and server (other's edited) cell data
// `updatedModel` contains merged cells from server and from user's current changes in the notebook.
notebook.context.model.fromJSON(updatedModel.content);
I am facing following issue:
and cell actions disappear.
did anyone have this issue and came up with a solution to properly load notebook from a json?
Jupyterlab Version 3.5.0
Reproduction Code:
import {JupyterFrontEnd, JupyterFrontEndPlugin} from "#jupyterlab/application";
import {INotebookTracker, NotebookPanel, NotebookTracker} from "#jupyterlab/notebook";
const testCopyModelFromJSON = (notebookTracker: NotebookTracker) => {
notebookTracker.widgetAdded.connect((tracker: NotebookTracker, panel: NotebookPanel) => {
let notebook = panel.content;
const notebookModel = notebook.model;
if (!notebookModel) {
return;
}
const model = notebookModel.toJSON();
notebookModel.fromJSON(model);
});
}
const plugin: JupyterFrontEndPlugin<void> = {
id: 'nbsync-extension:plugin',
autoStart: true,
requires: [INotebookTracker],
activate: (app: JupyterFrontEnd, notebookTracker: NotebookTracker) => {
console.info('nbsync-extension started');
app.started
.then(() => {
testCopyModelFromJSON(notebookTracker);
});
app.restored
.then(() => {
testCopyModelFromJSON(notebookTracker);
});
}
};
export default plugin;
dependencies:
"#jupyterlab/application": "^3.5.0",
"#jupyterlab/notebook": "^3.5.0"

Related

How to prevent the router.asPath useEffect from rendering twice on load while using NextJs and getServerSideProps? [duplicate]

This question already has answers here:
Why is my React component is rendering twice?
(8 answers)
Closed 8 months ago.
I am building an explore page with url query parameters (NextJs page with getServerSideProps)
If an external user goes onto this url domain.com/explore?type=actions&category=food it will fetch on the DB the data for "actions" and "food"
If an internal user uses on-page filters, it generates a new url domain.com/explore?type=actions&category=food&orderBy=points and I then fetch the data and render.
To do so, I am basically setting up a useEffect with the [router.asPath] dependency. The problem is that it renders twice on load for external users (due to gerServerSideProps ?) and therefore fetching the data twice :(
Any hints ? Thanks !
useEffect(() => {
// parsing the url
const url = location.search
const urlQuery = url.slice(1)
const result = {}
urlQuery.split("&").forEach(part => {
const item = part.split("=");
result[item[0]] = decodeURIComponent(item[1]);
});
console.log(result)
// Updating forms/filters states and setting up query parameters
queryParams = [] // reseting the params
setFiltersData(prevFiltersData => {
return {
...prevFiltersData,
thumbType: result.type,
}
})
if (result.field) {
setFiltersData(prevFiltersData => {
return {
...prevFiltersData,
categoryField: result.field,
categoryOperator: result.fieldOp,
categoryValue: result.fieldVal,
}
})
queryParams.push(where(result.field, result.fieldOp, decodeURIComponent(result.fieldVal)))
}
if (result.orderBy) {
setFiltersData(prevFiltersData => {
return {
...prevFiltersData,
orderFieldActions: result.orderBy,
orderOperatorActions: result.orderType,
}
})
queryParams.push(orderBy(result.orderBy, result.orderType))
}
setSearchParams(queryParams) // saving query params to state for subsequent data fetch
getFilteredData(result.type) // Fetching data from the DB
setInitialLoading(false)
}, [router.asPath])
Finally found a solution with this thread. https://github.com/vercel/next.js/issues/35822
The problem is due to React being used in "Strict mode" in the next.config.js.
https://reactjs.org/docs/strict-mode.html
Solution :
/** #type {import('next').NextConfig} */
const nextConfig = {
reactStrictMode: false,
experimental: {
scrollRestoration: true,
},
images: {
domains: ['lh3.googleusercontent.com', 'graph.facebook.com', 'firebasestorage.googleapis.com'],
},
}
module.exports = nextConfig
Switching the strictMode to false

TypeOrm - Can't create a connection outside of main function

I have a problem with typeorm, function createConnection works only in index file, if I try to run it in any other file it gets stuck waiting for connection.
export async function saveKU(data: KUData) {
console.log("Foo");
let connection = await createConnection(typeormConfig);
console.log("Received!: " + connection);
const user = connection
.getRepository(KU)
.createQueryBuilder("ku")
.where("ku.ku_number = :ku_number", { ku_number: "54645" })
.getOne();
console.log(user);
}
Message received never gets logged, but then if I run the exact same script in the main function
const main = async () => {
// quit application when all windows are closed
app.on("window-all-closed", () => {
// on macOS it is common for applications to stay open until the user explicitly quits
if (process.platform !== "darwin") {
app.quit();
}
});
app.on("activate", () => {
// on macOS it is common to re-create a window even after all windows have been closed
if (mainWindow === null) {
mainWindow = createMainWindow();
}
});
app.allowRendererProcessReuse = true;
// create main BrowserWindow when electron is ready
app.on("ready", () => {
mainWindow = createMainWindow();
});
let connection = await createConnection(typeormConfig);
console.log("Received!: " + connection);
const user = connection
.getRepository(KU)
.createQueryBuilder("ku")
.where("ku.ku_number = :ku_number", { ku_number: "54645" })
.getOne();
console.log(user);
};
Everything works fine, no error is showing up in both cases, I have no idea what the problem could be, the closest to my example is the following link: https://senorihl.github.io/2019/03/electron-typescript-react-typeorm/
Except that I'm using electron-webpack and creating connections in an index.tsx file doesn't work for me, but rather index.ts

How to configure apollo server with meteor with the meteor/apollo package?

I'm trying to build an app with meteor, apollo/graphql for the first time and the tutorial I'm watching might have outdated versions of apollo. I set up my server as:
import { createApolloServer } from "meteor/apollo";
import { makeExecutableSchema } from "graphql-tools";
const typeDefs = `
type Query {
hi: String
}
`;
const resolvers = {
Query: {
hi() {
return "Hello world";
}
}
};
const schema = makeExecutableSchema({
typeDefs,
resolvers
});
createApolloServer({ schema });
However I usually get this as an error:
TypeError: graphqlExpress is not a function
I know it has to do with the apollo package, but I don't know how to get the migration changes made for apollo 2.0.0 into the meteor/apollo file from the migration doc on apollo's site. Any help is appreciated!

How to load a file into an Angular Test?

i'm trying to test an extension validator using Karma and Jasmine with latest Angular version. I have a service that receives a File and checks its extension and MIME type, this is the method signature:
public validateFileType(file: File, validTypes: string[]): Observable<boolean>
As you can see the method receives a File, so i want to either load some files i have in a /testing folder or create a file with '.doc'/'.xls'/'.pdf' extension (i would like to use the first approach, already tried creating a .doc, .xls file and the signature numbers does not match any real file).
But its impossible to load any File as the HttpClient can not be instantiated in a Karma test, i have tried everything i know and searched a lot, any help is really appreciated.
Example
import { TestBed } from '#angular/core/testing';
import { FileValidatorService } from './file-validator.service';
describe('FileValidatorService', () => {
let service: FileValidatorService;
beforeEach(() => {
TestBed.configureTestingModule({ providers: [FileValidatorService] });
service = TestBed.get(FileValidatorService);
});
it('should be created', () => {
expect(service).toBeTruthy();
});
describe('Types', () => {
it('should be false', () => {
const content = 'Hello test';
const data = new Blob([content], { type: 'application/zip' });
const arrayOfBlob = new Array<Blob>();
arrayOfBlob.push(data);
const applicationZip = new File(arrayOfBlob, 'Mock.zip', { type: 'application/zip' });
service.validateFileType(applicationZip, ['.doc', '.xls']).subscribe((result: boolean) => {
expect(result).toBeFalsy();
});
});
});
});
This test only works because the file i created generates some random signature code that i don't use so its not recognized and it doesn't match the expected types so is not working as it should.

jsreport 2.0 BeforeRender Not Working

I am working on jsreport v2.0 and wants to render the data for the report. I am using handlebars and phantom-pdf and my beforeRender function is not getting called by default.
For jsreport v2.0, i have added the listener for the beforeRender as following but still it did not seem to be called by default to render the data.
function beforeRenderListeners1(req,res){
console.log("Listener Called");
}
const jsreport = require('jsreport-core')({
})
jsreport.beforeRenderListeners.add('beforeRenderListeners1', (req, res) => {
console.log("hello");
req.data.check = abc();
})
since i don't know the complete code that you are using i will go ahead and provide you a snippet that works in latest jsreport-core v2 (2.0.3) with node 8
const jsreport = require('jsreport-core')()
jsreport.use(require('jsreport-handlebars')())
jsreport.beforeRenderListeners.add('beforeRenderListeners1', (req, res) => {
console.log("before render called")
req.data = req.data || {}
req.data.check = 'check pass'
})
jsreport.init().then(() => {
console.log('started')
return jsreport.render({
template: {
content: '<p>sample demo content, check: {{check}}</p>',
engine: 'handlebars',
recipe: 'html'
}
})
}).then((res) => {
console.log('render done')
console.log(res.content.toString())
}).catch((err) => console.error(err))
put that in a file and then run it, you will see the message before render called being printed in console.

Resources