Nodejs + Rickshaw: src= reference not working - html

I am trying to make an app the generates 'live' graphs of Twitter word counts, basically trying to extend and exercise in Chapter 14 of NodeJS in 24 Hours. I decided to use 'Rickshaw' and I thought I'd start with simply getting a simple example working. However, while I can get a simple html page to load, I can't get a graph to display. Firefox debug indicates: "ReferenceError: Rickshaw is not defined [Break On This Error] graph = new Rickshaw.Graph( { " . That means that there is a referencing error but after a couple of hours of googling and reading, I'm not seeing it. The directory structure is correct; npm installed all modules correctly, no errors. Can anyone see what I'm missing?
Note: I am new to JS/Node and while the book is working in Express 2.x, I have been working in Express 3.x, so not sure if I've got the translation correct in all cases. The code is as follows:
package.json
{
"name":"socket.io-twitter-example",
"version": "0.0.1",
"private": "true",
"dependencies": {
"express": ">=2.5.4",
"rickshaw": ">=1.1.0"
}
}
app.js
var express = require('express'),
rickshaw = require('rickshaw'),
app = express(),
http = require('http'),
server = http.createServer(app)
server.listen(3000);
app.get('/', function (req,res) {
res.sendfile(__dirname + '/index.html');
});
index.html
<!DOCTYPE html>
<html lang="eng">
<head>
<meta charset="UTF-8" />
<title>Socket.IO Twitter Example</title>
</head>
<body>
<h1>Rickshaw Example</h1>
<div id="chart"></div>
<ul class="tweets"></ul>
<script type="text/javascript" src="node_modules/rickshaw/vendor/d3.v2.js"></script> //don't think "node_modules/" is required, but doesn't work without either
<script type="text/javascript" src="node_modules/rickshaw/rickshaw.min.js"></script>
<script>
graph = new Rickshaw.Graph( {
element: document.querySelector("#chart"),
width: 285,
height: 180,
series: [{
color: 'steelblue',
data: [
{ x: 0, y: 40 },
{ x: 1, y: 49 },
{ x: 2, y: 38 },
{ x: 3, y: 30 },
{ x: 4, y: 32 } ]
}]
});
graph.render();
</script>
</body>
</html>

You need to configure express.static middleware so that express knows where to look for static resources like js and css files:
app.use(express.static( __dirname + '/public'));
Its common to put such resources into a public folder (as shown in the example above) or static folder.
If you create a public folder and organize it like
app.js
public
rickshaw
vendor
d3.v2.js
rickshaw.min.js
then you'll be able to have the files correctly loaded in your html using
<script type="text/javascript" src="/rickshaw/vendor/d3.v2.js"></script>
<script type="text/javascript" src="/rickshaw/rickshaw.min.js"></script>
See this section of the express docs for more info on and examples of middleware.

Related

Mocha testcase is not running on chrome browser when we use import module in test spec files

We have been working on mocha and chai to write the unit test cases for the typescript project. But when we use the import module statement in the test spec file and launch html to run test cases on the browser, the mocha interface loads but no test cases run on the browser. It keeps on showing passes: 0
failures: 0
duration: 0s and the browser doesn't even throw some error to point out the exact issues.Browser snapshot
If we go to the sources folder in the browser then the test spec file, chai.js, and mocha.js load successfully.
Official steps have been followed to integrate the mocha and chai test cases.
Here is the sample code structure:
index.ts:
export class SampleClass {
sayHello() {
return "Hello, world!";
}
}
SampleSpec.ts
import { SampleClass } from "../src/index.js";
var expect = chai.expect;
var assert = chai.assert;
describe("Sample", () => {
it("says hello", () => {
console.log("Inside it block");
const sample = new SampleClass();
const result = "Hello";
expect(result).to.equal(sample.sayHello);
});
});
index.html:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Test</title>
<!-- <script src="../node_modules/chai/chai.js"></script>
<script src="../node_modules/mocha/mocha.js"></script> -->
<script src="https://cdn.jsdelivr.net/npm/chai#4.2.0/chai.js"></script>
<script src="https://cdn.jsdelivr.net/npm/mocha#10.2.0/mocha.js"></script>
</head>
<body>
<div id="mocha"></div>
<script type="module" src="../test/Castor.spec.js"></script>
<script>
mocha.setup("bdd");
mocha.run();
</script>
</body>
</html>
tsconfig:
{
"compilerOptions": {
"target": "ES2020",
"module": "ES2020",
"esModuleInterop": true,
"forceConsistentCasingInFileNames": true,
"strict": true,
"skipLibCheck": true
}
}
Note: It is working on safari and giving the right results of unit testing but not running on chrome browser.
Can someone help what's the issue here when running on chrome?

Upgrading from MathJax 2.7.5 to 3.0, trying to preserve a custom TeX environment

