Starting Here.js Creating new MapView Get TypeError - here-api

I am trying to use harp.gl and used following tutorial.
tutorial:https://developer.here.com/tutorials/harpgl/
But I am getting following errors.
MapView.ts:919 Uncaught TypeError: Cannot read property 'addEventListener' of null
at new MapView (MapView.ts:919)
at JavaScript.js:2

You tried to use the method 2 of tutorial on https://developer.here.com/tutorials/harpgl/
I made the same followed tutorial method2 and into the file index.ts implemented the mapView.addEventListener as you can see what contains my index.ts below:
/*
* Copyright (C) 2017-2019 HERE Europe B.V.
* Licensed under Apache 2.0, see full license in LICENSE
* SPDX-License-Identifier: Apache-2.0
*/
import { GeoCoordinates } from "#here/harp-geoutils";
import { View } from "./View";
import { MapViewEventNames } from "#here/harp-mapview";
const app = new View({
canvas: document.getElementById("map") as HTMLCanvasElement
});
const mapView = app.mapView;
const options = { tilt: 45, distance: 3000 };
const coordinates = new GeoCoordinates(1.278676, 103.850216);
let azimuth = 300;
mapView.addEventListener(MapViewEventNames.Render, () => {
mapView.lookAt(coordinates, options.distance, options.tilt, (azimuth += 0.1))
});
mapView.beginAnimation();
// make map full-screen
mapView.resize(window.innerWidth, window.innerHeight);
// react on resize events from the browser.
window.addEventListener("resize", () => {
mapView.resize(window.innerWidth, window.innerHeight);
});
// center the camera to New York
mapView.lookAt(new GeoCoordinates(40.70398928, -74.01319808), 1500, 40, 0);
// make sure the map is rendered
mapView.update();
This code and mapView.addEventListener works for me properly without any errors.
Please check your hardware, Operation System, browser version.
Please test all examples on http://harp.gl.s3-website-us-east-1.amazonaws.com/docs/master/examples/ on your device and others.

Related

mmenu wordpress plugin - bind open / close events

I am using the licenced wordpress plugin version 3.1.0.
I have the menu working, but I cannot access the mmenu API to trigger the button open / close effect I would like to use. Previously I have used the mmenu core version [not WP plugin] and triggered the class changes using this:
var $menu = $("#menu").mmenu({...})
var API = $menu.data("mmenu");
API.bind("open:finish", function () {
$("#menu-btn").addClass("is-active");
});
API.bind("close:finish", function () {
$("#menu-btn").removeClass("is-active");
});
Modifying the var API to use the plugin generated id fails with undefined, probably because the menu creation is managed in a different script.
var API = $('#mm-1').data("mmenu"); //'mm-1' - the plugin generated mmenu id
I have also tried to use jQuery direct on #menu-btn but it is not triggered unless I remove the #menu-btn from the mmenu settings. For example [not copied, just a rough example so please ignore syntax errors]:
$("#menu-btn").click(function(){console.log('click')});
all I need is to add / remove an 'is-active' class to the open menu link [id=menu-btn].
The mmenu adds a body class when opened, so added a mutation observer to check if the has the .mm-wrapper--opened class or not. If it does, add the 'is-active' class to the menu icon (which uses the .hamburger class) and if not, remove it.
if ($('body').hasClass('mm-wrapper--opened')){
$('.hamburger').addClass("is-active");
}
const targetNode = document.body;
const config = { childList : true, attributes: true };
const callback = function(mutationsList, observer) {
for(let mutation of mutationsList) {
if (mutation.type === 'attributes') {
if ($('body').hasClass('mm-wrapper--opened')){
setTimeout(() => { $('.hamburger').addClass("is-active"); }, 500);
}
else {
$('.hamburger').removeClass("is-active");
}
}
}
};
const observer = new MutationObserver(callback);
observer.observe(targetNode, config);

How do you get the currently active notebook name in JupyterLab?

