Require not working when used in jupyter/ipython notebook - requirejs

When I write the following code in jupyter opened from my system, it is working, but when I open it from another system it is not. The problem is with require(it is not running). I have put some consoles to see where it is stopping and it is running till console.log(require.s.contexts._.defined). I have checked the modules with this console and angular seems to be missing in this. Thanks in advance.
%%javascript
require.config({
paths: {
velocity: "https://cdn.jsdelivr.net/velocity/1.2.3/velocity.min",
interact: "https://cdn.jsdelivr.net/interact.js/1.2.6/interact.min",
angular: "https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.8/angular.min"
},
shim: {
'angular': {
exports: 'angular'
}
}
});
function start_application(data) {
// console.log("data ready")
console.log(require.s.contexts._.defined)
require(['angular', 'jquery'], function(angular,$) {
console.log("require running")
$.ajax({url: "http://localhost:8889/tree/Jupyter_Angular/DQAForm.html",
success: function(result) {
// console.log("SUCCESS")
// console.log(result);
$("#DQAFormContainer").html(result)
var el = document.getElementById("dqaBrickContent");
if(angular.element(el).injector()){
angular.element(el).injector().get('$rootScope').$destroy()
}
var dqaBrick = angular.module('dqaBrick', []);
dqaBrick.controller('dqaBrickCtrl', ['$scope', function ($scope) {
$scope.myVariable = 'Starting new DQA Brick';
console.log($scope.myVariable);
$scope.showPanel = 1;
$scope.openPanel = function (panelNum) {
$scope.showPanel = panelNum;
// console.log(panelNum);
}
}]);
angular.element(document).ready(function() {
angular.bootstrap(el, ['dqaBrick']);
});
}
});
})
}
var callbacks = {
iopub : {
output : start_application
}
}
var kernel = IPython.notebook.kernel
kernel.execute('print("This is the starting")', callbacks)

Related

vuejs nextick don't update