I use MathJax with my Jekyll blog on GitHub Pages. In fact, I wrote a blog post on exactly what steps I took to set up MathJax 2.7.5: "MathJax in Jekyll" (August 2018)
For a couple of posts, I wanted to use a psmallmatrix environment, like the one from the mathtools package: $$\begin{psmallmatrix} 1 \\ 0 \end{psmallmatrix}$$. I know how I would create such an environment in actual TeX, using the \newenvironment command: "How do I make a small pmatrix?"
But to get the command "pre-loaded" in MathJax 2.7.5, I was doing this, cargo-culting some code from MathJax's version of the AMSmath package:
<script type="text/x-mathjax-config">
MathJax.Hub.Config({
extensions: [
"MathMenu.js",
"MathZoom.js",
"AssistiveMML.js",
"a11y/accessibility-menu.js"
],
jax: ["input/TeX", "output/CommonHTML"],
TeX: {
extensions: [
"AMSmath.js",
"AMSsymbols.js",
"noErrors.js",
"noUndefined.js",
]
}
});
MathJax.Hub.Register.StartupHook("TeX Jax Ready",function () {
var TEX = MathJax.InputJax.TeX;
var COLS = function (W) {
var WW = [];
for (var i = 0, m = W.length; i < m; i++)
{WW[i] = TEX.Parse.prototype.Em(W[i])}
return WW.join(" ");
};
TEX.Definitions.Add({
environment: {
psmallmatrix: ['Array',null,'(',')','c',COLS([1/3]),".2em",'S',1],
}
});
});
</script>
<script type="text/javascript" async
src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.5/latest.js">
</script>
Sometime in the past year or so, MathJax 2.7.5 completely stopped working on GitHub, so I'm trying to upgrade to MathJax 3.0.
I have managed to translate the non-tricky parts of this config by using MathJax's own config converter, but I don't know what to do about my hand-crafted psmallmatrix.
Here's what I have now:
<script type="text/javascript">
window.MathJax = {
tex: {
packages: ['base', 'ams'],
},
loader: {
load: ['ui/menu', '[tex]/ams'],
},
};
</script>
<script type="text/javascript" id="MathJax-script" async
src="https://cdn.jsdelivr.net/npm/mathjax#3/es5/tex-chtml.js">
</script>
How can I recover my hand-crafted psmallmatrix environment, in MathJax 3.0? The formatting need only be roughly equivalent, as long as I can keep invoking it with \begin{psmallmatrix}.
I should mention that the MathJax docs on "Defining TeX Macros" give an example of how to "preload" the TeX parser with a macro, roughly equivalent to what \newcommand would do. The docs say:
window.MathJax = {
tex: {
macros: {
RR: "{\\bf R}",
bold: ["{\\bf #1}", 1]
}
}
};
But the docs are missing any examples of how to do the same kind of thing for \newenvironment.
Below is a configuration that adds the psmallmatrix environment to the AMS environment list. There should be a method to pre-configure environments that is similar to what is done for macros. I've made a feature request for it in the MathJax GitHub repository.
For now, add
<script>
MathJax = {
startup: {
ready() {
MathJax.startup.defaultReady();
const Macro = MathJax._.input.tex.Symbol.Macro;
const MapHandler = MathJax._.input.tex.MapHandler.MapHandler;
const Array = MathJax._.input.tex.ams.AmsMethods.AmsMethods.Array;
const env = new Macro('psmallmatrix', Array, [null,'(',')','c','.333em','.2em','S',1]);
MapHandler.getMap('AMSmath-environment').add('psmallmatrix', env);
}
}
};
</script>
as your configuration to enable the psmallmatrix environment.

Load graph from json using JointJS

I'm having a problem trying to load a graph form json using JointJS. I know the theory (https://resources.jointjs.com/tutorial/serialization), however, I still do not know how to show a graph.
This is my html file:
<!-- JointJS libraries omitted for space -->
<script src="https://code.jquery.com/jquery-1.12.4.min.js" integrity="sha256-ZosEbRLbNQzLpnKIkEdrPv7lOy9C27hHQ+Xp8a4MxAQ=" crossorigin="anonymous"></script>
<script type="text/javascript">
function read_json() {
$.getJSON("/jointsjdemo/demo.json", function(data) {
var graph = new joint.dia.Graph;
graph.fromJSON(data);
var paper = new joint.dia.Paper({
el: document.getElementById('myholder'),
model: graph,
width: 600,
height: 100,
gridSize: 1
});
});
}
read_json();
</script>
And this is my json file:
{"cells":[{"type":"standard.Rectangle","position":{"x":100,"y":30},"size":{"width":100,"height":40},"angle":0,"id":"42a7f123-1f0d-4d06-b49e-8cbcbbb17e23","z":1,"attrs":{"body":{"fill":"blue"},"label":{"fill":"white","text":"Hello"}}},{"type":"standard.Rectangle","position":{"x":400,"y":30},"size":{"width":100,"height":40},"angle":0,"id":"6ecac186-b9c1-4755-97db-704cd9b9156f","z":1,"attrs":{"body":{"fill":"blue"},"label":{"fill":"white","text":"World!"}}},{"type":"standard.Link","source":{"id":"42a7f123-1f0d-4d06-b49e-8cbcbbb17e23"},"target":{"id":"6ecac186-b9c1-4755-97db-704cd9b9156f"},"id":"fa23e165-3c9f-46f8-9fe9-e6660d4086ca","z":2,"attrs":{}}]}
When a load the web page, it shows nothing on screen. I'm deployed my app in Apache Tomcat. Using Chrome Developer Tools, no errors are shown in Console.
I dont know what I'm missing.
Any help please? The json file was generated through toJSON command.
P.D. I think it should be better to hire someone, but I'm still trying to do this.