I'm working on creating a server-side extension in JupyterLab and have been searching for quite a while for a way to get the currently active notebook name inside my index.ts file. I found this existing extension that gets the currently active tab name with ILabShell and sets the browser tab to have the same name. In my case I'll be triggering the process with a button on the notebook toolbar so the active tab will always be a notebook. However, when I try to use the code in the activate section of my extension, I get TypeError: labShell.currentChanged is undefined where labShell is an instance of ILabShell. That extension doesn't support JupyterLab 3.0+ so I believe that's part of the problem. However, currentChanged for ILabShell is clearly defined here. What if anything can I change to make it work? Is there another way to accomplish what I'm trying to do? I'm aware of things like this to get the notebook name inside the notebook but that's not quite what I'm trying to do.
Windows 10,
Node v14.17.0,
npm 6.14.13,
jlpm 1.21.1,
jupyter lab 3.0.14
I'm using this example server extension as a template: https://github.com/jupyterlab/extension-examples/tree/master/server-extension
index.ts file from the existing extension to get the current tab name:
import {
ILabShell,
JupyterFrontEnd,
JupyterFrontEndPlugin
} from '#jupyterlab/application';
import { Title, Widget } from '#lumino/widgets';
/**
* Initialization data for the jupyterlab-active-as-tab-name extension.
*/
const extension: JupyterFrontEndPlugin<void> = {
id: 'jupyterlab-active-as-tab-name',
autoStart: true,
requires: [ILabShell],
activate: (app: JupyterFrontEnd, labShell: ILabShell) => {
const onTitleChanged = (title: Title<Widget>) => {
console.log('the JupyterLab main application:', title);
document.title = title.label;
};
// Keep the session object on the status item up-to-date.
labShell.currentChanged.connect((_, change) => {
const { oldValue, newValue } = change;
// Clean up after the old value if it exists,
// listen for changes to the title of the activity
if (oldValue) {
oldValue.title.changed.disconnect(onTitleChanged);
}
if (newValue) {
newValue.title.changed.connect(onTitleChanged);
}
});
}
};
export default extension;
My index.ts file:
import {
ILabShell,
JupyterFrontEnd,
JupyterFrontEndPlugin
} from '#jupyterlab/application';
import { ICommandPalette } from '#jupyterlab/apputils';
import { ILauncher } from '#jupyterlab/launcher';
import { requestAPI } from './handler';
import { ToolbarButton } from '#jupyterlab/apputils';
import { DocumentRegistry } from '#jupyterlab/docregistry';
import { INotebookModel, NotebookPanel } from '#jupyterlab/notebook';
import { IDisposable } from '#lumino/disposable';
import { Title, Widget } from '#lumino/widgets';
export class ButtonExtension implements DocumentRegistry.IWidgetExtension<NotebookPanel, INotebookModel> {
constructor(app: JupyterFrontEnd) {
this.app = app;
}
readonly app: JupyterFrontEnd
createNew(panel: NotebookPanel, context: DocumentRegistry.IContext<INotebookModel>): IDisposable {
// dummy json data to test post requests
const data2 = {"test message" : "message"}
const options = {
method: 'POST',
body: JSON.stringify(data2),
headers: {'Content-Type': 'application/json'
}
};
// Create the toolbar button
let mybutton = new ToolbarButton({
label: 'Measure Energy Usage',
onClick: async () => {
// POST request to Jupyter server
const dataToSend = { file: 'nbtest.ipynb' };
try {
const reply = await requestAPI<any>('hello', {
body: JSON.stringify(dataToSend),
method: 'POST'
});
console.log(reply);
} catch (reason) {
console.error(
`Error on POST /jlab-ext-example/hello ${dataToSend}.\n${reason}`
);
}
// sample POST request to svr.js
fetch('http://localhost:9898/api', options);
}
});
// Add the toolbar button to the notebook toolbar
panel.toolbar.insertItem(10, 'MeasureEnergyUsage', mybutton);
console.log("MeasEnerUsage activated");
// The ToolbarButton class implements `IDisposable`, so the
// button *is* the extension for the purposes of this method.
return mybutton;
}
}
/**
* Initialization data for the server-extension-example extension.
*/
const extension: JupyterFrontEndPlugin<void> = {
id: 'server-extension-example',
autoStart: true,
optional: [ILauncher],
requires: [ICommandPalette, ILabShell],
activate: async (
app: JupyterFrontEnd,
palette: ICommandPalette,
launcher: ILauncher | null,
labShell: ILabShell
) => {
console.log('JupyterLab extension server-extension-example is activated!');
const your_button = new ButtonExtension(app);
app.docRegistry.addWidgetExtension('Notebook', your_button);
// sample GET request to jupyter server
try {
const data = await requestAPI<any>('hello');
console.log(data);
} catch (reason) {
console.error(`Error on GET /jlab-ext-example/hello.\n${reason}`);
}
// get name of active tab
const onTitleChanged = (title: Title<Widget>) => {
console.log('the JupyterLab main application:', title);
document.title = title.label;
};
// Keep the session object on the status item up-to-date.
labShell.currentChanged.connect((_, change) => {
const { oldValue, newValue } = change;
// Clean up after the old value if it exists,
// listen for changes to the title of the activity
if (oldValue) {
oldValue.title.changed.disconnect(onTitleChanged);
}
if (newValue) {
newValue.title.changed.connect(onTitleChanged);
}
});
}
};
export default extension;
There are two ways to fix it and one way to improve it. I recommend using (2) and (3).
Your order of arguments in activate is wrong. There is no magic matching of argument types to signature function; instead arguments are passed in the order given in requires and then optional. This means that you will receive:
...[JupyterFrontEnd, ICommandPalette, ILabShell, ILauncher]
but what you are expecting is:
...[JupyterFrontEnd, ICommandPalette, ILauncher, ILabShell]
In other words, optionals are always at the end. There is no static type check so this is a common source of mistakes - just make sure you double check the order next time (or debug/console.log to see what you are getting).
Actually, don't require ILabShell as a token. Use the ILabShell that comes in app.shell instead. This way your extension will be also compatible with other frontends built using JupyterLab components.
shell = app.shell as ILabShell
(optional improvement) install RetroLab as a development-only requirement and use import type (this way it is not a runtime requirement) to ensure compatibility with RetroLab:
import type { IRetroShell } from '#retrolab/application';
// ... and then in `activate()`:
shell = app.shell as ILabShell | IRetroShell
to be clear: not doing so would not make your extension incompatible; what it does is ensures you do not make it incompatible by depending on lab-specific behaviour of the ILabShell in the future.
So in total it would look like:
import {
ILabShell,
JupyterFrontEnd,
JupyterFrontEndPlugin
} from '#jupyterlab/application';
import type { IRetroShell } from '#retrolab/application';
// ...
const extension: JupyterFrontEndPlugin<void> = {
id: 'server-extension-example',
autoStart: true,
optional: [ILauncher],
requires: [ICommandPalette],
activate: async (
app: JupyterFrontEnd,
palette: ICommandPalette,
launcher: ILauncher | null
) => {
let shell = app.shell as ILabShell | IRetroShell ;
shell.currentChanged.connect((_, change) => {
console.log(change);
// ...
});
}
};
export default extension;

