Has `scenarioResult.isFailed()` been removed in (typings) CucumberJS 1.x to 2.x - typescript-typings

I'm currently migrating a Typescript CucumberJS 1.3 project to CucumberJS 2.2. this also means an update from #types/cucumber version 1.3.1 to 2.0.1.
In my After hook is now see that I can't use isFailed() anymore, see below, or am I missing something?
// 1.3.x
this.After((scenario: HookScenario): void {
// logs scenario.isFailed() = true / false
console.log('scenario.isFailed() = ', scenario.isFailed());
}
// 2.x.x
this.After((scenarioResult:HookScenarioResult): void => {
// logs scenario.status = '{string} status'
console.log('scenarioResult.status = ', scenarioResult.status);
});

As you can see in your release notes,
// 1.3.x
this.After(function (scenario: HookScenario): void {
// logs scenario.isFailed() = true / false
console.log('scenario.isFailed() = ', scenario.isFailed());
}
// 2.x.x
this.After(function (scenarioResult: HookScenarioResult): void {
// logs scenario.status = '{string} status'
console.log('scenarioResult.status = ', scenarioResult.status);
// Changed to
console.log('scenario failed = ', scenarioResult.status === 'failed');
});

Related

Turning on logging of the Mapnik SQL query during map rendering

I am using the npm package Mapnik with PostGIS and I want to enable logging to the console of the SQL query that Mapnik is executing, including the value of the bbox parameter, when running the render() function.
import * as mapnik from "mapnik";
async function main() {
mapnik.register_default_input_plugins();
mapnik.settings.log.level = "debug"; // something like that???
...
const vectorTile = new VectorTile(parseInt(z), parseInt(x), parseInt(y));
const map = new Map(256, 256);
new RouteLayer(vectorTile).apply(map);
map.zoomAll();
map.render(vectorTile, (err, vectorTile) => { // how to log executed sql query?
if (err) {
return rej(err);
}
return res(vectorTile.getData());
});
}
main();
...
// RouteLayer
private apply(map: mapnik.Map): void {
const config = this.createPostgisConfig(`
select
id,
geometry
from nordic_sector
where
deleted_at is null
and st_intersects(st_transform(geometry, 3857),!bbox!)
`);
const layer = new (mapnik as any).Layer(
"nordic-sector-back",
PROJECTION_3857
);
layer.datasource = new mapnik.Datasource(config);
(map as any).add_layer(layer);
}
EDIT1:
Unsuccessful attempts:
(mapnik as any).logger.set_severity((mapnik as any).severity_type.Debug);
(mapnik as any).Logger.setSeverity((mapnik as any).Logger.DEBUG);
In Mapnik you can configure the default logging severity level like this:
mapnik.logger.set_severity(mapnik.severity_type.Debug)

node:assert:400 throw err; ^ AssertionError [ERR_ASSERTION]: Invalid callback object specified

I'm trying to run node compile.js but it's throwing me this error and idea what I am doing wrong:
node:assert:400 throw err; ^ AssertionError [ERR_ASSERTION]: Invalid callback object specified
my inbox.sol
pragma solidity ^0.8.9;
contract Inbox{
string public message;
function Inbox(string intialMessage) public {
message = intialMessage;
}
function setMessage(string newMessage) public {
message = newMessage;
}
}
my package.json
{
"dependencies": {
"ganache-cli": "^6.12.2",
"mocha": "^9.1.3",
"solc": "^0.8.9",
"web3": "^1.6.0"
}
}
Just rewrite your code like this in 'compile.js'.This work fine even in 0.8.0 version of solidity
const path = require('path');
const fs = require('fs');
const solc = require('solc');
const inboxpath = path.resolve(__dirname, 'Contracts', 'Inbox.sol');
const source = fs.readFileSync(inboxpath, 'UTF-8');
var input = {
language: 'Solidity',
sources: {
'Inbox.sol' : {
content: source
}
},
settings: {
outputSelection: {
'*': {
'*': [ '*' ]
}
}
}
};
var output = JSON.parse(solc.compile(JSON.stringify(input)));
// console.log(output.contracts['Inbox.sol']['Inbox']);
// exports.abi = output.contracts['Inbox.sol']['Inbox'].abi;
// exports.bytecode = output.contracts['Inbox.sol']['Inbox'].evm.bytecode.object;
That course is outdated, solidity version 0.6.6 is released and you better update your code to that version. if you are not a good programmer you better refund that course, cause you will encounter many problems later on, you will see some errors using meta mask and Web3. that course teachs you a lot, so i really recommend you to keep learning that course and update yourself throughout the course. this is the first problem and the solution to the updated version is this.
this will be your "inbox.sol" code:
pragma solidity ^0.6.6;
contract Inbox{
string public message;
constructor (string memory initialMessage) public{
message = initialMessage;
}
function setMessage(string memory newMessage) public{
message = newMessage;
}
}
and this will be your "compile.js" code:
const path = require('path');
const fs = require('fs');
const solc = require('solc');
const inboxpath = path.resolve(__dirname, 'Contracts', 'Inbox.sol');
const source = fs.readFileSync(inboxpath, 'UTF-8');
var input = {
language: 'Solidity',
sources: {
'Inbox.sol' : {
content: source
}
},
settings: {
outputSelection: {
'*': {
'*': [ '*' ]
}
}
}
};
var output = JSON.parse(solc.compile(JSON.stringify(input)));
exports.abi = output.contracts['Inbox.sol']['Inbox'].abi;
exports.bytecode = output.contracts['Inbox.sol'] ['Inbox'].evm.bytecode.object;
in the new solidity the compiler will give you another version of compiled code compared to old compiler, so you'll need to pass the json file to your compiler and in order to access to abi(interface) and bytecode you need to do like i did in here.
It will work with solc version 0.4.17.
Just add memory after both string which are present in function's parameters.
function Inbox(string memory initialMessage)...
AND
function setMessage(string memory newMessage)...
For the people who are here for the v0.4.17
Simply update your package.json file solc version to 0.4.17
var output = solc.compile(source,1);
console.log(output)
I guess all you have to do is rollback your complier version. You will get your output. That worked for me.

Determine dependency's greatest matching version that exists on an NPM server from a semver version

I'm writing a node script which helps pin dependencies.
How can I determine the greatest realized version of a package existing on an NPM server, from a semver version?
For example, we have a dependency "foo" which is specified in a package.json as ~1.2.3.
Out on NPM, there exists published version 1.2.5, which is the latest published version compatible with ~1.2.3.
I need to write a script that would take as input "foo" and ~1.2.3, then after a server query, return 1.2.5. Something like this:
await fetchRealizedVersion('foo', '~1.2.3'); // resolves to 1.2.5
I understand I could do something like yarn upgrade and then parse the lock file, but I am looking for a more direct way of accomplishing this.
Hopefully there is a package that boils this down to an API call, but I'm not finding anything after googling around.
"Hopefully there is a package that boils this down to an API call,"
Short Answer: Unfortunately no, there is not a package that currently exists as far as I know.
Edit: There is the get-latest-version package you may want to try:
Basic usage:
const getLatestVersion = require('get-latest-version')
getLatestVersion('some-other-module', {range: '^1.0.0'})
.then((version) => console.log(version)) // highest version matching ^1.0.0 range
.catch((err) => console.error(err))
Alternatively, consider utilizing/writing a custom node.js module to perform the following steps:
Either:
Shell out the npm view command to retrieve all versions that are available in the NPM registry for a given package: For instance:
npm view <pkg> versions --json
Or, directly make a https request to the public npm registry at https://registry.npmjs.org to retrieve all versions available in for a given package.
Parse the JSON returned and pass it, along with the semver range (e.g. ~1.2.3), to the node-semver package's maxSatisfying() method.
The maxSatisfying() method is described in the docs as:
maxSatisfying(versions, range): Return the highest version in the list that satisfies the range, or null if none of them do.
Custom module (A):
The custom example module provided in get-latest-version.js (below) essentially performs the aforementioned steps. In this example we shell out the npm view command.
get-latest-version.js
'use strict';
//------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------
const { exec } = require('child_process');
const { maxSatisfying } = require('semver');
//------------------------------------------------------------------------------
// Data
//------------------------------------------------------------------------------
const errorBadge = '\x1b[31;40mERR!\x1b[0m';
//------------------------------------------------------------------------------
// Helpers
//------------------------------------------------------------------------------
/**
* Captures the data written to stdout from a given shell command.
*
* #param {String} command The shell command to execute.
* #return {Promise<string>} A Promise object whose fulfillment value holds the
* data written to stdout. When rejected an error message is returned.
* #private
*/
function shellExec(command) {
return new Promise((resolve, reject) => {
exec(command, (error, stdout, stderr) => {
if (error) {
reject(new Error(`Failed executing command: '${command}'`));
return;
}
resolve(stdout.trim());
});
});
}
//------------------------------------------------------------------------------
// Public Interface
//------------------------------------------------------------------------------
module.exports = {
/**
* Retrieves the latest version that matches the given range for a package.
*
* #async
* #param {String} pkg The package name.
* #param {String} range The semver range.
* #returns {Promise<string>} A Promise object that when fulfilled returns the
* latest version that matches. When rejected an error message is returned.
*/
async fetchRealizedVersion(pkg, range) {
try {
const response = await shellExec(`npm view ${pkg} versions --json`);
const versions = JSON.parse(response);
return maxSatisfying(versions, range);
} catch ({ message: errorMssg }) {
throw Error([
`${errorBadge} ${errorMssg}`,
`${errorBadge} '${pkg}' is probably not in the npm registry.`
].join('\n'));
}
}
};
Usage:
The following index.js demonstrates using the aforementioned module.
index.js
'use strict';
const { fetchRealizedVersion } = require('./get-latest-version.js');
(async function() {
try {
const latest = await fetchRealizedVersion('eslint', '~5.15.0');
console.log(latest); // --> 5.15.3
} catch ({ message: errMssg }) {
console.error(errMssg);
}
})();
As you can see, in that example we obtain the latest published version for the eslint package that is compatible with the semver tilde range ~5.15.0.
The latest/maximum version that satisfies ~5.15.0 is printed to the console:
$ node ./index.js
5.15.3
Note: You can always double check the results using the online semver calculator which actually utilizes the node-semver package.
Another Usage Example:
The following index.js demonstrates using the aforementioned module to obtain the latest/maximum version for multiple packages and different ranges.
index.js
'use strict';
const { fetchRealizedVersion } = require('./get-latest-version.js');
const criteria = [
{
pkg: 'eslint',
range: '^4.9.0'
},
{
pkg: 'eslint',
range: '~5.0.0'
},
{
pkg: 'lighthouse',
range: '~1.0.0'
},
{
pkg: 'lighthouse',
range: '^1.0.4'
},
{
pkg: 'yarn',
range: '~1.3.0'
},
{
pkg: 'yarn',
range: '^1.3.0'
},
{
pkg: 'yarn',
range: '^20.3.0'
},
{
pkg: 'quuxbarfoo',
range: '~1.3.0'
}
];
(async function () {
// Each request is sent and read in parallel.
const promises = criteria.map(async ({ pkg, range }) => {
try {
return await fetchRealizedVersion(pkg, range);
} catch ({ message: errMssg }) {
return errMssg;
}
});
// Log each 'latest' semver in sequence.
for (const latest of promises) {
console.log(await latest);
}
})();
The result for that last example is as follows:
$ node ./index.js
4.19.1
5.0.1
1.0.6
1.6.5
1.3.2
1.22.4
null
ERR! Failed executing command: 'npm view quuxbarfoo versions --json'
ERR! 'quuxbarfoo' is probably not in the npm registry.
Additional Note: The shellExec helper function in get-latest-version.js currently promisifies the child_process module's exec() method to shell out the npm view command. However, since node.js version 12 the built-in util.promisify provides another way to promisify the exec() method (as shown in the docs for exec), so you may prefer to do it that way instead.
Custom module (B):
If you wanted to avoid shelling out the npm view command you could consider making a request directly to the https://registry.npmjs.org endpoint instead (which is the same endpoint that the npm view command sends a https GET request to).
The modified version of get-latest-version.js (below) essentially utilizes a promisified version of the builtin https.get.
Usage is the same as demonstrated previously in the "Usage" section.
get-latest-version.js
'use strict';
//------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------
const https = require('https');
const { maxSatisfying } = require('semver');
//------------------------------------------------------------------------------
// Data
//------------------------------------------------------------------------------
const endPoint = 'https://registry.npmjs.org';
const errorBadge = '\x1b[31;40mERR!\x1b[0m';
//------------------------------------------------------------------------------
// Helpers
//------------------------------------------------------------------------------
/**
* Requests JSON for a given package from the npm registry.
*
* #param {String} pkg The package name.
* #return {Promise<json>} A Promise object that when fulfilled returns the JSON
* metadata for the specific package. When rejected an error message is returned.
* #private
*/
function fetchPackageInfo(pkg) {
return new Promise((resolve, reject) => {
https.get(`${endPoint}/${pkg}/`, response => {
const { statusCode, headers: { 'content-type': contentType } } = response;
if (statusCode !== 200) {
reject(new Error(`Request to ${endPoint} failed. ${statusCode}`));
return;
}
if (!/^application\/json/.test(contentType)) {
reject(new Error(`Expected application/json but received ${contentType}`));
return;
}
let data = '';
response.on('data', chunk => {
data += chunk;
});
response.on('end', () => {
resolve(data);
});
}).on('error', error => {
reject(new Error(`Cannot find ${endPoint}`));
});
});
}
//------------------------------------------------------------------------------
// Public Interface
//------------------------------------------------------------------------------
module.exports = {
/**
* Retrieves the latest version that matches the given range for a package.
*
* #async
* #param {String} pkg The package name.
* #param {String} range The semver range.
* #returns {Promise<string>} A Promise object that when fulfilled returns the
* latest version that matches. When rejected an error message is returned.
*/
async fetchRealizedVersion(pkg, range) {
try {
const response = await fetchPackageInfo(pkg);
const { versions: allVersionInfo } = JSON.parse(response);
// The response includes all metadata for all versions of a package.
// Let's create an Array holding just the `version` info.
const versions = [];
Object.keys(allVersionInfo).forEach(key => {
versions.push(allVersionInfo[key].version)
});
return maxSatisfying(versions, range);
} catch ({ message: errorMssg }) {
throw Error([
`${errorBadge} ${errorMssg}`,
`${errorBadge} '${pkg}' is probably not in the npm registry.`
].join('\n'));
}
}
};
Note The version of node-semver used in the example custom modules (A & B) IS NOT the current latest version (i.e. 7.3.2). Version ^5.7.1 was used instead - which is the same version used by the npm cli tool.

MVC5 and IIS 7.5 Configuration

I have virtual server where is configured IIS 7.5 to works with ASP.NET MVC.
When I deploy application everything works fine. Only one thing is not working when I run application, maybe I'm wrong but I thought that code is correct.
<script>
$(document).ready(function () {
$("#Subcode").prop("disabled", true);
$("#MasterId").change(function () {
if ($("#MasterId").val() != "Select Master Code") {
var CountryOptions = {};
CountryOptions.url = "/Audit/FindSubCode";
CountryOptions.type = "POST";
CountryOptions.data = JSON.stringify({ master_id: $("#MasterId").val() });
CountryOptions.datatype = "json";
CountryOptions.contentType = "application/json";
CountryOptions.success = function (SubCodeList) {
$("#Subcode").empty();
for (var i = 0; i < SubCodeList.length; i++) {
$("#Subcode").append("<option>" + SubCodeList[i] + "</option>");
}
$("#Subcode").prop("disabled", false);
};
CountryOptions.error = function () { alert("Error in Getting SubCodes!!"); };
$.ajax(CountryOptions);
}
else {
$("#Subcode").empty();
$("#Subcode").prop("disabled", true);
}
});
});
</script>
#Html.DropDownList("MasterId",ViewBag.MasterId as SelectList,"Select Master Code",new { #class = "form-control"})
<select id="Subcode"></select>
And code from controller
public JsonResult FindSubCode(int master_id)
{
List<string> SubCodeList = new List<string>();
switch(master_id)
{
case 1:
SubCodeList.Add("Test");
break;
case 2:
SubCodeList.Add("Test2");
break;
}
return Json(SubCodeList);
}
Why I'm writing this problem as IIS Configuration, because if I run locally this application, everything works fine. But when I run on server I got error from code "Error in Getting SubCodes!!".
I tried to debug and get next error: Error when devug
Any suggestion how I can fix this ?
I don't think it has to do with configuration. Verify your URL.
/Audit/FindSubCode would be pointing to the root of the server which may be a different path to where the application is being served from.
Try not to hard code the path but rather use razor engin UrlHelper to generate the path.
CountryOptions.url = "#(Url.Action("FindSubCode","Audit")";

How can I get msysgit on windows to invoke node.js scripts in hooks?

I would like to use node.js scripts as my git hook scripts. Currently I'm experimenting on my Windows machine with Bonobo Git HTTP service which is attached to msysgit Git-1.9.0-preview20140217 portable installation. It works fine, tested with copuple pulls and pushes.
I have nodejs up and running but my git update script just fails without any clear reason. It definitely works - it started to always reject pushes as soon as I added it into the hooks folder on the server but there are no any clues in SourceTree output log.
Here is my update script:
#!C:/nodejs/node.exe
console.log('Hello world!');
console.log('Hello world 2!');
I tried back slashes, I tried double forward slashes, I tried quoting the path - no results.
Server response is as follows:
git -c diff.mnemonicprefix=false -c core.quotepath=false push -v --tags origin master:master
Pushing to http://myurl.git
POST git-receive-pack (4686 bytes)
remote: error: hook declined to update refs/heads/master[K
To http://myurl.git
! [remote rejected] master -> master (hook declined)
error: failed to push some refs to 'http://myurl.git'
Completed with errors, see above.
P.S. I don't know where [K comes from, my gusess is that it's corrupted newline character.
I ended up using similar approach to the one I found someone was using for Python.
I created a C# console app as follows:
using System;
using System.Diagnostics;
using System.IO;
namespace GitNodeRunner
{
class Program
{
static int Main(string[] args)
{
if (args == null || args.Length == 0)
{
Console.Error.WriteLine("Path to script file not specified");
return -1;
}
string argString = string.Join(" ", args);
Console.WriteLine("Node.js arguments received: {0}", argString);
string nodePath = Environment.GetEnvironmentVariable("NODE_HOME",
EnvironmentVariableTarget.Machine); // without "Machine" Git's Bash loses it
if (string.IsNullOrWhiteSpace(nodePath))
{
Console.Error.WriteLine("NODE_HOME global envirnoment variable not found");
return -1;
}
nodePath = Path.Combine(nodePath, "node.exe");
ProcessStartInfo start = new ProcessStartInfo
{
UseShellExecute = false,
Arguments = argString,
FileName = nodePath,
RedirectStandardInput = true,
RedirectStandardOutput = true,
RedirectStandardError = true,
CreateNoWindow = true
};
Process process = new Process();
process.StartInfo = start;
process.EnableRaisingEvents = true;
process.OutputDataReceived += process_OutputDataReceived;
process.ErrorDataReceived += process_OutputDataReceived;
process.Start();
process.BeginErrorReadLine();
process.BeginOutputReadLine();
process.WaitForExit();
return process.ExitCode;
}
static void process_OutputDataReceived(object sender, DataReceivedEventArgs e)
{
string s = e.Data;
Console.Out.WriteLine(s);
}
static void process_ErrorDataReceived(object sender, DataReceivedEventArgs e)
{
string s = e.Data;
Console.Error.WriteLine(s);
}
}
}
I compiled it as git-nodejs.exe, put into Git's bin folder, ensured that I have NODE_HOME environment variable defined, and now I can use node.js scripts. As an example, I provide my node.js update hook which rejects pushes with malformed comment messages:
#!/bin/git-nodejs
// bin/git-nodejs is our custom C# programmed node launcher
// the following code is ported from http://git-scm.com/book/en/Customizing-Git-An-Example-Git-Enforced-Policy
// we have some offset from standard Git args here:
// 0 is path to node
// 1 is path to this script
var exec = require('child_process').exec,
refname = process.argv[2],
oldrev = process.argv[3],
newrev = process.argv[4],
regexMatch = /^REF #\d* /; // in my case I require strict start with "REF #number "
console.log("Enforcing policies in branch " + refname + " for commits between revisions " + oldrev + " and " + newrev);
// we have a special case - if this is a new branch, oldrev..newrev will cause git to throw an error,
// that's why we check for empty branch commit ID
var revListCmd = (oldrev === "0000000000000000000000000000000000000000") ?
"git rev-list " + newrev + " --not --branches=*" :
"git rev-list " + oldrev + ".." + newrev;
exec(revListCmd,
function (error, stdout, stderr) {
if (error !== null) {
console.error("Exec error: " + error);
exitError();
}
var missedRevs = stdout.split("\n");
missedRevs.forEach(function(rev){
// there is a redundant empty entry at the end after split()
if (rev.length === 0) {
return;
}
console.log("Verifying policy for revision " + rev);
// | sed '1,/^$/d' does not quite work as expected on Windows
// - it returns all commit details instead of comment
// thus we complete the processing from JavaScript
exec("git cat-file commit " + rev,
function (error, stdout, stderr) {
if (error !== null) {
console.error("Exec error: " + error);
exitError();
}
// we skip the blank line (two sequential newlines) and take everything that follows
// not sure if this is the best solution but "it works on my machine"
var commitMessage = stdout.split("\n\n")[1];
// notice: if commit message missing, git will report it as "no message"
if (commitMessage.match(regexMatch) === null) {
console.error("Commit message '" + commitMessage + "' does not match the required pattern " + regexMatch);
exitError();
}
});
});
});
//////////////////////////
// some helpers
function exitError()
{
// hack for bug https://github.com/joyent/node/issues/3584
// delay exit until stdout on Windows has had some time to flush
setTimeout(function() {
console.error("Exiting with error status 1");
process.exit(1);
}, 1000);
}

Resources