I've downloaded a repository from Git to make amendments to it however, I can't seem to compile it and make it run.
I was prompted to install node modules, #ionic/cli-pl
ugin-gulp and also #ionic/cli-plugin-ionic1 as this was an ionic1 based project.
I keep receiving this error:
C:\Users\User1\Desktop\belfastsalah-master\belfastsalah-master\node_modules\#ionic\cli-plugin-ionic1\dist\serve\live-reload.js:19
let contentStr = content.toString();
^
TypeError: Cannot read property 'toString' of undefined
at Object.injectLiveReloadScript (C:\Users\User1\Desktop\belfastsalah-master\belfastsalah-master\node_modules\#ionic\cli-plugin-ionic1\dist\serve\live-reload.js:19:29)
at ReadFileContext.fs.readFile [as callback] (C:\Users\User1\Desktop\belfastsalah-master\belfastsalah-master\node_modules\#ionic\cli-plugin-ionic1\dist\serve\http-server.js:59:39)
at FSReqWrap.readFileAfterOpen [as oncomplete] (fs.js:366:13)
Below is the code from the JS file the error appears in however, this hasn't been modified by me. It is what I was prompted to install as stated above.
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const path = require("path");
const modules_1 = require("../lib/modules");
function createLiveReloadServer(options) {
const tinylr = modules_1.load('tiny-lr');
const liveReloadServer = tinylr();
liveReloadServer.listen(options.livereloadPort, options.address);
return (changedFiles) => {
liveReloadServer.changed({
body: {
files: changedFiles.map(changedFile => ('/' + path.relative(options.wwwDir, changedFile)))
}
});
};
}
exports.createLiveReloadServer = createLiveReloadServer;
function injectLiveReloadScript(content, host, port) {
let contentStr = content.toString();
const liveReloadScript = getLiveReloadScript(host, port);
if (contentStr.indexOf('/livereload.js') > -1) {
return content;
}
let match = contentStr.match(/<\/body>(?![\s\S]*<\/body>)/i);
if (!match) {
match = contentStr.match(/<\/html>(?![\s\S]*<\/html>)/i);
}
if (match) {
contentStr = contentStr.replace(match[0], `${liveReloadScript}\n${match[0]}`);
}
else {
contentStr += liveReloadScript;
}
return contentStr;
}
exports.injectLiveReloadScript = injectLiveReloadScript;
function getLiveReloadScript(host, port) {
if (host === '0.0.0.0') {
host = 'localhost';
}
const src = `//${host}:${port}/livereload.js?snipver=1`;
return ` <!-- Ionic Dev Server: Injected LiveReload Script -->\n` + ` <script src="${src}" async="" defer=""></script>`;
}
Any help would be greatly appreciated.
Thanks
You should check if, after all bundling/generation is done, www/index.html exists
Had this problem after extensive experiments with index.html generation what resulted with it being gone ;)
Related
I do not have any idea why do I have this error. Everything seems ok. Can you please help me to solve this?
The plugins file is missing or invalid.
Your pluginsFile is set to /Users/gnematova/AMPautomation/AMPautomation/cypress/plugins/index.js, but either the file is missing, it contains a syntax error, or threw an error when required. The pluginsFile must be a .js, .ts, or .coffee file.
Or you might have renamed the extension of your pluginsFile. If that's the case, restart the test runner.
Please fix this, or set pluginsFile to false if a plugins file is not necessary for your project.
Error: Cannot find module 'cypress-cucumber-preprocessor'
Stack trace
plugins->index.js
const cucumber = require('cypress-cucumber-preprocessor').default;
/**
* #type {Cypress.PluginConfig}
*/
module.exports = (on, config) => {
require('cypress-mochawesome-reporter/plugin')(on);
on('file:preprocessor', cucumber());
on('before:browser:launch', (browser = {}, launchOptions) => {
console.log(launchOptions.args);
if (browser.family === 'chromium' && browser.name !== 'electron') {
launchOptions.args.push('--start-fullscreen');
launchOptions.args.push('--window-size=1400,1200');
}
if (browser.name === 'electron') {
launchOptions.preferences.fullscreen = true;
}
if (browser.name === 'chrome' && browser.isHeadless) {
launchOptions.args.push('--disable-gpu');
}
return launchOptions;
});
return config;
};
I have a problem, when I debug on visual studio code, it gives me this error message "Uncaught Error: Cannot find module './command/$(files)'
Require stack:
"c:\Users\user\OneDrive\Bureau\himetsubabot\index.js"
however I put the right path and my file is called commande, here is the code
const fs = require('fs');
const Discord = require('discord.js');
const bot = new Discord.Client()
const config = require ("./config.js");
bot.commands = new Discord.Collection();
const commandFiles = fs.readdirSync('./commande').filter(file => file.endsWith('.js'));
for (const file of commandFiles) {
const command = require('./commande/$(files)')
client.command.set(command.name, command)
}
bot.on("ready", async message => {
console.log("Le bot démarre")
bot.user.setStatus('online')
bot.user.setActivity("en développement")
})
bot.on('message', async (msg) => {
if(msg.content.startsWith(config.prefix) && !msg.author.bot){
cmdArray = msg.content.substring(config.prefix.length).split(" ");
cmd = cmdArray[0];
args = cmdArray.slice(1);
let command = commands.getCommand(cmd);
if(command) command.run(bot, msg, args);
if(cmd === '8ball'){}
}
})
bot.login(config.token)
Instead of using "('/commande/$(files)')" use "('./commande/${files}')".
What i mean is to use ${files} instead of $(files).
The Coverage tool is good at finding used and unused code. However, there doesn't appear to be a way to save or export only the used code. Even hiding unused code would be helpful.
I'm attempting to reduce the amount of Bootstrap CSS in my application; the file is more than 7000 lines. The only way to get just the used code is to carefully scroll thru the file, look for green sections, then copy that code to a new file. It's time-consuming and unreliable.
Is there a different way? Chrome 60 does not seem to have added this functionality.
You can do this with puppeteer
(async () => {
const browser = await puppeteer.launch();
const page = await browser.newPage()
//Start sending raw DevTools Protocol commands are sent using `client.send()`
//First off enable the necessary "Domains" for the DevTools commands we care about
const client = await page.target().createCDPSession()
await client.send('Page.enable')
await client.send('DOM.enable')
await client.send('CSS.enable')
const inlineStylesheetIndex = new Set();
client.on('CSS.styleSheetAdded', stylesheet => {
const { header } = stylesheet
if (header.isInline || header.sourceURL === '' || header.sourceURL.startsWith('blob:')) {
inlineStylesheetIndex.add(header.styleSheetId);
}
});
//Start tracking CSS coverage
await client.send('CSS.startRuleUsageTracking')
await page.goto(`http://localhost`)
// const content = await page.content();
// console.log(content);
const rules = await client.send('CSS.takeCoverageDelta')
const usedRules = rules.coverage.filter(rule => {
return rule.used
})
const slices = [];
for (const usedRule of usedRules) {
// console.log(usedRule.styleSheetId)
if (inlineStylesheetIndex.has(usedRule.styleSheetId)) {
continue;
}
const stylesheet = await client.send('CSS.getStyleSheetText', {
styleSheetId: usedRule.styleSheetId
});
slices.push(stylesheet.text.slice(usedRule.startOffset, usedRule.endOffset));
}
console.log(slices.join(''));
await page.close();
await browser.close();
})();
You can do this with Headless Chrome and puppeteer:
In a new folder install puppeteer using npm (this will include Headless Chrome for you):
npm i puppeteer --save
Put the following in a file called csscoverage.js and change localhost to point to your website.
:
const puppeteer = require('puppeteer');
const util = require('util');
const fs = require("fs");
(async () => {
const browser = await puppeteer.launch();
const page = await browser.newPage();
await page.coverage.startCSSCoverage();
await page.goto('https://localhost'); // Change this
const css_coverage = await page.coverage.stopCSSCoverage();
console.log(util.inspect(css_coverage, { showHidden: false, depth: null }));
await browser.close();
let final_css_bytes = '';
let total_bytes = 0;
let used_bytes = 0;
for (const entry of css_coverage) {
final_css_bytes = "";
total_bytes += entry.text.length;
for (const range of entry.ranges) {
used_bytes += range.end - range.start - 1;
final_css_bytes += entry.text.slice(range.start, range.end) + '\n';
}
filename = entry.url.split('/').pop();
fs.writeFile('./'+filename, final_css_bytes, error => {
if (error) {
console.log('Error creating file:', error);
} else {
console.log('File saved');
}
});
}
})();
Run it with node csscoverage.js
This will output all the CSS you're using into the separate files they appear in (stopping you from merging external libraries into your own code, like the other answer does).
I talked with the engineer who owns this feature. As of Chrome 64 there's still no way to export the results of a coverage analysis.
Star issue #717195 to help the team prioritize this feature request.
I love this simple solution. It works with the Coverage tool in Chrome without any further installation. You can simply use the json file that the Coverage tool lets you export:
https://nachovz.github.io/devtools-coverage-css-generator/
But be aware of the comment below my answer!!! He is right, it's risky. I am still hoping / waiting for an update.
first of all you need to download and install "Google Chrome Dev".
on Google chrome Dev go to Inspect element > Sources > Ctrl+shift+p
Enter "coverage" and select "Start Instrumenting coverage and reload Page"
Then use Export icon
this will give you a json file.
you can also visit : Chrome DevTools: Export your raw Code Coverage Data
I downloaded the latest version of canary and the export button was present.
I then used this PHP script to parse the json file returned. (Where key '6' in the array is the resource to parse). I hope it helps someone!
$a = json_decode(file_get_contents('coverage3.json'));
$sText = $a[6]->text;
$sOut = "";
foreach ($a[6]->ranges as $iPos => $oR) {
$sOut .= substr($sText, $oR->start, ($oR->end-$oR->start))." \n";
}
echo '<style rel="stylesheet" type="text/css">' . $sOut . '</style>';
Chrome canary 73 can do it. You will need Windows or Mac OS. There is an export function (Down arrow icon) next to the record and clear buttons. You'll get a json file and then you can use that to programmatically remove the unused lines.
Here's a version that will keep media queries, based on Christopher Schiefer's:
$jsont = <<<'EOD'
{ "url":"test"}
EOD;
$a = json_decode($jsont);
$sText = $a->text;
preg_match_all('(#media(?>[^{]|(?0))*?{)', $sText, $mediaStartsTmp, PREG_OFFSET_CAPTURE);
preg_match_all("/\}(\s|\\n|\\t)*\}/", $sText, $mediaEndsTmp, PREG_OFFSET_CAPTURE);
$mediaStarts = empty($mediaStartsTmp) ? array() : $mediaStartsTmp[0];
$mediaEnds = empty($mediaEndsTmp) ? array() : $mediaEndsTmp[0];
$sOut = "";
$needMediaClose = false;
foreach ($a->ranges as $iPos => $oR) {
if ($needMediaClose) { //you are in a media query
//add closing bracket if you were in a media query and are past it
if ($oR->start > $mediaEnds[0][1]) {
$sOut .= "}\n";
array_splice($mediaEnds, 0, 1);
$needMediaClose = false;
}
}
if (!$needMediaClose) {
//remove any skipped media queries
while (!empty($mediaEnds) && $oR->start > $mediaEnds[0][1]) {
array_splice($mediaStarts, 0, 1);
array_splice($mediaEnds, 0, 1);
}
}
if (!empty($mediaStarts) && $oR->start > $mediaStarts[0][1]) {
$sOut .= "\n" . $mediaStarts[0][0] . "\n";
array_splice($mediaStarts, 0, 1);
$needMediaClose = true;
}
$sOut .= mb_substr($sText, $oR->start, ($oR->end-$oR->start))." \n";
}
if ($needMediaClose) { $sOut .= '}'; }
echo '<style rel="stylesheet" type="text/css">' . $sOut . '</style>';
That's my python code to extract the code:
import json
code_coverage_filename = 'Coverage-20210613T173016.json'
specific_file_url = 'https://localhost:3000/b.css'
with open(code_coverage_filename) as f:
data = json.load(f)
for entry in data:
pass # print entry['url']
if entry['url'] == specific_file_url:
text = ""
for range in entry['ranges']:
range_start = range['start']
range_end = range['end']
text += entry['text'][int(range_start):int(range_end)]+"\n"
print text
However, there is a problem. Chrome debugger doesn't mark these kind of lines
#media (min-width: 768px) {
So it's a bit problematic to use this technique
More practical version based on Atoms.
Improved to work without any files.
PHP Sandbox http://sandbox.onlinephpfunctions.com/
JSON Formater to be converted to 1line https://www.freeformatter.com/json-formatter.html#ad-output
Unmify it https://unminify.com/
$jsont = <<<'EOD'
{ "url":"test"}
EOD;
$a = json_decode($jsont);
$sText = $a->text;
$sOut = "";
foreach ($a->ranges as $iPos => $oR) {
$sOut .= substr($sText, $oR->start, ($oR->end-$oR->start))." \n";
}
echo '<style rel="stylesheet" type="text/css">' . $sOut . '</style>';
I use this DisCoverage chrome extension, it parses json file from coverage tool
I'm getting the error Failed to create new object, with error code: XMLHttpRequest failed: "Unable to connect to the Parse API" when i try to connect to Parse Server API. I deployed ParsePlatform/parse-server-example on Heroku. I can access to my app with a broswser with no problems.I get the error when trying to connect to Parse on Heroku with this code :
var $result=$('#results').html('Testing configuration.....');
Parse.initialize('<MY_APP_ID>', '<MY_JAVASRIPT_KEY>');
Parse.serverURL = '<MY_HEROKU_APP_NAME>.herokuapp.com/'
var ParseServerTest = Parse.Object.extend('ParseServerTest');
var _ParseServerTest = new ParseServerTest();
_ParseServerTest.set('key', 'value');
_ParseServerTest.save(null, {
success: function(_ParseServerTest) {
var txt = 'Yay, your server works! New object created with objectId: ' + _ParseServerTest.id;
$result.html('<div class="alert alert-success" role="alert">' + txt + '</div>');
},
error: function(_ParseServerTest, error) {
var txt = 'Bummer, Failed to create new object, with error code: ' + error.message;
$result.html('<div class="alert alert-danger" role="alert">' + txt + '</div>');
}
});
index.js
// Example express application adding the parse-server module to expose Parse
// compatible API routes.
var express = require('express');
var cors = require('cors');
var ParseServer = require('parse-server').ParseServer;
var path = require('path');
var databaseUri = process.env.DATABASE_URI || process.env.MONGODB_URI;
if (!databaseUri) {
console.log('DATABASE_URI not specified, falling back to localhost.');
}
var api = new ParseServer({
databaseURI: databaseUri || 'mongodb://localhost:27017/dev',
cloud: process.env.CLOUD_CODE_MAIN || __dirname + '/cloud/main.js',
appId: process.env.APP_ID || 'myAppId',
masterKey: process.env.MASTER_KEY || '', //Add your master key here. Keep it secret!
serverURL: process.env.SERVER_URL || 'https://localhost:1337/parse', // Don't forget to change to https if needed
liveQuery: {
classNames: ["Posts", "Comments"] // List of classes to support for query subscriptions
}
});
// Client-keys like the javascript key or the .NET key are not necessary with parse-server
// If you wish you require them, you can set them as options in the initialization above:
// javascriptKey, restAPIKey, dotNetKey, clientKey
var app = express();
app.use(cors());
// Serve static assets from the /public folder
app.use('/public', express.static(path.join(__dirname, '/public')));
// Serve the Parse API on the /parse URL prefix
var mountPath = process.env.PARSE_MOUNT || '/parse';
app.use(mountPath, api);
// Parse Server plays nicely with the rest of your web routes
app.get('/', function(req, res) {
res.status(200).send('I dream of being a website. Please star the parse-server repo on GitHub!');
});
// There will be a test page available on the /test path of your server url
// Remove this before launching your app
app.get('/test', function(req, res) {
res.sendFile(path.join(__dirname, '/public/test.html'));
});
var port = process.env.PORT || 1337;
var httpServer = require('http').createServer(app);
httpServer.listen(port, function() {
console.log('parse-server-example running on port ' + port + '.');
});
// This will enable the Live Query real-time server
ParseServer.createLiveQueryServer(httpServer);
Heroku config :
I followed this post : How can I host my own Parse Server on Heroku using MongoDB? except i didn't use the "Deploy to Eroku" button, i deployed it manually.
Thank you for your help.
Finally I found a way.
I first created another user in my mongo db and change it in Heroku. Try to connect with the same js code code jsfiddle but didn't work...
Then I tried with an android client, this link helped me a lot http://www.robpercival.co.uk/parse-server-on-heroku/
StarterApplication.java
public class StarterApplication extends Application {
#Override
public void onCreate() {
super.onCreate();
// Enable Local Datastore.
Parse.enableLocalDatastore(this);
// Add your initialization code here
Parse.initialize(new Parse.Configuration.Builder(getApplicationContext())
.applicationId("BUTYcVjD7nFz4Le")
.clientKey("XgQaeDY8Bfvw2r8vKCW")
.server("https://xxxxx-xxxx-xxxxx.herokuapp.com/parse")
.build()
);
ParseUser.enableAutomaticUser();
ParseACL defaultACL = new ParseACL();
// Optionally enable public read access.
// defaultACL.setPublicReadAccess(true);
ParseACL.setDefaultACL(defaultACL, true);
}
MainActivity.java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
ParseAnalytics.trackAppOpenedInBackground(getIntent());
ParseObject test = new ParseObject("Test");
test.put("username","pedro");
test.put("age",33);
test.saveInBackground(new SaveCallback() {
public void done(ParseException e) {
if (e == null) {
Log.i("Parse", "Save Succeeded");
} else {
Log.e("Parse", "Save Failed");
}
}
});
}
I really don't know what was the problem with my first user, can't connect with it. I never could connect with the js code... but anyway my goal was to connect with Android client so...
I'm trying to write a phantomjs script to log in to my facebook account and take a screenshot.
Here's my code:
var page = require('webpage').create();
var system = require('system');
var stepIndex = 0;
var loadInProgress = false;
email = system.args[1];
password = system.args[2];
page.onLoadStarted = function() {
loadInProgress = true;
console.log("load started");
};
page.onLoadFinished = function() {
loadInProgress = false;
console.log("load finished");
};
var steps = [
function() {
page.open("http://www.facebook.com/login.php", function(status) {
page.evaluate(function(email, password) {
document.querySelector("input[name='email']").value = email;
document.querySelector("input[name='pass']").value = password;
document.querySelector("#login_form").submit();
console.log("Login submitted!");
}, email, password);
page.render('output.png');
});
},
function() {
console.log(document.documentElement.innerHTML);
},
function() {
phantom.exit();
}
]
setInterval(function() {
if (!loadInProgress && typeof steps[stepIndex] == "function") {
console.log("step " + (stepIndex + 1));
steps[stepIndex]();
stepIndex++;
}
if (typeof steps[stepIndex] != "function") {
console.log("test complete!");
phantom.exit();
}
}, 10000);
(Inspired by this answer, but note that I've upped the interval to 10s)
Called like so:
./phantomjs test.js <email> <password>
With output (filtering out the selfxss warnings from Facebook):
step 1
load started
load finished
Login submitted!
load started
load finished
step 2
<head></head><body></body>
step 3
test
complete!
(Note that the html output in step two is empty)
This answer suggests that there are problems with phantomjs' SSL options, but running with --ssl-protocol=any has no effect.
This appears to be a similar problem, but for caspar, not phantomjs (and on Windows, not Mac) - I've tried using --ignore-ssl-errors=yes, but that also had no effect.
I guessed that this might be a redirection problem (and, indeed, when I replicate this on Chrome, the response from clicking "Submit" was a 302 Found with location https://www.facebook.com/checkpoint/?next), but according to this documentation I can set a page.onNavigationRequested handler - when I do so in my script, it doesn't get called.
I think this issue is related, but it looks as if there's no fix there.