Integrate MPGS session.js in Aurelia SPA

I am trying to integrate the MasterCard Payment Gateway services to a SPA using Aurelia.
I am trying to use the hosted checkout mechanism to integrate MPGS.
I am writing code in the attached event of the Aurelia viewmodel to load the session.js library and on load of the library adding another script element to initialize the session.
The attached method is listed below.
this.mpgsSessionScript = `if (self === top) { var antiClickjack = document.getElementById("antiClickjack"); antiClickjack.parentNode.removeChild(antiClickjack); } else { top.location = self.location; } PaymentSession.configure({ fields: { card: { number: "#card-number", securityCode: "#card-cvv", expiryMonth: "#card-expiry-month", expiryYear: "#card-expiry-year" } }, frameEmbeddingMitigation: ["javascript"], callbacks: { initialized: function(response) { console.log(response); }, formSessionUpdate: function(response) { } } }); function pay() { PaymentSession.updateSessionFromForm('card'); }`;
this.styleElement = document.createElement('style');
this.styleElement.setAttribute('id', "antiClickjack");
this.styleElement.innerText = "body{display:none !important;}";
document.head.appendChild(this.styleElement);
this.scriptElement = document.createElement('script');
this.scriptElement.src = this.sessionJs;
this.scriptElement.onload = () => {
const innerScriptElement = document.createElement('script');
innerScriptElement.innerText = this.mpgsSessionScript;
document.body.appendChild(innerScriptElement);
};
document.body.appendChild(this.scriptElement);
I can successfully run the code the and the script elements are added to DOM and also, the antiClickjack style gets removed, which indicates that the script element gets added.
But the issue is, the card number and the cvv elements are not getting enabled for input. If successfully initialized, the card number and the cvv elements should get enabled.
I do not see any errors in the console. Any help would be appreciated.