Using Chrome to debug React TypeScript .tsx file - Webpack

I'm using webpack for bundling my js-files so normally I only see one big bundled file under sources in Chrome. However if I add a debugger; to my .tsx file I can see a single file just fine. My question is if I can get webpack to output all my files in Chrome Source so that I can browse them there and just click a row if I wan't the debugger to stop?
In the screenshot below I would like a folder for Scripts/src and then all my files.
Sample code:
index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/latest/css/bootstrap.min.css">
<title>App</title>
</head>
<body>
<div id="app"></div>
<script src="/Scripts/dist/bundle.js"></script>
</body>
</html>
index.tsx:
import * as React from "react";
import * as ReactDOM from "react-dom";
import * as ReactRouter from "react-router";
import * as ReactBootstrap from "react-bootstrap";
import { Test } from "./components/test";
ReactDOM.render(
<div>
<Test text="Well!" />
<Container />
</div>,
document.getElementById("app")
);
test.tsx:
import * as React from "react";
export interface ITestProps {
text: string
}
export class Test extends React.Component<ITestProps, {}> {
render() {
debugger;
return <div className="well">{this.props.text}</div>;
}
}
webpack.config.json:
var webpack = require('webpack');
var path = require("path");
var proxy = 'localhost:61299';
module.exports = {
entry: [
// activate HMR for React
'react-hot-loader/patch',
// the entry point of our app
'./Scripts/src/index.tsx',
],
output: {
filename: "./Scripts/dist/bundle.js",
},
// Enable sourcemaps for debugging webpack's output.
devtool: "source-map",
resolve: {
// Add '.ts' and '.tsx' as resolvable extensions.
extensions: [".webpack.js", ".web.js", ".ts", ".tsx", ".js"]
},
module: {
loaders: [
{ test: /\.tsx?$/, loader: ['react-hot-loader/webpack', 'ts-loader'] }
]
},
plugins: [
// enable HMR globally
new webpack.HotModuleReplacementPlugin(),
// prints more readable module names in the browser console on HMR updates
new webpack.NamedModulesPlugin(),
],
devServer: {
proxy: {
'*': {
target: 'http://' + proxy,
}
},
port: 8080,
host: '0.0.0.0',
hot: true,
},
}
Since you already generate source maps with webpack (devtool: "source-map") this should already work ;)
Instead of viewing sources in "localhost", use the webpack:// item in the chrome debugger. This is the last item in your screenshot.
If the generation of the source maps works correctly you should have your source folder structure there. It may be contained in an folder called ..
For example:
I have to warn you though. Sometimes source maps don't work correctly and you break points end ups somewhere else :-x

not well-formed Source File in mozilla firefox

Following is the content of my JSON File -
{
"tags": [
"Red",
"Green",
"Blue",
"Yellow"
]
}
I checked this with jsonlint but still I am getting the following error in firefox.
Timestamp: Wednesday 18 June 2014 10:39:41 IST Error: not well-formed
Source File:
file:///home/trialcode/trialcode/Projects/ang/18-06-2014/ang/content.json
Line: 1, Column: 1 Source Code: {
I am not sure what I am doing wrong if any.
FYI -
OS - Linux Ubuntu 12.04
Firefox - 24.0
EDIT
I am using the content of content.json file in angular controller via $http.get method.
I explored more about this kind of error and found it is related with the Content-Type setting.
Following is the full code -
<!doctype html>
<html lang="en" ng-app="app">
<head>
<title>JSON Read In Angularjs</title>
<meta charset="UTF-8" />
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.10/angular.min.js"></script>
<script>
var app = angular.module('app', []);
app.controller('myCtrl', function($scope, $http){
$scope.data = {};
$http.get('content.json').success(function(data) {
$scope.data = data;
});
});
</script>
</head>
<body ng-controller="myCtrl">
<ul>
<li ng-repeat="em in data.tags">{{em}}</li>
</ul>
</body>
</html>
How do I set the content type if that is a problem. I searched HERE but unable to fix it. Help me Please if any.
After few hours of searching I came across that -
Chrome and other modern browsers have implemented security
restrictions for Cross Origin Requests, which means that you cannot
load anything through file:/// , you need to use http:// protocol at
all times, even locally -due Same Origin policies.
Source -
Cross Origin Script Stackoverflow Answer
Simple Solution For Local Cross Origin Requests