I am creating a progressive web app using react and webpack.
I have successfully configured everything and able to start the development.
Now, i have many helper functions like :
function getCookie(name) {
var start = document.cookie.indexOf(name + "=");
var len = start + name.length + 1;
if ((!start) && (name != document.cookie.substring(0, name.length))) {
return null;
}
if (start == -1) return null;
var end = document.cookie.indexOf(';', len);
if (end == -1) end = document.cookie.length;
return unescape(document.cookie.substring(len, end));
}
So, for this i have created another js file : helper.jsx.
Now my helper.js contains the above function as it is. Now i want to use the above function in another react component.
I am doing a require in my component :
var helper = require("helper");
and trying to call the function using :
helper.getCookie('user');
Which is giving me helper.getCookie is not a defined.
Please tell me how can i create a helper js and use the functions of helper js in my react components.
You need to export the function using module.exports:
function getCookie(name) {
var start = document.cookie.indexOf(name + "=");
var len = start + name.length + 1;
if ((!start) && (name != document.cookie.substring(0, name.length))) {
return null;
}
if (start == -1) return null;
var end = document.cookie.indexOf(';', len);
if (end == -1) end = document.cookie.length;
return unescape(document.cookie.substring(len, end));
}
module.exports = {
getCookie: getCookie
};
Related
I'm working on a Javascript/web module bundler program that is written in C and a bit of JavaScript. I keep having a problem with the program where the program will randomly crash at a random malloc call in a random function. It only occurs when I use it on a more complicated project with far more files and will work fine if used on a smaller project. I've had errors with malloc and free that were being caused by memory leaks/errors in other parts of the program but as far as I can tell there is nothing wrong this time that is noticeable.
This is the error message that occurs:
RuntimeError: memory access out of bounds
at dlmalloc (wasm://wasm/007a3c2a:wasm-function[339]:0x7db59)
at ReadDataFromFile (wasm://wasm/007a3c2a:wasm-function[114]:0x4cfd8)
at BundleFile (wasm://wasm/007a3c2a:wasm-function[128]:0x55e36)
at BundleFiles (wasm://wasm/007a3c2a:wasm-function[130]:0x6b9fb)
at /mnt/c/Users/redstarbird/Documents/Projects/ArrowStack/Build/CFunctions.js:985:22
at Object.ccall (/mnt/c/Users/redstarbird/Documents/Projects/ArrowStack/Build/CFunctions.js:5328:22)
at /mnt/c/Users/redstarbird/Documents/Projects/ArrowStack/src/ArrowPack.js:104:24
The function that it crashes in looks like this:
char EMSCRIPTEN_KEEPALIVE *ReadDataFromFile(char *path)
{ // returns contents of file
printf("path: %s\n", path);
FILE *filePTR = fopen(path, "r");
if (filePTR == NULL)
{
printf("Error opening file %s\n", path);
return NULL;
}
fseek(filePTR, 0, SEEK_END); // seek to end of file
long int length = ftell(filePTR); // get length of file
fseek(filePTR, 0, SEEK_SET); // go back to start of file
char *buffer = malloc(length + 1); // This is where it crashes
if (buffer == NULL)
{
printf("Error creating buffer\n");
exit(1);
}
int currentChar = 0;
do
{
if (feof(filePTR))
{
break;
}
buffer[currentChar] = fgetc(filePTR);
currentChar++;
} while (1);
fclose(filePTR);
buffer[currentChar - 1] = '\0';
return buffer;
}
The project is compiled using this command:
emcc --no-entry -s INITIAL_MEMORY=128mb -Wl,--export=__heap_base -Wl,--export=__data_end -Wl,--export=malloc -Wl,--export=free -sENVIRONMENT=node --profiling -sRUNTIME_DEBUG=1 -fsanitize=undefined -sLLD_REPORT_UNDEFINED -g3 -sSTACK_OVERFLOW_CHECK=2 -sASSERTIONS=2 src/Main.c src/C/cJSON/cJSON.c src/DependencyGraph/DependencyGraph.c ./src/C/StringRelatedFunctions.c ./src/Regex/RegexFunctions.c ./src/DependencyGraph/FindDependencies.c ./src/SettingsSingleton/settingsSingleton.c ./src/C/ProblemHandler.c ./src/C/TextColors.c ./src/C/FileHandler.c ./src/C/IntFunctions.c ./src/Minifiers/HTMLMinifier.c ./src/C/FileTypesHandler.c ./src/C/Stack.c ./src/C/BundleFiles.c ./src/C/ProgressBar.c ./src/C/StringShiftHandler.c ./src/Minifiers/JSMinifier.c -s EXPORT_ES6=0 -s MODULARIZE -s USE_ES6_IMPORT_META=0 -s EXPORTED_RUNTIME_METHODS=["ccall"] -s NODERAWFS=1 -sBINARYEN=1 -sEXIT_RUNTIME=1 -sALLOW_MEMORY_GROWTH -o Build/CFunctions.js
The javascript code to initialise the webassembly looks like this:
#!/usr/bin/env node
"use strict";
// js wrapper for arrowpack for NPM
const fs = require("fs");
const path = require("path");
const chalk = require("chalk");
const settingsSingleton = require("./SettingsSingleton/settingsSingleton");
const DirFunctions = require("./js/DirFunctions");
const wasm_exec = require("../Build/wasm_exec.js");
const CFunctionFactory = require("../Build/CFunctions.js");
const go = new Go();
// const Sleep = require("../src/js/Sleep");
const { mkdirIfNotExists } = require("./js/DirFunctions.js");
var StartTime = performance.now();
const argv = require("yargs/yargs")(process.argv.slice(2))
.option("c", {
alias: "config-path",
describe: "Path to config file if not in working directory",
type: "string"
})
.help().argv;
var CONFIG_FILE_NAME = "ArrowPack-config.json"
if (argv.c) { CONFIG_FILE_NAME = path.join(argv.c, CONFIG_FILE_NAME) } else { console.log("no custom file thingy"); }
var rawconfigData = null;
if (fs.existsSync(CONFIG_FILE_NAME)) { rawconfigData = fs.readFileSync(CONFIG_FILE_NAME, "utf8"); }
var temp;
const Settings = new settingsSingleton(rawconfigData);
if (Settings.getValue("largeProject") === false) {
temp = DirFunctions.RecursiveWalkDir(Settings.getValue("entry")); // eventually add pluginAPI event here
} else {
let RecursiveWalkDirWASM = fs.readFileSync("../Build/RecursiveWalkDir.wasm"); const { WebAssembly } = require("wasi");
let compiledWalkDirWASM = WebAssembly.compile(wasm);
let InstanceWalkDirWASM = WebAssembly.instantiate(compiledWalkDirWASM);
const { InstanceWalkDirWASMExports } = instance;
temp = InstanceWalkDirWASMExports.walk_dir(Settings.getValue("entry"));
}
var WalkedFiles = temp.Files;
var WalkedDirs = temp.Directories;
console.log(WalkedDirs);
if (WalkedDirs) {
WalkedDirs.forEach(Dir => {
console.log(chalk.red(Dir));
var tempDir = Settings.getValue("exit") + Dir.substring(Settings.getValue("entry").length);
console.log(chalk.yellowBright(tempDir));
DirFunctions.mkdirIfNotExists(tempDir);
//DirFunctions.mkdirIfNotExists(Dir);
});
}
DirFunctions.mkdirIfNotExists("ARROWPACK_TEMP_PREPROCESS_DIR");
var AbsoluteFilesCharLength = 0;
var WrappedWalkedFiles = "";
if (WalkedFiles && WalkedFiles.length > 0) { // Paths are wrapped into one string because passing array of strings from JS to C is complicated
WalkedFiles.forEach(FilePath => { WrappedWalkedFiles += FilePath + "::"; console.log(chalk.bold.blue(FilePath)); AbsoluteFilesCharLength += FilePath.length; });
console.log(chalk.red(WalkedFiles.length));
var StructsPointer;
CFunctionFactory().then((CFunctions) => {
CFunctions._CheckWasm();
CFunctions._InitFileTypes();
for (let k in Settings.settings) {
if (CFunctions.ccall(
"SendSettingsString",
"number",
["string"],
[k]
) != 1) {
throw "Error sending Wasm settings string: " + k;
}
console.log(chalk.bold.blue(k));
// Gives time to apply settings
if (CFunctions.ccall(
"SendSettingsString",
"number",
["string"],
[Settings.settings[k].toString()]
) != 1) {
throw "Error sending Wasm settings string: " + Settings.settings[k];
}
console.log(chalk.bold.blue(Settings.settings[k]));
// Also gives time to apply settings
}
var Success;
// StructsPointer = CFunctions._CreateTree(allocateUTF8(WrappedWalkedFiles), WalkedFiles.length, AbsoluteFilesCharLength); // Need to get this working eventually for faster speed but couldn't work out allocateUTF8
StructsPointer = CFunctions.ccall(
"CreateGraph",
"number",
["string", "number"],
[WrappedWalkedFiles, WalkedFiles.length]
);
Success = CFunctions.ccall(
"BundleFiles",
"number",
["number"],
[StructsPointer]
);
if (Success === 1 || Success === 0) {
fs.rm("ARROWPACK_TEMP_PREPROCESS_DIR", { recursive: true }, (err) => {
if (err) { console.error(err); } else {
console.log("Sucessfully removed temporary preprocess directory");
}
});
DirFunctions.DeleteDirectory(); //CFunctions.ccall("PrintTimeTaken", "void", ["number", "number"], [StartTime, performance.now()]); // Not working for some reason
console.log(chalk.magentaBright("Bundling files completed in " + (performance.now() - StartTime) / 1000 + " seconds"));
}
});
// console.log("\n\nBuild completed in" + (EndTime - StartTime) / 1000 + " seconds!\n\n\n"); // Need to get Wasm code to run this because Wasm code seems to be non-blocking
/*
WebAssembly.instantiateStreaming(DependencyTreeWasmBuffer, DependencyTreeMemory).then((instance) => {
StructsPointer = instance.ccall(
"CreateTree",
"number",
["string", "number", "string"],
[WrappedWalkedFiles, WalkedFiles.length, settings.getValue("entry"), settings.getValue("exit")]
)
});
var GoWASMFileHandler;
const goWASM = fs.readFileSync("../Build/FileHandler.wasm");
WebAssembly.instantiate(goWASM, go.importObject).then(function (obj) {
GoWASMFileHandler = obj.instance;
go.run(GoWASMFileHandler);
GoWASMFileHandler.exports.HandleFiles(StructsPointer, settings.getValue("entry"));
});*/
}
The full code for the project is at https://github.com/redstarbird/arrowpack. Any help would be appreciated because I'm very stuck as to how to fix this.
I have a directive which takes in an array of container objects and $compiles a new container directive for each container and each nested container. It also compiles a resize handle before all containers except the first child. The link function looks like this:
//scope.dock is retrieved from a factory
scope.initContainers = function () {
var prevScope;
for (var i = 0; i < scope.dock.containers.length; i++) {
var newScope = scope.$new(true);
newScope.container = scope.dock.containers[i];
var newElement = '<panel-container class=\"' + scope.dock.containers[i].axis + '" ></panel-container>';
var newTemplate = $compile(newElement)(newScope);
if (i > 0) {
var sizerScope = scope.$new(true);
sizerScope.containerOne = prevScope;
sizerScope.containerTwo = newScope;
var sizerElement = '<resize-handle class=\"' + scope.dock.containers[i].axis + '"></resize-handle>';
var sizerTemplate = $compile(sizerElement)(sizerScope);
element.append(sizerTemplate);
}
element.append(newTemplate);
if (scope.dock.containers[i].containers.length > 0) {
generateContainers(scope.dock.containers[i], newScope, newTemplate);
}
}
return scope;
};
scope.sizeContainers = function () {
scope.$broadcast('size-containers');
};
var generateContainers = function (value, parentScope, parentElement) {
var prevScope;
for (var y = 0; y < value.containers.length; y++) {
var newChildScope = parentScope.$new(true);
newChildScope.container = value.containers[y];
var newChildElement = '<panel-container class=\"' + value.containers[y].axis + '" ></panel-container>';
var newChildTemplate = $compile(newChildElement)(newChildScope);
if (y > 0) {
var sizerScope = parentScope.$new(true);
sizerScope.containerOne = prevScope;
sizerScope.containerTwo = newChildScope;
var sizerElement = '<resize-handle class=\"' + value.containers[y].axis + '"></resize-handle>';
var sizerTemplate = $compile(sizerElement)(sizerScope);
parentElement.append(sizerTemplate);
}
parentElement.append(newChildTemplate);
if(typeof value.containers[y].containers !== 'undefined') {
if (value.containers[y].containers.length > 0) {
generateContainers(value.containers[y], newChildScope, newChildTemplate);
}
}
prevScope = newChildScope;
}
};
scope.initContainers().sizeContainers();
My problem is that the first child layer compiles but the second one does not. It does, however, work when I add scope.$apply to the end of generateContainers. Unfortunately for some reason it is skipping the first child element for each container and throwing a 'digest in progress' error.
Does anyone have any ideas on how to get this to compile?
And could someone explain why scope.$apply() is compiling the second layer only after I explicitly call it, even when $digest is already running?
I fixed this by getting rid of initContainers (since it was exactly the same as generateContainers) and moving that function to the container directive as well. That way the root directive wasn't trying to compile everything.
is it possible to render a specific page in a razor function. I tried #RenderPage but i cant figure out the path. Are there any built in functions to accomplish this?
Thanks Johan
Not really a C1 specific approach, but personally my best approach has been to just make a separate web-request for the page in question, parse out the html and render it.
This code can serve as an example, its a 1:1 of what i'm using. As you can see the trick is to find the element that wraps your content, in my example its the element inside that has an id equals to ContentColumnInner
public static string GetContentFromPage(Guid pageId)
{
var DomainName = HttpContext.Current.Request.Url.Authority;
var Uri = String.Format("http://{0}/page({1})", DomainName, pageId);
var request = WebRequest.Create(Uri);
// If required by the server, set the credentials.
request.Credentials = CredentialCache.DefaultCredentials;
// Get the response.
using (var response = (HttpWebResponse)request.GetResponseWithoutException())
{
if (response.StatusCode != HttpStatusCode.OK)
{
LogError("StatusCode: " + response.StatusCode);
return null;
}
// Get the stream containing content returned by the server.
using (var responseStream = response.GetResponseStream())
{
if (responseStream == null)
{
LogError("ResponseStream is null");
return null;
}
// Open the stream using a StreamReader for easy access.
using (var stream = new StreamReader(responseStream))
{
// Read the content.
var responseFromServer = stream.ReadToEnd();
var beforeBodyStartIndex = responseFromServer.IndexOf("<body", StringComparison.Ordinal);
var afterBodyEndIndex = responseFromServer.LastIndexOf("</body>", StringComparison.Ordinal) + 7;
var body = responseFromServer.Substring(beforeBodyStartIndex, afterBodyEndIndex - beforeBodyStartIndex);
try
{
var xmlDocument = XElement.Parse(body);
var content = xmlDocument.Descendants().FirstOrDefault(o => o.Attribute("id") != null && o.Attribute("id").Value.EndsWith("ContentColumnInner"));
if (content == null || !content.HasElements)
{
return null;
}
var reader = content.CreateReader();
reader.MoveToContent();
return reader.ReadInnerXml();
}
catch (XmlException ex)
{
LogError("Error parsing xml: " + ex.Message);
return null;
}
}
}
}
}
For what it's worth, I'm using angularjs and https://github.com/pc035860/angular-highlightjs. I want to know which language was detected and if there's any way to do this.
If this library doesn't do it, are there any that do?
You could search for the hljs class with JavaScript and then find the language class associated with it (assuming the language class is the last class). Example with jQuery:
function findLanguageOfHLJSWithID(id) {
var foundClasses = jQuery('#' + id + '.hljs').attr('class').split(' ');
return foundClasses[foundClasses.length - 1];
}
If you want all the languages highlighted on the page, use this function:
function findAllHLJSLanguages() {
var tempClasses = jQuery('.hljs'), foundClasses = [];
for (var iter = 0; iter < tempClasses.length; iter++) {
var tempClassesSplit = $(tempClasses[iter]).attr('class').split(' ');
foundClasses.push(tempClassesSplit[tempClassesSplit.length - 1]);
}
return foundClasses;
}
I am trying to implement named routes, so I don't have to write the whole path (often changes).
I was thinking I could get away with writing a service that would return the list of defined routes and a filter that would transform object to aroute
The use example would look like:
<a ng-href="{id:1}|route:'detail'">Click here!</a>
Provided I have added name:'detail' to my route definition, this would generate the following result :
Click here!
I think this is quite simple, but:
How can I get the list of defined routes ?
I was thinking I can make use of routeProvider , but AFAIK it has no public methods or attributes I can access.
turns out this is pretty straight forward:
http://plunker.co/edit/GNZxcvK4hfQ9LrlSvasK?p=preview
Components.filter('url', function ($route) {
function resolveRoute(options, route) {
var parts = route.split('/');
for (var i = 0; i < parts.length; i++) {
var part = parts[i];
if (part[0] === ':') {
parts[i] = options[part.replace(':', '')];
if (parts[i] == undefined) throw Error('Attribute \'' + part + '\' was not given for route \'' + route + '\'')
}
}
return parts.join('/');
}
return function (options, routeName) {
var routes = [];
angular.forEach($route.routes,function (config,route) {
if(config.name===routeName){
routes.push(route);
}
});
if (routes.length == 1) {
return resolveRoute(options, routes[0]);
}
else if (routes.length == 0) {
throw Error('Route ' + routeName + ' not found');
}
throw Error('Multiple routes matching ' + routeName + ' were found');
}
});