Tuesday, May 3, 2022

Recent Questions - Stack Overflow

Recent Questions - Stack Overflow

Recent Questions - Stack Overflow


Unittesting Login in Mocha, Chai

Posted: 03 May 2022 11:02 AM PDT

I am making a unit test, utilizing Mocha and Chai framework. I am trying to test if the method of the response is POST. When I console.log(res) I get the following object

{...}      socketPath: undefined,      method: 'POST',      maxHeaderSize: undefined,      insecureHTTPParser: undefined,      path: '/api/users/login',      _ended: true,      res: <ref *1> IncomingMessage {  {...}    

My code so far, that doesn't work is

const assert = require("chai").assert;  const chai = require("chai");  const chaiHttp = require("chai-http");  let app = require("../app");  var should = chai.should();    chai.use(chaiHttp);    describe("Login", () => {    it("Testing if response method is POST", (done) => {      let body = { email: "test@test.dk", password: "1234" };      chai        .request(app)        .post("/api/users/login")        .send(body)        .then((res) => {          console.log(res);          res.should.have.property('method').eql('POST')          done();        })        .catch(done);    });  });  

The error I am receiving is AssertionError: expected { Object (_events, _eventsCount, ...) } to have own property 'method'

I think this has something to do with object destructuring, does anyone know what I am doing wrong? Thank you!

In Racket's FFI, how do you register a callback that takes a list?

Posted: 03 May 2022 11:02 AM PDT

I need to define a function in Racket's FFI that takes a callback:

(define-ffi-definer define-lib (ffi-lib "libLib"))  (define callback    (_fun [len : _int]          [elems : (_list i _int)]))  (define-lib registerCallback    (_fun callback -> _void)    #:c-id registerCallback)  

I want to be able to define elems in terms of len, that is, so I can write:

(registerCallback (lambda (xs) stuff))  

How is this accomplished?

Furthermore, my code as written gives the error:

length: contract violation    expected: list?    given: #<cpointer>  

I presume this is because elems can't be listified. What do I do?

when i try to run solidity-coverage with truffle run coverage then i got this error

Posted: 03 May 2022 11:02 AM PDT

Using Truffle library from local node_modules.

solidity-coverage cleaning up, shutting down ganache server UnhandledRejections detected Promise { TypeError: Cannot read private member from an object whose class did not declare it at __classPrivateFieldGet (C:\Users\RahulMuwal\Downloads\smartcontract (2)\smartcontract\node_modules\ganache\dist\node\webpack:\Ganache\core\lib\src\server.js:10:94)

Getting ValueError when trying to obtain confusion matrix of trained CNN model

Posted: 03 May 2022 11:01 AM PDT

I had a classification problem in which I trained a CNN and now I was hoping I could obtain its confusion matrix. I tried the following:

from sklearn.metrics import confusion_matrix    y_pred = model.predict(x_test)  #Generate the confusion matrix  cf_matrix = confusion_matrix(y_test, y_pred)    print(cf_matrix)  

But I got the following error:

ValueError: Classification metrics can't handle a mix of unknown and continuous-multioutput targets  

x_test is made of (84, 32, 32) - 84 monochrome images of shape 32x32

Is there a way around this problem?

Other ways to use Spring Beans or other concepts that can be used in a Spring Condition?

Posted: 03 May 2022 11:01 AM PDT

I have a multi-module project that currently uses a Spring managed bean in a Condition.

As an example, I have following code:

// in module-core  public interface CustomBean {}    // in module-aws  @Component  @Profile("aws")  public class AwsCustomBean implements CustomBean {}    // in module-gcp  @Component  @Profile("gcp")  public class GcpCustomBean implements CustomBean {}  //...  
/**   *  Note that this class is located in the module    *  that does not reference to `AwsCustomBean` or `GcpCustomBean`.   */  public class CustomCondition implements Condition {      @Override      public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {          CustomBean customBean = context.getBeanFactory().getBean(CustomBean.class);          return customBean.isTrue();      }  }  
@Configuration  @Conditional(CustomCondition.class)  public class CustomConfiguration {}  

However, I understand that Beans shouldn't be used within Condition according to the documentation: Conditions must follow the same restrictions as BeanFactoryPostProcessor and take care to never interact with bean instances. For more fine-grained control of conditions that interact with @Configuration beans consider implementing the ConfigurationCondition interface.

However, I couldn't really find any other ways that I can get different implementations on the CustomCondition without using dependency injection.

My question is is there any other ways that I can achieve this without using Beans? Is there any other concept that is provided by Spring?

How to filter a barchart by a "thrid" value using d3.js

Posted: 03 May 2022 11:01 AM PDT

I was able to plot a very simple barchart using D3.js version 7 that relates names with points from a dataset. In this same dataset there's a third value that I would like to use to filter the barchart.

I can filter it by name or points already simply using:

.filter((d) => d.name = "OneA")  .filter((d) => d.points > 100000)  

But if I try to filter the barchart data by status it doesn't work. Nothing is filtered.

This is the entire code:

// set margins, width and height  const MARGIN = { LEFT: 64, RIGHT: 2, TOP: 32, BOTTOM: 16 }  const WIDTH = 600 - MARGIN.LEFT - MARGIN.RIGHT  const HEIGHT = 400 - MARGIN.TOP - MARGIN.BOTTOM    // set svg  const svg = d3.select("#chart-area").append("svg")    .attr("width", WIDTH + MARGIN.LEFT + MARGIN.RIGHT)    .attr("height", HEIGHT + MARGIN.TOP + MARGIN.BOTTOM)    // set group  const g = svg.append("g")    .attr("transform", `translate(${MARGIN.LEFT}, ${MARGIN.TOP})`)    // import data  d3.json("data/data.json").then(data => {    // prepare data    data      .forEach(d => {        d.points = Number(d.points)      })      // set scale, domain and range for x axis    const x = d3.scaleBand()      .domain(data.map(d => d.name))      .range([0, WIDTH])      .padding(0.1)        // set scale, domain and range for y axis    const y = d3.scaleLinear()      .domain([0, d3.max(data, d => d.points)])      .range([HEIGHT, 0])      // call x axis    const xAxisCall = d3.axisBottom(x)    g.append("g")      .attr("class", "x axis")      .attr("transform", `translate(0, ${HEIGHT})`)      .call(xAxisCall)      // call y axis    const yAxisCall = d3.axisLeft(y)    g.append("g")      .attr("class", "y axis")      .call(yAxisCall)      // join data    const rects = g.selectAll("rect")      .data(data)      // enter elements to plot chart    rects.enter().append("rect")      .filter((d) => d.status = "ON") // THIS IS NOT WORKING. WHY?      .attr("x", (d) => x(d.name))      .attr("y", d => y(d.points))      .attr("width", x.bandwidth)      .attr("height", d => HEIGHT - y(d.points))      .attr("fill", "steelblue")  })  

And json file with the data is:

[      {          "name": "OneA",          "points": "492799",          "status": "ON"      },      {          "name": "TwoB",          "points": "313420",          "status": "ON"      },      {          "name": "ThreeC",          "points": "133443",          "status": "ON"      },      {          "name": "FourD",          "points": "50963",          "status": "OFF"      },      {          "name": "FiveE",          "points": "26797",          "status": "OFF"      },      {          "name": "SixF",          "points": "13483",          "status": "OFF"      },      {          "name": "SevenG",          "points": "12889",          "status": "OFF"      }  ]  

How is it possible to filter the barchart by status in this case?

How do You exit from an application without exiting the menu that activated the application?

Posted: 03 May 2022 11:01 AM PDT

Bear with me... Im not sure how to ask this question. I'm working on a Web site using VB.NET and Visual Studios 2017 (soon to upgrade to VS 2019). The software is activated by a website menu item that I don't have access to; I have no idea how the menu structure calls my software. The problem the users reported is that my software has a LogOut button that not only closes the application, it also logs them out of the Menu struture. They would like to exit my software without loggig out of the Menu because restarting the browser and logging back into the menu is a pain (complicated). I can't show any code because they changed the firewall at work and it blocks this site.

I added a Button to the index screen that says "EXIT". I figured out that the other buttons activate the javascript section of the Index View. I tried to find a close, and an exit, and a shutdown, but couldn't find anything that would help.

Stuck with HtmlAgilityPack

Posted: 03 May 2022 11:01 AM PDT

I'm trying to scrap the list of music for a given date from the billboard website. When I obtain a list of div for each music I'm trying to get the title and the artist for each div, but in my foreach loop I get always the same return values, is like my foreach loop doesn't go to the next div.

using HtmlAgilityPack;  using System;  using System.Collections.Generic;      namespace Billboard_Scraping  {      internal class Program      {          static void Main(string[] args)          {              var billBoardMusic = GetMusicList("https://www.billboard.com/charts/hot-100/2000-08-12");          }            static List<Music> GetMusicList(string url)          {              var musics = new List<Music>();                            HtmlWeb web = new HtmlWeb();              HtmlDocument document = web.Load(url);              HtmlNodeCollection linknode = document.DocumentNode.SelectNodes("//div[contains(@class,\"o-chart-results-list-row-container\")]");                  foreach (var link in linknode)              {                  var music = new Music();                  var titleXPath = "//h3[contains(@class,\"c-title\")]";                  var artistXPath = "//span[contains(@class,\"c-label  a-no-trucate\")]";                    music.Title = link.SelectSingleNode(titleXPath).InnerText.Trim();                  music.Autor = link.SelectSingleNode(artistXPath).InnerText.Trim();                  musics.Add(music);              }              return musics;          }      }        public class Music      {          public string Title { get; set; }          public string Autor { get; set; }      }  }  

Destructor protected within this context c++ (issue #1)

Posted: 03 May 2022 11:00 AM PDT

I have a compilation error with C++ (v11). I have defined a base class (Node) with protected ctor and dtor. I have defined an inherited class of Node (Directory) with public inheritance. I am calling the dtor of the base class in the dtor of the inherited class. The compilation failed with the message :

"error: 'virtual Node::~Node()' is protected within this context"  

I really don't understand why as I was pretty sure that protected keywords allowed methods (and objects) in a derived class to have access to public and protected methods (and data) of the base class.

Below I have put the code, that I hope enough commented : the idea is to create a basic fs running in RAM.

Thanks by advance

Node.hpp

#ifndef NODE_HPP  #define NODE_HPP    #include "FileSystem.hpp"    class Directory;    //Forward declaration of class Directory used in this class  class File;         //Forward declaration of class File used in this class    /*Class representing a node of the fs : a node can be a file or a directory*/  class Node  {      /*friend class Directory;*/     //Related to the issue #1 : Destructor protected within this context        protected:          Node(FileSystem *, int, string, Directory * = nullptr);          virtual ~Node();          Node(const Node&);        public:          /*Getter*/          string get_name() const;            /*Abstract methods redefined in the derived class File and Directory*/          virtual bool is_directory() = 0;          virtual Directory * to_directory() = 0;          virtual File * to_file() = 0;          virtual int size() = 0;        protected:          FileSystem *fs;     //Fs where is the node          int uid;            //Unique id to identify a node          string name;        //Name of the node          Directory *parent;  //Parent directory of the node  };    

No comments:

Post a Comment