Writing test specs for A-Frame

I'm totally new to VR and am working on a Vr space shooter in AFrame for a class project and was wondering if there is any documentation/standards for TDD in AFrame. Could anyone point me in the right direction?
Build your application almost entirely in A-Frame components: https://aframe.io/docs/0.4.0/guides/writing-a-component.html
Then test the components. Just about every component in the A-Frame codebase has unit tests: https://github.com/aframevr/aframe/tree/master/tests/components
The component template in angle also has a unit test setup. https://github.com/aframevr/angle/tree/master/templates/component (npm install -g angle && angle initcomponent for a standalone component).
The tests use Karma to spin up a real browser and execute code. It appends entities to the DOM, and attaches components with different property values, and asserts values. A basic example:
suite('foo component', function () {
var component;
var el;
setup(function (done) {
el = entityFactory();
el.addEventListener('componentinitialized', function (evt) {
if (evt.detail.name !== 'foo') { return; }
component = el.components.foo;
done();
});
el.setAttribute('foo', {});
});
suite('update', function () {
test('bar', function () {
el.setAttribute('foo', 'bar', 10);
assert.equal(component.baz, 10); // Assert something.
});
});
});

How to set up react-native integration test

In react-native doc, it says to check UIExploreIntegrationTest. It seems that it requires some setup on Xcode as it uses Objective C code(*.m). I'm new on Obj-C test.. May I know how to set up the integration test on Xcode?
With some guesswork I was able to nail down a few steps to get integration tests running on iOS. However I'm still figuring out how to get Android integration tests working.
Go ahead and copy IntegrationTests.js from the RN github and make a new JS file called Tests.js
Place both of these files in the root of your project. Then change IntegrationTests.js by going down and changing all of their requires to just one require statement for the file you just created require('./Tests')
Here is a basic implementation of what your Tests.js file should look like:
'use strict';
var React = require('react');
var ReactNative = require('react-native');
var {
Text,
View,
} = ReactNative;
var { TestModule } = ReactNative.NativeModules;
var Tests = React.createClass({
shouldResolve: false,
shouldReject: false,
propTypes: {
RunSampleCall: React.PropTypes.bool
},
getInitialState() {
return {
done: false,
};
},
componentDidMount() {
if(this.props.TestName === "SomeTest"){
Promise.all([this.SomeTest()]).then(()=>
{
TestModule.markTestPassed(this.shouldResolve);
});
return;
}
},
async SomeTest(){
var one = 1;
var two = 2;
var three = one + two;
if(three === 3){
this.shouldResolve = true;
}else{
this.shouldResolve = false;
}
}
render() : ReactElement<any> {
return <View />;
}
});
Tests.displayName = 'Tests';
module.exports = Tests;
Here is a basic implementation of your Tests.m file (inside xcode)
#import <UIKit/UIKit.h>
#import <XCTest/XCTest.h>
#import <RCTTest/RCTTestRunner.h>
#import "RCTAssert.h"
#define RCT_TEST(name) \
- (void)test##name \
{ \
[_runner runTest:_cmd module:##name]; \
}
#interface IntegrationTests : XCTestCase
#end
#implementation IntegrationTests
{
RCTTestRunner *_runner;
}
- (void)setUp
{
_runner = RCTInitRunnerForApp(#"IntegrationTests", nil);
}
- (void)test_SomeTest
{
[_runner runTest:_cmd
module:#"Tests"
initialProps:#{#"TestName": #"SomeTest"}
configurationBlock:nil];
}
#end
Also you need to add RCTTest from node_modules/react-native/Libraries/RCTTest/RCTTest.xcodeproj to your libraries. then you need to drag the product libRCTTest.a of that project you added to Linked Frameworks and Libraries for your main target in the general tab.
^^ that path might be slightly incorrect
Then you need to edit your scheme and set an environment variable CI_USE_PACKAGER to 1
So if you do all those steps you should have a simple test run and pass. It should be fairly easy to expand after that. Sorry if my answer is slightly sloppy, let me know if you have any questions.

Resources