Friday, October 8, 2021

Recent Questions - Stack Overflow

Recent Questions - Stack Overflow


Dependency Injection via Abstract class/Interface to an Array in Angular

Posted: 08 Oct 2021 08:38 AM PDT

I am very, very new to Angular and TypeScript, and I mostly play around with Java and Spring Boot. In Spring, we have a useful feature where we can get the instances of all the implementations of an Interface in a List. The code for that is like below:

public interface Vehicle {      void runs();  }    @Component  public class Car implements Vehicle {      public void runs(){          // some implementation      }  }    @Component  public class Bike implements Vehicle {      public void runs(){          // some implementation      }  }    @Component  public class SomeService {        @Autowired      private List<Vehicle> vehicles;        public void otherMethod() {          for(int i = 0; i < vehicles.size(); i++) {              vehicles[i].runs();          }      }  }  

This way we can execute multiple functions without even touching existing methods. Can we achieve such type of an implementation in Angular as well.

Saving TensorFlow keras model in custom algorithm container for sagemaker estimator, fails with permission error on deploy endpoint

Posted: 08 Oct 2021 08:38 AM PDT

The custom algorithm container trains a Tensorflow keras model, and after it finishes with the training I save the model:

model.save('/opt/ml/model')

The training jobs finishes successfull, but when I try to deploy the sagemaker.Estimator made from the custom algorithm container, I get the following error:

tensorflow.python.framework.errors_impl.PermissionDeniedError: /opt/ml/model/variables/variables_temp; Read-only file system [Op:SaveV2]

it fails on the model.save line

ListItem Not Showing Anything

Posted: 08 Oct 2021 08:38 AM PDT

I tried to implement the listItem from react-native-elements but when I run the app it displays nothing

const SettingsScreen = () => {          return (              <SafeAreaView  style={styles.container}>                  <ScrollView>                      <ListItem key='user-account' bottomDivider >                          <Icon name="user" type='ant-design'  />                          <ListItem.Content>                              <ListItem.Title>User Account</ListItem.Title>                          </ListItem.Content>                      </ListItem>                  </ScrollView>              </SafeAreaView>          )      }  

enter image description here

How do I compute similarity of two images using SIFT/evaluate SIFT results?

Posted: 08 Oct 2021 08:38 AM PDT

I want to compute similarities between two images using SIFT. I have managed to compute matches and visualize it as seen in the image below. Sift between heavily rotated Eiffel tower and normal Eiffel tower. I have one image of the Eiffel tower and another image of a heavily modified Eiffel tower. To me this match looks good but I don't know what metrics, equations or algorithms to use to compute the similarity or to evaluate the match.

I am using the following code to compute the matching.

import cv2    # Read images  img1 = cv2.imread("eiffel_normal.jpeg")  img2 = cv2.imread("eiffel_rotated.jpeg")    #sift  sift = cv2.SIFT_create()    # Get keypoints and descriptors  keypoints_1, descriptors_1 = sift.detectAndCompute(img1, None)  keypoints_2, descriptors_2 = sift.detectAndCompute(img2, None)    #feature matching  bf = cv2.BFMatcher(cv2.NORM_L1, crossCheck=True)    matches = bf.match(descriptors_1,descriptors_2)  matches = sorted(matches, key=lambda x:x.distance)    # Visualize the results  img3 = cv2.drawMatches(img1, keypoints_1, img2, keypoints_2, matches[:30], img2, flags=2)  plt.imshow(img3)  plt.show()    

I've tried:

def calculateScore(matches, key_1_len, key_2_len):      return 100 * (matches/min(key_1_len, key_2_len))    similar_regions = [i for i in matches if i.distance < 50]  sift_score= calculateScore(len(matches), len(keypoints_1), len(keypoints_2))  sift_acc = len(similar_regions)/len(matches)  

but both sift_score and sift_acc gives bad results.

The evaluator must take in account: Scaling, Rotation and translation

Any ideas?

Purge_table operation

Posted: 08 Oct 2021 08:37 AM PDT

I have 60000 of records in s3 buckets and I am using purge_table for deleting files and glue catalog

delete_data = glueContext.purge_table(DatabaseName, RecentTableName, {"partitionPredicate": predicate, "retentionPeriod": 0 }) but only few records gets delete from s3 buckets(18740)

does purge_table having any limitation? please someone help in that. thanks

B2C - Custom Policy - Split SignUp and Verification breaks Password Reset

Posted: 08 Oct 2021 08:37 AM PDT

I have a custom policy that incorporates the Embedded Password Reset flow as outlined here: https://github.com/azure-ad-b2c/samples/tree/master/policies/embedded-password-reset.

Now, I need to split the signup and verification screens so I tried following the sample here: https://github.com/azure-ad-b2c/samples/tree/master/policies/split-email-verification-and-signup.

Once I have combined the two custom policies, the Signup and Signin flows work fine. However clicking on the Reset Password link gives me: "The page cannot be displayed because an internal server error has occurred."

How to insert condition in function

Posted: 08 Oct 2021 08:37 AM PDT

Could you help me insert one more condition in my function? You can see that I can generate graphics for ABC and FGH, but not for CDE. In another question, this was resolved (How to adjust problem when generating graph in R), but I'm not able to put the resolution in this function that I did now, could you help me?

library(dplyr)  library(tidyverse)  library(lubridate)  library(stringr)    dmda<-"2021-07-07"    datas <- structure(    list(Code = c("ABC","ABC","ABC","CDE","CDE","CDE","ABC","FGH","FGH"),         Days = c(11,12,13,11,12,13,11,12,13),         Numbers = c(11,17,13,12,12,12,17,12,15)),    class = "data.frame", row.names = c(NA, -9L))    m<-mean(datas$Numbers)    f1 <- function(dat, code_nm) {    dat <- subset(dat,  Code == code_nm)    plot(Numbers ~ Days,  xlim= c(0,45), ylim= c(0,30),         xaxs='i',data = dat,main = paste0(dmda, "-", code_nm))            if (nrow(dat)<=2){      abline(h=m,lwd=2)       points(0, m, col = "red", pch = 19, cex = 2, xpd = TRUE)      text(.1,m+ .5, round(m,1), cex=1.1,pos=4,offset =1,col="black")}       else  {              model <- nls(Numbers ~ b1*Days^2+b2,start = list(b1 = 0,b2 = 0),data = dat, algorithm = "port")                new.data <- data.frame(Days = with(dat, seq(min(Days),max(Days),len = 45)))        new.data <- rbind(0, new.data)        lines(new.data$Days,predict(model,newdata = new.data),lwd=2)        coef<-coef(model)[2]        points(0, coef, col="red",pch=19,cex = 2,xpd=TRUE)        text(.99,coef + 1,max(0, round(coef,1)), cex=1.1,pos=4,offset =1,col="black")}  }    f1(datas, "ABC")  

For ABC

enter image description here

For FGH

enter image description here

Dynamic / autopopulating rows in excel

Posted: 08 Oct 2021 08:37 AM PDT

I have a problem I am trying to solve.

Looking at the attached image, you see Function 1, which has 5 names underneath. Is it possible (with excel) to have the names auto-populate, based on data from a separate sheet? So reading which individuals belong to Function 1, and bring all of those names below?

I can use a vlookup, but I would need to manually drag the formula up/down to update the fields. Ideally I would like the list of names to auto-adjust based on the actual data (i.e. list of employees). So if an employee is deleted from the supporting sheet, the tab

Not sure if I was able to make clear what I am looking for? Using the table function does not seem feasible, as it needs to be run for up to 50 different business units etc (see 2nd image).

Any input would be greatly appreciated!

Thank you in advance.

Regards,

Nicolas

enter image description here

enter image description here

Tabbar backgroung image scaling|selection for different devices

Posted: 08 Oct 2021 08:37 AM PDT

I'm pretty junior in iOS dev and looking for the practical tips for theming.

Designer sent me 3 tabbar vector background images for iPhone SE, iPhone 11 Pro, iPad 12.9".

There are: round right corner and shadow above the tabbar.

I'm stuck with no one to ask, what is the best way to have it done for mentioned devices and I guess for another devices also.

Background images:

Tabbar bg image for iPhone 11 Pro Tabbar bg image for iPhone SE Tabbar bg image for iPad 12.9"

I would also be grateful for the recommendation of videos or tutorials, which disassemble such cases for my deep understanding.

Thanks guys, you are always here to help!!!

Spring Boot async task stuck on completion

Posted: 08 Oct 2021 08:37 AM PDT

As per spring documentation for setWaitForTasksToCompleteOnShutdown

Set whether to wait for scheduled tasks to complete on shutdown

Does it mean that if any task is stuck on some long running process and we explicity try to stop the container, it will not be terminated untill that task is finished?