i try to connect my frontend to my backend,
the request is done correctly i received the correct data, but the DOM is not updating. I use this.$nextTick but it doesn't affect the update
in the template i use {{ system.CPU.avgload }}
like i said the fetch is done correctly it pass into nexttick, but nothing change
in the main vue i have this
import System from '../utils/system'
import Auth from '../utils/auth'
export default {
created: function () {
this.system = {
CPU: {
avgload: 0
}
}
},
mounted: function () {
this.fetchData()
setInterval(function () {
this.fetchData()
}.bind(this), 10000)
},
methods: {
fetchData () {
if (!Auth.checkAuth) {
console.log('test')
this.error = true
} else {
var self = this
this.$nextTick(function () {
System.Get(function (response) {
self.system = response
})
})
}
}
}
}
and the template is
<div class="text-xs-left" id="example-caption-1">CPU : {{ system.CPU.avgload }} %</div>
You have to add variable system in the data section of vue instance. Than only this variable will become reactive and available in the HTML.
export default {
data: function () {
return { system: {
CPU: {
avgload : ""
}
}
}
}
...
...

running e2e testing with aurelia cli

I'm trying to implement a few e2e tests in my aurelia-cli app. I've tried looking for docs or blogs but haven't found anything on e2e setup for the cli. I've made the following adjustments to the project.
first I added this to aurelia.json
"e2eTestRunner": {
"id": "protractor",
"displayName": "Protractor",
"source": "test/e2e/src/**/*.ts",
"dist": "test/e2e/dist/",
"typingsSource": [
"typings/**/*.d.ts",
"custom_typings/**/*.d.ts"
]
},
Also added the e2e tasks on aurelia_project/tasks:
e2e.ts
import * as project from '../aurelia.json';
import * as gulp from 'gulp';
import * as del from 'del';
import * as typescript from 'gulp-typescript';
import * as tsConfig from '../../tsconfig.json';
import {CLIOptions} from 'aurelia-cli';
import { webdriver_update, protractor } from 'gulp-protractor';
function clean() {
return del(project.e2eTestRunner.dist + '*');
}
function build() {
var typescriptCompiler = typescriptCompiler || null;
if ( !typescriptCompiler ) {
delete tsConfig.compilerOptions.lib;
typescriptCompiler = typescript.createProject(Object.assign({}, tsConfig.compilerOptions, {
// Add any special overrides for the compiler here
module: 'commonjs'
}));
}
return gulp.src(project.e2eTestRunner.typingsSource.concat(project.e2eTestRunner.source))
.pipe(typescript(typescriptCompiler))
.pipe(gulp.dest(project.e2eTestRunner.dist));
}
// runs build-e2e task
// then runs end to end tasks
// using Protractor: http://angular.github.io/protractor/
function e2e() {
return gulp.src(project.e2eTestRunner.dist + '**/*.js')
.pipe(protractor({
configFile: 'protractor.conf.js',
args: ['--baseUrl', 'http://127.0.0.1:9000']
}))
.on('end', function() { process.exit(); })
.on('error', function(e) { throw e; });
}
export default gulp.series(
webdriver_update,
clean,
build,
e2e
);
and the e2e.json
{
"name": "e2e",
"description": "Runs all e2e tests and reports the results.",
"flags": []
}
I've added a protractor.conf file and aurelia.protractor to the root of my project
protractor.conf.js
exports.config = {
directConnect: true,
// Capabilities to be passed to the webdriver instance.
capabilities: {
'browserName': 'chrome'
},
//seleniumAddress: 'http://0.0.0.0:4444',
specs: ['test/e2e/dist/*.js'],
plugins: [{
path: 'aurelia.protractor.js'
}],
// Options to be passed to Jasmine-node.
jasmineNodeOpts: {
showColors: true,
defaultTimeoutInterval: 30000
}
};
aurelia.protractor.js
/* Aurelia Protractor Plugin */
function addValueBindLocator() {
by.addLocator('valueBind', function (bindingModel, opt_parentElement) {
var using = opt_parentElement || document;
var matches = using.querySelectorAll('*[value\\.bind="' + bindingModel +'"]');
var result;
if (matches.length === 0) {
result = null;
} else if (matches.length === 1) {
result = matches[0];
} else {
result = matches;
}
return result;
});
}
function loadAndWaitForAureliaPage(pageUrl) {
browser.get(pageUrl);
return browser.executeAsyncScript(
'var cb = arguments[arguments.length - 1];' +
'document.addEventListener("aurelia-composed", function (e) {' +
' cb("Aurelia App composed")' +
'}, false);'
).then(function(result){
console.log(result);
return result;
});
}
function waitForRouterComplete() {
return browser.executeAsyncScript(
'var cb = arguments[arguments.length - 1];' +
'document.querySelector("[aurelia-app]")' +
'.aurelia.subscribeOnce("router:navigation:complete", function() {' +
' cb(true)' +
'});'
).then(function(result){
return result;
});
}
/* Plugin hooks */
exports.setup = function(config) {
// Ignore the default Angular synchronization helpers
browser.ignoreSynchronization = true;
// add the aurelia specific valueBind locator
addValueBindLocator();
// attach a new way to browser.get a page and wait for Aurelia to complete loading
browser.loadAndWaitForAureliaPage = loadAndWaitForAureliaPage;
// wait for router navigations to complete
browser.waitForRouterComplete = waitForRouterComplete;
};
exports.teardown = function(config) {};
exports.postResults = function(config) {};
and I added a sample test in my test/e2e/src folder it doesn't get executed. I've also tried implementing a e2e test within the unit test folder since when I run au test I see that a chrome browser opens up.
describe('aurelia homepage', function() {
it('should load page', function() {
browser.get('http://www.aurelia.io');
expect(browser.getTitle()).toEqual('Home | Aurelia');
});
});
But this throws the error browser is undefined. Am I missing something with e2e testing with the cli? I know aurelia-protractor comes pre-installed but I don't see any way to run it.
I know this is a very late answer, but perhaps for others looking for an answer, you could try to import from the aurelia-protractor plugin
import {browser} from 'aurelia-protractor-plugin/protractor';

Magento2 Override existing js component

I want to override the existing magento2 JS Component in my theme for some more customization.
Magento_Checkout/js/view/minicart.js
Above JS component i want to override and i want to add some more operation on the remove button event.
You can try "map" of require js. I used this and working for me. following is the requirejs-config.js inside my theme.
var config = {
map: {
'*': {
'Magento_Checkout/js/view/minicart':'js/custom/minicart'
}
}
};
Modified minicart.js file is placed inside "web/js/custom" folder inside my theme.
Just Go to your theme Override Magento_Checkout there, then under web folder make path as same as core module then add your js file & do required changes. It will reflect on frontend.
You can also extend an existing Magento JS without overwriting the whole file in your module add the require-config.js
app/code/MyVendor/MyModule/view/frontend/requirejs-config.js
var config = {
config: {
mixins: {
'Magento_Checkout/js/view/minicart': {
'MyVendor_MyModule/js/minicart': true
}
}
}
};
Then add the minicart.js
app/code/MyVendor/MyModule/view/frontend/web/js/minicart.js
define([], function () {
'use strict';
return function (Component) {
return Component.extend({
/**
* #override
*/
initialize: function () {
var self = this;
return this._super();
},
MyCustomFunction: function () {
return "my function";
}
});
}
});
define(['jquery'],function ($) {
'use strict';
var mixin = {
/**
*
* #param {Column} elem
*/
initSidebar: function () {
var sidebarInitialized = false, miniCart;
miniCart = $('[data-block=\'minicart\']');
if (miniCart.data('mageSidebar')) {
miniCart.sidebar('update');
}
if (!$('[data-role=product-item]').length) {
return false;
}
miniCart.trigger('contentUpdated');
if (sidebarInitialized) {
return false;
}
sidebarInitialized = true;
miniCart.sidebar({
'targetElement': 'div.block.block-minicart',
'url': {
'checkout': window.checkout.checkoutUrl,
'update': window.checkout.updateItemQtyUrl,
'remove': window.checkout.removeItemUrl,
'loginUrl': window.checkout.customerLoginUrl,
'isRedirectRequired': window.checkout.isRedirectRequired
},
'button': {
'checkout': '#top-cart-btn-checkout',
'remove': '#mini-cart a.action.delete',
'increacseqty':'#mini-cart a.action.increase-qty',
'decreaseqty':'#mini-cart a.action.decrease-qty',
'close': '#btn-minicart-close'
},
'showcart': {
'parent': 'span.counter',
'qty': 'span.counter-number',
'label': 'span.counter-label'
},
'minicart': {
'list': '#mini-cart',
'content': '#minicart-content-wrapper',
'qty': 'div.items-total',
'subtotal': 'div.subtotal span.price',
'maxItemsVisible': window.checkout.minicartMaxItemsVisible
},
'item': {
'qty': ':input.cart-item-qty',
'button': ':button.update-cart-item'
},
'confirmMessage': $.mage.__('Are you sure you would like to remove this item from the shopping cart??')
});
return this._super();
}
};
return function (minicart) { // target == Result that Magento_Ui/.../columns returns.
return minicart.extend(mixin); // new result that all other modules receive
};
});

require.js listener or callback

I am loading a 3rd party script that simply creates an overlay on a site it has been loaded onto. It works fine but sites using require.js seem to have intermittent issues I'm assuming with async loading some js files. Is there any type of callback or way to create a module in the DOM as sort of a listener to see if require.js is done loading?
I tried this but not even close:
define(function() {
alert('test');
return {};
});
and
define('myModule',
function () {
var myModule = {
doStuff:function(){
console.log('Yay! Stuff');
}
};
return myModule;
});
console.log(myModule);
I ended up just creating a secondary require.config file and loading the module with require if require is detected, seems to work fine.
if(typeof require === 'function') {
var base = 'http://' + someDomainVar;
function getJSTreeURL() {
var url = base + '/js/libs/jstree.min';
return url;
}
function getModuleURL() {
var url = base + '/module';
return url;
}
var reqTwo = require.config({
context: "instance2",
baseUrl: "instance2",
paths: {
'jq': 'http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min',
'jqTree': getJSTreeURL(),
'module': getModuleURL()
},
shim: {
'jq': {
exports: 'jq'
},
'jqTree': {
deps: ['jq'],
exports: 'jqTree'
},
'module': {
deps: ['jq', 'jqTree'],
exports: 'module'
}
}
});
reqTwo(['require', 'jq', 'jqTree'],
function(require, jq, jqTree) {
setTimeout(function() {
require(['module'],
function(module) {
console.log('loaded');
}
);
}, 0);
});

problems with databinding with angularjs

Hy folks, I got a problem with databinding. I tried since ages to figure out why my few has no access to my global.user provided by a service.
Could somebody figure out whats happening. Thank in advance. best regards Thomas
profile.html
<section data-ng-controller="MyprofileController">
<h1>{{global.current_User()}}</h1>
</section>
myprofile.js
'use strict';
angular.module('mean.system').controller('MyprofileController', ['$scope', 'Global', function ($scope, Global) {
$scope.global = Global;
$scope.test = 'testcase';}]);
service
'use strict';
//Global service for global variables
angular.module('mean.system').factory('Global', [
function() {
var current_user = window.user;
return {
current_User: function() {
return current_user;
},
isloggedIn: function() {
return !!current_user;
}
};
}
]);
thanks a lot for your help.
Just found out that firefox does print an error message!
Error: [ng:areq] Argument 'MyprofileController' is not a function, got undefined
http://errors.angularjs.org/1.2.11/ng/areq?
p0=MyprofileController&p1=not%20a%20function%2C%20got%20undefined
minErr/<#http://localhost:3000/lib/angular/angular.js:78
assertArg#http://localhost:3000/lib/angular/angular.js:1363
assertArgFn#http://localhost:3000/lib/angular/angular.js:1374
#http://localhost:3000/lib/angular/angular.js:6774
nodeLinkFn/<#http://localhost:3000/lib/angular/angular.js:6186
forEach#http://localhost:3000/lib/angular/angular.js:310
nodeLinkFn#http://localhost:3000/lib/angular/angular.js:6173
compositeLinkFn#http://localhost:3000/lib/angular/angular.js:5637
publicLinkFn#http://localhost:3000/lib/angular/angular.js:5542
ngViewFillContentFactory/<.link#http://localhost:3000/lib/angular-route/angular-
route.js:915
nodeLinkFn#http://localhost:3000/lib/angular/angular.js:6228
compositeLinkFn#http://localhost:3000/lib/angular/angular.js:5637
publicLinkFn#http://localhost:3000/lib/angular/angular.js:5542
boundTranscludeFn#http://localhost:3000/lib/angular/angular.js:5656
controllersBoundTransclude#http://localhost:3000/lib/angular/angular.js:6248
update#http://localhost:3000/lib/angular-route/angular-route.js:865
Scope.prototype.$broadcast#http://localhost:3000/lib/angular/angular.js:12245
updateRoute/<#http://localhost:3000/lib/angular-route/angular-route.js:556
qFactory/defer/deferred.promise.then/wrappedCallback#http:
//localhost:3000/lib/angular/angu lar.js:10949
qFactory/defer/deferred.promise.then/wrappedCallback#http:
//localhost:3000/lib/angular/angu lar.js:10949
qFactory/ref/<.then/<#http://localhost:3000/lib/angular/angular.js:11035
Scope.prototype.$eval#http://localhost:3000/lib/angular/angular.js:11961
Scope.prototype.$digest#http://localhost:3000/lib/angular/angular.js:11787
Scope.prototype.$apply#http://localhost:3000/lib/angular/angular.js:12067
#http://localhost:3000/lib/angular/angular.js:9202
createEventHandler/eventHandler/<#http://localhost:3000/lib/angular/angular.js:2613
forEach#http://localhost:3000/lib/angular/angular.js:310
createEventHandler/eventHandler#http://localhost:3000/lib/angular/angular.js:2612
<section class="ng-scope" data-ng-view="">
It should work, and it does in a Fiddle I've created: http://jsfiddle.net/BernhardW/mLQWs/
window.user = 'John Doe';
angular.module('mean.system', []);
angular.module('mean.system').controller('MyprofileController', function ($scope, Global) {
$scope.global = Global;
$scope.test = 'testcase';
});
angular.module('mean.system').factory('Global', function() {
var current_user = window.user;
return {
current_User: function() {
return current_user;
},
isloggedIn: function() {
return !!current_user;
}
};
});
Are there any errors showing?

Resources