  @Bean    public TaskExecutor myAsyncTaskExecutor() {      ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();      executor.setCorePoolSize(20);      executor.setMaxPoolSize(30);      executor.setQueueCapacity(50);      executor.setWaitForTasksToCompleteOnShutdown(true); // How it behaves?      //executor.afterPropertiesSet();      executor.setThreadNamePrefix("MY-ASYNC-TASK");      executor.initialize();      return executor;    }  

Thanks for the answers.

Applying a Function to a List and a Dataframe

Posted: 08 Oct 2021 08:37 AM PDT

I have a single pair of longitude and latitude coordinates that will be inputted into a function to find the distance between it and a second pair of coordinates

For example:

lat_string1 = 48.167  long_string1 = -99.648  lat_string2 = 48.25606  long_string2 = -103.31802   

Using Haversine Distance function I can find the distance between these two coordinates.

def dist(lat1, long1, lat2, long2):        # convert decimal degrees to radians       lat1, long1, lat2, long2 = map(radians, [lat1, long1, lat2, long2])      # haversine formula       dlon = long2 - long1       dlat = lat2 - lat1       a = sin(dlat/2)**2 + cos(lat1) * cos(lat2) * sin(dlon/2)**2      c = 2 * asin(sqrt(a))       # Radius of earth in kilometers is 6371      km = 6371* c      return km    print(dist(lat_string1, long_string1, lat_string2, long_string2))  272.09670525744474  

How do I apply this function to lat_string1 and long_string1 and to coordinates_df containing 1,000's (or three in the example df below) of coordinate pairs so it may print every distance?

lat_string1 = 48.167  long_string1 = -99.648      coordinates_df = pd.DataFrame({'Name':['A', 'B', 'C'], 'Longitude':[-102.65324700, -102.75365900, -102.90515700], 'Latitude':[48.47342600, 48.31341700, 48.11112400]})  

React component not rendering also not showing up

Posted: 08 Oct 2021 08:38 AM PDT

As you can see below the my react component is not rendering also in vscode its greyed out (line 2 first picture). Dont know what I am doing wrong

import React, { Fragment, useEffect } from 'react';  import counterComponent from './components/counterComponent';    function App() {    return (      <Fragment >        <h1>hello</h1>        <counterComponent/>      </Fragment>    )  };    export default App;  

app.js

enter image description here

How to validate form array with dynamic values using form builder

Posted: 08 Oct 2021 08:37 AM PDT

Am working on angular project where I need to submit a form with some values where the exams

form fields are dynamically created when I click the add button each row() will be added in the form.

for adding each exam values. I could delete each row as well in the form.

The requirement is I need to display a validation message for subject, mark and exams for each dynamic row created on click submit button if it is invalid/not selected. The exams field is a multiple checkbox list validate if nothing is selected

<form [formGroup] = "SettingsForm" (ngSubmit) = "SettingsFormSubmit()">      <div class="row">        <div class="col-xl-4">          <input type="text" placeholder="Name" formControlName="Name">        </div>      <div class="row">        <div class="col-xl-4 ">          <p *ngIf="submitted && SettingsForm.get('Name').invalid class="text-danger">            Name is required.          </p>        </div>      </div>      <div class="row">        <div class="col-xl-12">          <table class="table" formArrayName="PersonalData">            <thead>              <tr>                <th>Subject</th>                <th>Mark</th>                <th>Exams</th>                <th>Delete</th>                <th><button type="button"  (click)="addPersonalData()" class="btn-blank">Add</button></th>              </tr>            </thead>            <tbody>              <tr [hidden]="!data.value.active"   *ngFor="let data of PersonalData().controls;let i=index" [formGroupName]="i">                <td>                  <select class="form-control" formControlName="subject"  >                    <option>Select Subject</option>                    <ng-container *ngFor="let subject of subjects">                    <option  value="{{ subject.id }}" >{{ subject.subject_name }}</option>                    </ng-container>                  </select>                  <ng-container *ngIf="data.get(subject).invalid">                    <span class="">error message</span>                  </ng-container>                </td>                <td>                  <select class="form-control" formControlName="mark">                       <option>Select Mark</option>                    <option>50</option>                    <option>60</option>                    <option>90</option>                  </select>                  <ng-container *ngIf="data.get(mark).invalid">                    <span class="">error message</span>                  </ng-container>                </td>                <td>                  <mat-form-field>                    <mat-label>Select Exams</mat-label>                    <mat-select  #examsSelect multiple formControlName="exams" >                      <mat-option (click)="examsSelect()" *ngFor="let term of terms" [value]="term_id">                        {{term.name}}                      </mat-option>                    </mat-select>                  </mat-form-field>                    <ng-container *ngIf="data.get(exams).invalid">                    <span class="">error message</span>                  </ng-container>                </td>                <td><button type="button"  (click)="deletedata(i)" >Delete</button>                </td>                <td><button type="button"  (click)="addPersonalData()" >Add</button>                </td>              </tr>            </tbody>          </table>        </div>      </div>      <div class="modal-footer">        <button type="submit" class="btn btn-success">Submit</button>      </div>     </form>            this.SettingsForm = this.formBuilder.group({      id: [''],       Name: ['',Validators.required],      PersonalData: this.formBuilder.array([this.formBuilder.control('', Validators.required)])     });        PersonalData() : FormArray {      return this.SettingsForm.get("PersonalData") as FormArray    }      newPersonalData(): FormGroup {      return this.formBuilder.group({        id: '',        subject: '',        mark: '',       exams: '',     })    }      addPersonalData() {      this.PersonalData().push(this.newPersonalData());    }  

RStudio - Parsing HTML using readLines() function returns a different result every time

Posted: 08 Oct 2021 08:37 AM PDT

I'm writing an R Script to parse a web page and write the results into a .txt document.

How come, when I run the script below:

> folder <- "C:/Users/[username]/Documents/"  > url <- "https://sunrise-sunset.org/search?location=parkville%20missouri%20usa&year=2021&month=10#calendar"  > flat_html <- readLines(con = url)  > write.table(flat_html, file = paste0(folder,"flat_html.txt"))  

the resulting file contains anywhere from 200 to 700+ lines each time this script is run?

Sometimes the number of lines varies by just a few, sometimes quite a bit, and there doesn't seem to be a logic to the variations. For example, I can see in my Environment pane that the object flat_html currently contains 780 characters (lines), but when I run the the third line of code above for a second time, flat_html jumps up to 786 characters. Running the same line a third time, flat_html now contains only 235 characters.


[Edit] Should maybe also note the warning that message pops up when running this script:

> Warning message:  > In readLines(con = ex_url) :  >   incomplete final line found on 'https://sunrise-sunset.org/search?location=parkville%20missouri%20usa&year=2021&month=10#calendar'  

Replace an object that is inside of array if object id value from another array match

Posted: 08 Oct 2021 08:37 AM PDT

I have this arrays with objects that looks like this:

array1 = [   0:{id:145, value:130000},   1:{id:146, value:103300},   2:{id:147, value:79500},  ]    array2 = [   0:{id:145, value:135000}  ]  

And I want to replace the object inside the array if the id of the object in array2 match with some id of the object in array1

So I expect something like this:

array1 = [   0:{id:145, value:135000},   1:{id:146, value:103300},   2:{id:147, value:79500},  ]  

I have this code

array1.splice(1, 1, array2[0])  

but it returns me this:

array1 = [   0:{id:145, value:135000},   1:{id:145, value:130000},   2:{id:146, value:103300},   3:{id:147, value:79500},  ]  

Any help I'll appreciate

How to change the y axis of a histogram so it's a density function in r?

Posted: 08 Oct 2021 08:38 AM PDT

How is it possible that I can change a normal histogram in a way that the x-axis indicates not absolute numbers but the relative numbers, the density?

This is what my histogram looks like now:

hist(df$rent, xlim = c(0, 36), ylim = c(0, 300), breaks = 30)  

Vulnerabilities all about handlebars

Posted: 08 Oct 2021 08:37 AM PDT

npm audit fix      

up to date in 0.456s
fixed 0 of 7 vulnerabilities in 64 scanned packages

Critical: Remote code execution in handlebars when compiling templates
Package handlebars

Patched in >=4.7.7

Dependency of hbs

Path hbs > handlebars

More info https://github.com/advisories/GHSA-f2jv-r9rf-7988

High Arbitrary Code Execution in handlebars

Package handlebars

Patched in >=4.5.3

Dependency of hbs

Path hbs > handlebars

More info https://github.com/advisories/GHSA-q2c6-c6pm-g3gh

High Prototype Pollution in handlebars

Package handlebars

Patched in >=4.5.3

Dependency of hbs

Path hbs > handlebars

More info https://github.com/advisories/GHSA-g9r4-xpmj-mj65

High Arbitrary Code Execution in handlebars

Package handlebars

Patched in >=4.5.2

Dependency of hbs

Path hbs > handlebars

More info https://github.com/advisories/GHSA-2cf5-4w76-r9qv

Moderate Denial of Service in handlebars

Package handlebars

Patched in >=4.4.5

Dependency of hbs

Path hbs > handlebars

More info https://github.com/advisories/GHSA-f52g-6jhx-586p

Moderate Prototype Pollution in minimist

Package minimist

Patched in >=0.2.1

Dependency of hbs

Path hbs > handlebars > optimist > minimist

More info https://github.com/advisories/GHSA-vh95-rmgr-6w4m

How do you define a typescript record where some of the keys have types and the others are freeform?

Posted: 08 Oct 2021 08:38 AM PDT

I want to have the types for some of the keys in the record to be strict, and the remainder to be freeform.

type Make "Volvo" | "Polestar" | "Saab";  interface Car {      make: Make;      horsePower: number;      allWheelDrive: boolean;      ...  }  

and I want it accept

{      make: "Saab",      horsePower: 232,      allWheelDrive: true,      colour: "blue",      trim: "leather  }  

but not

{     make: "Daimler",     horsePower: 199,     allWheelDrive: false,     colour: "blue",     trim: "leather  }  

How do I write the Car interface to be able to do this with typescript?

Concrete example for the definition of parallel inheritance

Posted: 08 Oct 2021 08:37 AM PDT

While reading Dive Into Design Patterns by Alexander Shvets, I stumbled across the following statement in the section "Favor Composition Over Inheritance":

Trying to reuse code through inheritance can lead to creating parallel inheritance hierarchies

According to this site the definition of parallel inheritance is the situation in which subclassing a class requires creating yet another subclass elsewhere. I'm interested in knowing what would be this kind of scenario, where we'd have to subclass all over the place, and further more the why of it: why would we have to create the subclass elsewhere? Does the need arise from the context and the problem we are trying to solve, or is it induced by the structure of the (at least) two class hierarchies and composition between them? While here is an attempt to give a mathematical definition for the parallel inheritance, the need for the implication is not clear to me.

how to sequentially input in a child process and get each outputs?

Posted: 08 Oct 2021 08:38 AM PDT

I have a program called child.out where it accepts 4 kinds of input, and has different output for each type of inputs, and if the input is 0, it will output "bye" then the program will be terminated.

Let's say I want to run the said child program child.out inside a parent program called parent.out.

My question is in the parent program how can I pass the strings in the std::vector<std::string> inputs = {"1","3","2","0"}; sequentially as an input in the child process? then get the outputs of each inputs then store it in the std::vector<std::string> outputs;?

given below is the program that only runs the child program in the parent program, and at this point I'm stuck and I don't know what to do, It would be great if someone can help me, thanks.

ps: also If there is something wrong on the way I run the child process and handle the errors please point it out.


parent.out

//parent.cpp  #include <iostream>  #include <vector>  #include <unistd.h>  #include <string.h>  #include <sys/wait.h>  #include <stdio.h>  #include <stdlib.h>    int main()  {      std::vector<std::string> inputs = {"1","3","2","0"};        std::cout<<"Parent start\n";      std::vector<std::string> outputs;        int pipes[2];      pid_t pid;        char output[4096+1];      memset(output,0,4096);        if(pipe(pipes)==-1)      {          fprintf(stderr, "pipe error\n");          exit(EXIT_FAILURE);      }        pid = fork();        if(pid==-1)      {          fprintf(stderr, "fork error\n");          exit(EXIT_FAILURE);      }        if(pid==0)      {          std::cout<<"Child\n";          dup2(pipes[1],STDOUT_FILENO);          close(pipes[0]);          close(pipes[1]);          execl("./child.out","child.out","myName",NULL);          fprintf(stderr, "execl error\n");          exit(EXIT_FAILURE);      }      else      {          close(pipes[1]);          while(read(pipes[0],output,sizeof(output)))          {              outputs.push_back(output);              memset(output,0,4096);          }          wait(NULL);      }        std::cout<<"Back to Parent :\n";      std::cout<<"outputs : ";      for(auto e: outputs)      {          std::cout<<e<<"\n";      }        return 0;  }  

New Input does not change FormGroup disable property on Sub Component

Posted: 08 Oct 2021 08:38 AM PDT

I have two components Parent and Child.

Parent stores the state of the formGroup used in the child component. Each time I receive new data from external source, I pass this data through template and construct new FormGroup and decide based on one property if FormGroup is enabled or disabled. New data are changed as I want but the disabled/enabled state does not.

My code:

Child component

@Input() edvForm: FormGroup;  @Input() isBlocMainSupport: boolean;  @Input() data: Data;    ngOnChanges(changes: SimpleChanges): void {     this.setForm();  }    setForm() {     ...     this.edvForm.addControl(        'supportType',        new FormControl({ value: supportType, disabled: !this.isBlocMainSupport })     );  }  

Parent component

edvForm: FormGroup;  isBlocMainSupport = true;  data: Data;    ...    ngOnInit(): void {     this.sourceEvent$        .pipe(takeUntil(this.destroy$))        .subscribe(newData => {          this.newGraphicElements([newData]);        });  }    ...    newGraphicElements(newData: Data[]) {       this.reset();     ...     this.data = newData[0];     this.isBlocMainSupport = myCondition ? true : false;  }    ...    reset() {     this.edvForm = new FormGroup({});  }  

Parent template

<child-comp     *ngIf="isTheRightChild"     [data]="data"     [edvForm]="edvForm"     [isBlocMainSupport]="isBlocMainSupport"  ></child-comp>  

To resume, data are well passed and change everytime as needed. But, disable state is not applied with : "disabled: !this.isBlocMainSupport"

What HTTP method do I use to retrieve information when also requiring a one-time passcode?

Posted: 08 Oct 2021 08:38 AM PDT

I have done some research regarding this, but I haven't found a solid answer for this particular situation.

Let's say I have a route called /information that returns some sensitive data of a specified info_id and only if provided with a valid one_time_code.

I can think to do this in two ways:

  1. GET /information?info_id=x&one_time_code=y
  2. POST /information
    body: info_id = x, one_time_code = y

Response (this does not change, nor does anything else in the database - the one time code has an expiry - and can be cleared via a different way):

{      "info_owner_id" : "1234",      ...  }  

From how I understand it the GET approach would seem to be the more RESTful approach, but may not be ideal as the URL with the query strings would get saved in the browser and perhaps results would get cached along the way. Also, the info_id could leak along the way (even if using HTTPS as its in the URL).

However, with the POST approach, nothing is cached and expired codes won't be saved in the browser. However, nothing is created and in fact, the database isn't altered at all so it may not be the most 'logical' approach.

I'm struggling to understand what would be the best practices in this situation, I hope to receive some clarification.

Furthermore, if you think a completely different way is preferable, please let me know. I was thinking to use GET with authentication headers, but my site doesn't have 'users' in its database, but people can save their own info and get access to it with generated links (info_id / one time code sent via email).

Segfault with inheritence and casting

Posted: 08 Oct 2021 08:37 AM PDT

I am using an existing C++ which looks something like this

class Geometry {  public:      enum {BOX, MESH} type;      std::string name;  };    class Mesh : public Geometry {  public:      std::string filename;  };    std::shared_ptr<Geometry> getGeometry() {      std::shared_ptr<Geometry> geom = std::make_shared<Geometry>();      geom->name = "geometry";        Mesh *mesh = new Mesh();      mesh->name = "name";      mesh->filename = "filename";      mesh->type = Geometry::MESH;      geom.reset(mesh);        return geom;  }  

I need to extend the functionalities provided by these classes, so I have derived these two classes

#include <memory>  #include <iostream>    class Geometry {  public:      enum {BOX, MESH} type;      std::string name;  };    class Mesh : public Geometry {  public:      std::string filename;  };    std::shared_ptr<Geometry> getGeometry() {      std::shared_ptr<Geometry> geom = std::make_shared<Geometry>();      geom->name = "geometry";        Mesh *mesh = new Mesh();      mesh->name = "name";      mesh->filename = "filename";      mesh->type = Geometry::MESH;      geom.reset(mesh);        return geom;  }    class GeometryDerived : public Geometry {  public:      void consumeGeometry() {          Geometry geom = static_cast<Geometry>(*this);          std::cout << geom.name << std::endl;          if(geom.type == Geometry::MESH) {              Mesh *mesh = static_cast<Mesh*>(&geom);              std::cout << mesh->filename << std::endl;              // mesh->get_output();          }      }  };    class MeshDerived : public Mesh {  public:      std::string get_output() {          return this->filename;              }  };        int main(int argc, char** argv)  {      std::shared_ptr<Geometry> geom = getGeometry(); // this object is returned by the library        std::shared_ptr<GeometryDerived> geomDerived = std::static_pointer_cast<GeometryDerived>(geom);      geomDerived->consumeGeometry();        return 0;  }  

I get a segfault in line (in my actual code, its garbage string)

std::cout << mesh->filename << std::endl;  

though other ints and doubles are printed correctly. Even geom.name gets printed correctly. What is going on with strings here? What is the correct way to cast the objects here? Casting the object twice looks ugly. Below is the GDB output

GNU gdb (Ubuntu 9.2-0ubuntu1~20.04) 9.2  Copyright (C) 2020 Free Software Foundation, Inc.  License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>  This is free software: you are free to change and redistribute it.  There is NO WARRANTY, to the extent permitted by law.  Type "show copying" and "show warranty" for details.  This GDB was configured as "x86_64-linux-gnu".  Type "show configuration" for configuration details.  For bug reporting instructions, please see:  <http://www.gnu.org/software/gdb/bugs/>.  Find the GDB manual and other documentation resources online at:      <http://www.gnu.org/software/gdb/documentation/>.    For help, type "help".  Type "apropos word" to search for commands related to "word"...  Reading symbols from ./cpp-example...  (gdb) run  Starting program: /home/user/cpp-example  name    Program received signal SIGSEGV, Segmentation fault.  __memmove_avx_unaligned_erms () at ../sysdeps/x86_64/multiarch/memmove-vec-unaligned-erms.S:383  383 ../sysdeps/x86_64/multiarch/memmove-vec-unaligned-erms.S: No such file or directory.  (gdb) bt  #0  __memmove_avx_unaligned_erms () at ../sysdeps/x86_64/multiarch/memmove-vec-unaligned-erms.S:383  #1  0x00007ffff7c247b2 in _IO_new_file_xsputn (n=140737488346512, data=0xdb8bbc853a3b3400, f=<optimized out>) at fileops.c:1236  #2  _IO_new_file_xsputn (f=0x7ffff7d7e6a0 <_IO_2_1_stdout_>, data=0xdb8bbc853a3b3400, n=140737488346512) at fileops.c:1197  #3  0x00007ffff7c18541 in __GI__IO_fwrite (buf=0xdb8bbc853a3b3400, size=1, count=140737488346512, fp=0x7ffff7d7e6a0 <_IO_2_1_stdout_>) at libioP.h:948  #4  0x00007ffff7ed2824 in std::basic_ostream<char, std::char_traits<char> >& std::__ostream_insert<char, std::char_traits<char> >(std::basic_ostream<char, std::char_traits<char> >&, char const*, long) ()     from /lib/x86_64-linux-gnu/libstdc++.so.6  #5  0x0000555555556858 in GeometryDerived::consumeGeometry (this=0x55555556def0) at ../downcasting.cpp:23  #6  0x0000555555556513 in main (argc=1, argv=0x7fffffffdec8) at ../downcasting.cpp:53    

Edit 1: The following changes works fine, but this is not what I want

int main(int argc, char** argv)  {      std::shared_ptr<Geometry> geom = getGeometry();        if(geom->type == Geometry::MESH) {          std::shared_ptr<MeshDerived> meshDerived = std::static_pointer_cast<MeshDerived>(geom);          std::cout << meshDerived->filename << std::endl;      }        // std::shared_ptr<GeometryDerived> geomDerived = std::static_pointer_cast<GeometryDerived>(geom);      // geomDerived->consumeGeometry();        return 0;  }  

matplotlib doesn't display the correct data

Posted: 08 Oct 2021 08:37 AM PDT

I am new to Python. For some reason when I look at the plot it displays all the data as if Y = 0 but the last one, which is weird since when I ask it to print Y it displays the right values. What am I doing wrong?

import math  import numpy as np  import matplotlib.pyplot as plt    y0=2 # [m]  g=9.81 # [m/s^2]  v=20 # initial speed [m/s]  y_target=1 # [m]  x=35 # [m]  n_iter=50  theta=np.linspace(0,0.5*math.pi,n_iter) # theta input [rad]  Y=np.zeros(n_iter) # y output [m]  for i in range(n_iter):      Y[i]=math.tan(theta[i])*x-g/(2*(v*math.cos(theta[i]))**2)*x**2+y0    plt.plot(theta,Y)  plt.ylabel('y [m]')  plt.xlabel('theta [rad]')  plt.ylim(top=max(Y),bottom=min(Y))  plt.show()  

Using Pivot or UnPivot to get Output Dynamically

Posted: 08 Oct 2021 08:37 AM PDT

I have a table with the following structure that I want to receive output from this table dynamically. But I do not know how to use Pivot and UnPivot.

The list of fields I use is as follows.

    SELECT [RoomID]            ,[RoomNumber]            ,[RoomType]            ,[RoomTypeDescription]            ,[RoomBed]            ,[PriceOfPerNight]            ,[RoomStatuse]            ,[RoomStatuseDesc]            ,[RoomFloorID]            ,[RoomFloorTitle]        FROM [HotelOnline].[dbo].[XtblRooms]          RoomID  RoomNumber  RType   RDesc       Beds    Price       RoomStatuse RDesc   FloorID RoomFloorTitle      1   RM100001    2   Degree 2    6   9000000.00  1   Free    1   Floor 001      2   RM100002    1   Degree 1    4   6000000.00  1   Free    1   Floor 001      3   RM100003    2   Degree 2    3   4500000.00  1   Free    1   Floor 001      4   RM100004    3   Degree 3    5   4800000.00  1   Free    1   Floor 001      5   RM100005    1   Degree 1    3   4700000.00  1   Free    1   Floor 001      6   RM100006    1   Degree 1    6   7500000.00  1   Free    1   Floor 001      7   RM100007    1   Degree 1    5   7000000.00  1   Free    1   Floor 001      8   RM100008    1   Degree 1    2   2500000.00  1   Free    1   Floor 001      9   RM100009    3   Degree 3    3   3500000.00  1   Free    1   Floor 001      10  RM100010    3   Degree 3    8   8000000.00  1   Free    1   Floor 001      11  RM100011    2   Degree 2    5   6500000.00  1   Free    2   Floor 002      12  RM100012    3   Degree 3    2   3800000.00  1   Free    2   Floor 002      13  RM100013    2   Degree 2    5   9650000.00  1   Free    2   Floor 002      14  RM100014    3   Degree 3    2   2500000.00  1   Free    2   Floor 002      15  RM100015    2   Degree 2    2   4500000.00  1   Free    2   Floor 002      16  RM100016    3   Degree 3    4   4000000.00  1   Free    2   Floor 002      17  RM100017    1   Degree 1    2   2500000.00  1   Free    2   Floor 002      18  RM100018    3   Degree 3    3   4500000.00  1   Free    2   Floor 002      19  RM100019    2   Degree 2    5   5000000.00  1   Free    2   Floor 002      20  RM100020    2   Degree 2    4   4500000.00  1   Free    2   Floor 002      21  RM100021    1   Degree 1    6   7500000.00  1   Free    3   Floor 003      22  RM100022    2   Degree 2    3   3000000.00  1   Free    3   Floor 003      23  RM100023    3   Degree 3    3   2500000.00  1   Free    3   Floor 003      24  RM100024    1   Degree 1    3   2500000.00  1   Free    3   Floor 003      25  RM100025    2   Degree 2    5   4800000.00  1   Free    3   Floor 003      26  RM100026    3   Degree 3    4   4000000.00  1   Free    3   Floor 003      27  RM100027    2   Degree 2    2   1800000.00  1   Free    3   Floor 003      28  RM100028    3   Degree 3    5   4700000.00  1   Free    3   Floor 003      29  RM100029    1   Degree 1    3   3500000.00  1   Free    3   Floor 003      30  RM100030    2   Degree 2    6   4600000.00  1   Free    3   Floor 003      31  RM100031    2   Degree 2    5   4500000.00  1   Free    4   Floor 004      32  RM100032    1   Degree 1    2   3500000.00  1   Free    4   Floor 004      33  RM100033    3   Degree 3    4   3700000.00  1   Free    4   Floor 004      34  RM100034    2   Degree 2    3   2800000.00  1   Free    4   Floor 004      35  RM100035    3   Degree 3    6   5500000.00  1   Free    4   Floor 004      36  RM100036    2   Degree 2    4   3700000.00  1   Free    4   Floor 004      37  RM100037    3   Degree 3    6   5800000.00  1   Free    4   Floor 004      38  RM100038    1   Degree 1    3   4000000.00  1   Free    4   Floor 004      39  RM100039    1   Degree 1    5   5500000.00  1   Free    4   Floor 004      40  RM100040    1   Degree 1    6   6500000.00  1   Free    4   Floor 004      41  RM100041    1   Degree 1    4   4500000.00  1   Free    5   Floor 005      42  RM100042    2   Degree 2    6   5500000.00  1   Free    5   Floor 005      43  RM100043    2   Degree 2    4   4000000.00  1   Free    5   Floor 005      44  RM100044    2   Degree 2    3   3500000.00  1   Free    5   Floor 005      45  RM100045    3   Degree 3    3   3000000.00  1   Free    5   Floor 005      46  RM100046    3   Degree 3    5   4000000.00  1   Free    5   Floor 005      47  RM100047    3   Degree 3    4   3900000.00  1   Free    5   Floor 005      48  RM100048    2   Degree 2    5   4700000.00  1   Free    5   Floor 005      49  RM100049    2   Degree 2    3   3800000.00  1   Free    5   Floor 005      50  RM100050    3   Degree 3    5   4700000.00  1   Free    5   Floor 005  

This is the output I need.

    Floor 001   Floor 002   Floor 003   Floor 004   Floor 005      ==========================================================      RM100001    RM100012    RM100028    RM100033    RM100049      RM100002    RM100013    RM100029    RM100033    RM100050      .. . . . . .   

I tried several ways but did not get the answer. Help if possible. I tried several ways but did not get the answer. Help if possible. If possible, use the dynamic method to get the answer. It does not matter if it is not for you. My problem will be solved in the same way as usual.

(Tailwind - DaisyUI) Is there anyways to change hover and active colors of dropdown items?

Posted: 08 Oct 2021 08:37 AM PDT

I use TailwindCSS with DaisyUI.

When using DasiyUI Dropdown, is there any way for me to change the color of the dropdown item? This includes the background color of the dropdown itself, then hovering on item (CSS :hover), and clicking on it (CSS :active).

When Clicking (When Clicking)

So far, I've been able to change the background color of the dropdown itself and when hovering.

                    <div class="dropdown">                      <div tabindex="0" class="m-1 btn clickables btn-green shadow">                          <p class="text-medium">Testing</p>                      </div>                      <ul tabindex="0" class="p-2 shadow menu dropdown-content bg-white text-black rounded-box w-52 text-sm">                          <li class="rounded hover:bg-gray-300 dropdown-active">                              <a href="page-one.html">Protecting your privacy</a>                          </li>                      </ul>                  </div>  

I can't seem to get when the list is clicked color (CSS active) with:

.dropdown-active:active {     background-color: #0B6339 !important;   }  

Delay in Contact form and Subscribe for - SMTP

Posted: 08 Oct 2021 08:38 AM PDT

I'm writing this query after searching insanely online. I'm not a geek so I have limited understanding of technical stuff. My Problem - I'm on VPS with Hostinger and installed Cyberpanel with cent os 7. I have nearly 6 websites under that hosting. Most of them are wordpress and laravel. All the sites have contact forms which I've built either through Elementor or Wordpress plugins or readymade smtp script on Laravel. My issue is all the contact form from all sites work really slow. I mean the submission takes almost couple of minutes. The plugin provider says its the hosting issue and the hosting provider says otherwise. I tried searching and editing PHP config file and with gmail but couldn't get through.. Can somebody help me with this issue and/or help to setup Gmail.

Thank you.

Sort list of lists based on date and first element

Posted: 08 Oct 2021 08:37 AM PDT

ArrayData = [['a', 'ad', '02/10/2021  7:39:19 am', 'Rank:1'],               ['b', 'db', '02/10/2021 6:25:20 am', 'Rank:2'],               ['a', 'sd', '02/10/2021  5:39:19 am', 'Rank:3'],               ['b', 'esas', '02/10/2021 6:25:20 am', 'Rank:1'],               ['a', 'aser', '02/10/2021  9:39:19 am', 'Rank:2'],               ['d', 'ssss', '02/10/2021  11:39:19 am', 'Rank:1']]  

The script should

  1. Sort the same group (eg. sort group 'a' first, followed by group 'b', 'c', 'd') base on the time. More recent times and dates have higher ranks.

  2. Update the "rank" in each subarray

Expected output:

[['d', 'ssss', '02/10/2021  11:39:19 am', 'Rank:1'],   ['b', 'esas', '03/10/2021 6:25:20 am', 'Rank:2'],   ['b', 'db', '02/10/2021 6:25:20 am', 'Rank:1'],   ['a', 'aser', '02/10/2021  9:39:19 am', 'Rank:3'],   ['a', 'ad', '02/10/2021  7:39:19 am', 'Rank:2'],   ['a', 'sd', '02/10/2021  5:39:19 am', 'Rank:1']]  

This is the current script I wrote

import operator  result = sorted(ArrayData, key=operator.itemgetter(2), reverse=True)  print(result)  

May I know how to improve it?

replace() error in MAGE function in R's iglu package for glucose analysis

Posted: 08 Oct 2021 08:37 AM PDT

I'm trying to use the all_metrics() function of the iglu package in R. The function always throws an error when calling the mage_ma_single() function, which itself gets called by the mage() function. Here's the package's function's source code which leads to an error, see lines 58 to 64.

Here's the error I'm getting:

Error: Problem with mutate() column MA_Long. ℹ MA_Long = replace(MA_Long, 1:long_ma, MA_Long[long_ma]). ℹ MA_Long must be size 5 or 1, not 23.

Here's some sample data with which I can reproduce the error:

structure(list(id = c(1, 1, 1, 1, 1), time = structure(c(1611228720, 1611229080, 1611247620, 1611249960, 1611263940), class = c("POSIXct", "POSIXt"), tzone = ""), gl = c(97L, 90L, 89L, 96L, 87L)), row.names = c(NA, 5L), class = "data.frame")  

How do I grep for all non-ASCII characters?

Posted: 08 Oct 2021 08:38 AM PDT

I have several very large XML files and I'm trying to find the lines that contain non-ASCII characters. I've tried the following:

grep -e "[\x{00FF}-\x{FFFF}]" file.xml  

But this returns every line in the file, regardless of whether the line contains a character in the range specified.

Do I have the syntax wrong or am I doing something else wrong? I've also tried:

egrep "[\x{00FF}-\x{FFFF}]" file.xml   

(with both single and double quotes surrounding the pattern).

No comments:

Post a Comment