Thursday, July 14, 2022

Recent Questions - Stack Overflow

Recent Questions - Stack Overflow


Apexchart angular: Mounted event called twice

Posted: 14 Jul 2022 02:51 AM PDT

I currently have an ApexChart in my Angular application:

<apx-chart *ngIf="chartOptions" #chart            [yaxis]="chartOptions.yaxis"            [xaxis]="chartOptions.xaxis"            [series]="chartOptions.series"            [chart]="chartOptions.chart"            [stroke]="chartOptions.stroke"            [markers]="chartOptions.markers"            [plotOptions]="chartOptions.plotOptions"            [legend]="chartOptions.legend"            [fill]="chartOptions.fill"            [responsive]="chartOptions.responsive"            [tooltip]="chartOptions.tooltip"          ></apx-chart>  

With the following JS:

this.chartOptions = {        ...        chart: {          events: {            mounted: (chartContext, config) => {              this.chartMounted(chartContext, config);            }          }        }       ...      }  

Works fine but the 'mounted' event is always called twice. I tried using only one series to check if it mounted per series, but then also it was called twice. Any idea why this happens?

Get only message or description in the notification using flask abort?

Posted: 14 Jul 2022 02:51 AM PDT

I want to get the error message on the screen, I tried all these variations

abort(make_response(jsonify(message="Error message"), 400))  abort(400, description ="invalid inputs")  

The problem is it's showing

{"code": 400, "name": "Bad Request", "description": "Invalid inputs; gewea.tcy: File format not supported"}  

in the notification box. I don't want any of that, I just want the message or description and I am flabbergasted of not being able to find solution. Help!

POSTGRESQL FILE OR IMAGE UPLOAD USING JDBC DRIVER

Posted: 14 Jul 2022 02:51 AM PDT

I have to insert file or images into the postgresql database. i have designed table with jsonb column data type. Previously i have used bytea as column data type and used jdbc driver method setBinary to set data in prepared statement. Now i have to use jsonb and what is jdbc driver method i have to use to insert my file or jsonb is not supported for files.

Arm azure table - entity/ item

Posted: 14 Jul 2022 02:51 AM PDT

I just deployed through arm template new storage and table

I wonder how can I deploy it with adding entities

also if I could populate some of the rows in arm also

someone can help me please ?

How to check programmatically that user has enable the AutoStart permission or not ? (in MI devices)

Posted: 14 Jul 2022 02:51 AM PDT

I am able to to go setting & comeback from it but didn't get if user has enable the AutoStart or not.

Read data from pyodbc to dask

Posted: 14 Jul 2022 02:51 AM PDT

At the moment connecting from pyodbc and reading the data to a pandas data frame. However, I want to change the codebase to use desk instead of pandas. Is there a simple way to use dask without changing much of this code?

cnxn = pyodbc.connect(  'DRIVER={ODBC Driver 18 for SQL Server}; \      SERVER='+  os.environ['server'] +'; \      DATABASE='+ os.environ['database'] +';\      uid='+ os.environ['uid'] +';\      pwd='+ os.environ['pwd'] +';\      Trusted_Connection=no;')  #get last 10 days of data  datetime_limit = str(datetime.today() - timedelta(days=10))[:-3]  #use env var for table to protect from sql injection   sql = f"SELECT * from {os.environ['dbtable']} WHERE {os.environ['limiter']} > '{datetime_limit}' "  data = pd.read_sql(sql,cnxn)  

How to fix the error when working with recursion and array?

Posted: 14 Jul 2022 02:50 AM PDT

I'm trying to solve a problem - need to return an array after entering a value to search. The depth of an array can be theoretically infinite. So I'm recursing to find suitable elements among any depth level and add them to the array and then return this array. But this code does not work as expected. I can't figure out what exactly I did wrong here.

Also link to codeSandbox - https://codesandbox.io/s/pensive-montalcini-ms1jir?file=/src/index.js:0-1177

const newList = [    {        role: "role111",        title: "title1",      },    {        role: "role222",        title: "title2",    },    {        role: "role333",        title: "title3",    },    {        role: "role444",        title: "title4",        items: [{            role: "role555",            title: "title5",        }, {            role: "role666",            title: "title6",        }, {            role: "role777",            title: "title7",            items: [{                role: "role888",                title: "title888",            },{                role: "role8888",                title: "title8888",            },]        },]    },    {        role: "role999",        title: "title999",    },  ];    const text = "role888";      const testFunction = (    list,    text,    emptyArray  ) => {    let arrayForRender = emptyArray;      return list?.filter((item) => {        if (item.title.toLowerCase().includes(text.toLowerCase())) {            arrayForRender = [...arrayForRender, item];            return arrayForRender;        }        if (item.items && item.items?.length > 0) {            testFunction(item.items, text, arrayForRender);        }    });  };    console.log(testFunction(newList, text, []));  

Does SignInAsync have the ability to create jwt like how it does for cookies? And whether to avoid using SignInAsycn when using JWT auth?

Posted: 14 Jul 2022 02:50 AM PDT

I have a project with .NET Identity tables and SignIn and User manager. The SignInManager.PasswordSignInAsync checks whether the username and password is correct and if so then it will create the cookie as part of the response. Currently the authentication configured is the default cookie based.

Following is the existing example of login action:

[HttpPost]  [AllowAnonymous]  [ValidateAntiForgeryToken]  public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)  {      if (!ModelState.IsValid)      {          return View(model);      }        // Require the user to have a confirmed email before they can log on.      var user = await UserManager.FindByNameAsync(model.Email);         // This doesn't count login failures towards account lockout      // To enable password failures to trigger account lockout, change to shouldLockout: true      var result = await SignInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, shouldLockout: false);      switch (result)      {          case SignInStatus.Success:              return RedirectToLocal(returnUrl);          case SignInStatus.Failure:          default:              ModelState.AddModelError("", "Invalid login attempt.");              return View(model);      }  }  

I want to change this to JWT based and for this I plan to create the following:

  1. GetUserFromDb(username, password) - this will be called instead of SignInManager.PasswordSignInAsync and it will check in the db if the user exists and return the user details
  2. CreateJWT(userdetails) - the output of point 1 will be passed into this method as an argument and this method will build the JWT token with user name, and all the claims.
  3. Change the authentication scheme in startup to JWT bearer based

Instead of doing any of the above manual work, I want to ask-

  1. Suppose I change the authentication scheme to JWT bearer based, then does SignInManager.PasswordSignInAsync have the ability to return a JWT rather than the cookie?
  2. During User registration, I can continue using var result = await UserManager.CreateAsync(user, model.Password);. But during login does it make sense to use SignInManager.PasswordSignInAsync (to check user/password) and then call the GetUserFromDb (to return user info) followed by CreateJWT (to set JWT)? Or should I prefer to not use the SignInManager.PasswordSignInAsync?
  3. Does SignInManager.PasswordSignInAsync create cookie in the response only if the authentication scheme is default (cookie based) or does it do so even if the Authentication scheme is changed to JWT bearer based? In this case it doesn't make sense to use SignInManager.PasswordSignInAsync when doing a JWT based authentication?

Query the Euclidean Distance between points and and format your answer to display decimal digits

Posted: 14 Jul 2022 02:51 AM PDT

select round((sqrt((pow((max(lat_n)-min(lat_n)),2))+(pow((max(long_w)-min(long_w)),2)))),4)   from station;  

Link to the question HackerRank

Backtesting a trading strategy of buy and sell using backtesting package

Posted: 14 Jul 2022 02:51 AM PDT

I tried to backtest a strategy of buying and selling a stock using package backtesting but i obtain the same result for all (i,j). The code is bellow

from backtesting import Backtest, Strategy  from fastquant import get_stock_data  vix=get_stock_data("^VIX","2007-06-01","2010-01-01")  vix=vix.reset_index()  vix=vix.rename(columns={'dt':'','open':'Open','high':'High','low':'Low','close':'Close','volume':'Volume'})  vix=vix.set_index('')  class vixstrategy(Strategy):      def init(self):          price = self.data.Close      def next(self):          self.buy_int=i          self.sell_int=j          self.buy()          self.sell()  table=[]  for i in range(10,30,5):      for j in range(30,50,5):          bt = Backtest(vix, vixstrategy,exclusive_orders=True)          resultat = bt.run()          print(resultat)           table.append(resultat[["Equity Final [$]","Return [%]","Sharpe Ratio","Max. Drawdown [%]","# Trades","Avg. Trade Duration","Duration","Max. Trade Duration"]])          bt.plot()  df = pandas.DataFrame(table)  print(df)  

Could you give me some suggestions

Change names of columns which contain only positive values

Posted: 14 Jul 2022 02:50 AM PDT

Let's consider data frame following:

import pandas as pd  df = pd.DataFrame([[1, -2, 3, -5, 4 ,2 ,7 ,-8 ,2], [2, -4, 6, 7, -8, 9, 5, 3, 2], [2, 4, 6, 7, 8, 9, 5, 3, 2], [1, 2, 3, 4, 5, 6, 7, 8, 9]]).transpose()  df.columns = ["A", "B", "C", "D"]       A  B  C  D  0  1  2  2  1  1 -2 -4  4  2  2  3  6  6  3  3 -5  7  7  4  4  4 -8  8  5  5  2  9  9  6  6  7  5  5  7  7 -8  3  3  8  8  2  2  2  9  

I want to add at the end of the column name "pos" if column contain only positive values. What I would do with it is:

pos_idx = df.loc[:, (df>0).all()].columns  df[pos_idx].columns = df[pos_idx].columns + "pos"  

However it seems not to work - it returns no error, however it does not change column names. Moreover, what is very interesting, is that code:

df.columns = df.columns + "anything"  

actually add to column names word "anything". Could you please explain to me why it happens (works in general case, but it does not work on index case), and how to do this correctly?

Why Where clause in not working with Virtual property in LINQ

Posted: 14 Jul 2022 02:50 AM PDT

I am trying to do something like this

var users = await _dbContext.Users.AsNoTracking().AsQueryable()      .Include(user => user.AdminRoles)      .Where(u => u.AdminRoles.Roles.Contains("admin2022"))      .ToListAsync();  

Here the list is getting 0 results, but when I do

var users = (await _dbContext.Users.AsNoTracking().AsQueryable()       .Include(user => user.AdminRoles).ToListAsync())           .Where(u => u.AdminRoles.Roles.Contains("admin2022"))           .ToList();  

Then it yields all the required results. Could some one please help me how can I make the first way work ?

Parse string of key value pairs where key occurs multiple times into object

Posted: 14 Jul 2022 02:50 AM PDT

I have a string in the following format:

"foo: bar, foo: baz, some: thing, some: other, third: other"

And what i want is an object:

{     foo: [bar, baz],    some: [other, thing],    third: [other]  }  

How could I achieve this in a smart way?

Launch ZAP using a script if not already running

Posted: 14 Jul 2022 02:51 AM PDT

I launch ZAP with a python script using subprocess:

filePath=r"C:\\Program Files\\OWASP\\Zed Attack Proxy\\zap-2.11.1.jar"  subprocess.Popen(filePath, shell=True, stdout=subprocess.PIPE)  

This script works fine and launches ZAP. However, I'd like to have a check whether the app is already running and if so, not to launch it again. I took a look how could this be achieved in python and realized I could use a check for running processes. Problem is that the process runs as Java(TM) Platform SE binary in Task Manager so checking for that one might not be the best solution. Any idea how to solve this would be appreciated. Aiming for python/ps script. Thank you!

TCN model result seems like offset by one time step

Posted: 14 Jul 2022 02:51 AM PDT

I have been training a temperature dataset with TCN model. I Have tested it on small data available. I am training a bivariate TCN model with the data which I am giving input is Maximum temperature and minimum temperature to predict maximum temperature. I want to know if this is overfitting or if the graph is right Graph here

Below is my model

i = Input(shape=(lookback_window, 2))  m = TCN(nb_filters =   64,dropout_rate=0.1,activation='relu',padding='causal')(i)  m = Dense(3, activation='linear')(m)    model = Model(inputs=[i], outputs=[m])  model.summary()  

The summary of the model is given here

Net Framework - WaitForExit not working because I can't determine svchost.exe PID

Posted: 14 Jul 2022 02:51 AM PDT

I need to show the Windows Task Scheduler window and wait until the user closes it before continuing the main program.

I've tried with this method:

public static bool RunCommand (string command)      {          try          {              ProcessStartInfo startInfo = new ProcessStartInfo              {                  FileName = "cmd.exe",                  Verb = "runas",                  Arguments = "/C " + command,                  UseShellExecute = false              };                Process process = new();              process.StartInfo = startInfo;              process.Start();              process.WaitForExit();                return true;          }          catch (Exception)          {              return false;              throw;          }      }  

I've tried passing the following commands as the argument "command" in order to show up the Task Scheduler:

  • "taskschd.msc"
  • "start /wait taskschd.msc /s"
  • "C:\windows\system32\taskschd.msc /s"
  • "control schedtasks"

The idea is to continue the execution of the main program when the Task Scheduler is closed (its process is killed), but the "process.WaitForExit();" instruction is linked to the cmd command, so the main program continues after cmd process is closed, even when the Task Scheduler window is still being displayed.

The problem is that the "taskschd.msc" process, when launched, is wrapped into an "svchost.exe" process. I can't determine its PID because of the many different svchosts running at the same time, so I can't kill it manually either.

I've tried the solutions proposed here, but to no avail.

I've also been looking for a way to give an alias to the the "scvhost.exe" process launched with this cmd, but it seems that's not possible.

I've been thinking of compiling a new exe just to launch the Task Scheduler under a process name that I could control, but I don't think it is a good solution.

Any ideas, please? Thank you very much.

google submit sheet check for duplicate

Posted: 14 Jul 2022 02:51 AM PDT

Anyone can advise that how could I check data from my submission form and doesn't allow proceed if there is a duplicate data from my database sheet and if no duplicate and proceed for data entry.

here my gs code

// SUBMIT FORM DEPOSIT   function submit() {    var ss = SpreadsheetApp.getActiveSpreadsheet();    var formS = ss.getSheetByName("Form"); //form entry sheet     var extdata = SpreadsheetApp.openByUrl("https://docs.google.com/spreadsheets/d/1BDKOHu0H7OddXeCIDYn1o6EwLd123fYgQFmRHC-SR5C1Zs/edit#gid=0")    var dataS = extdata.getSheetByName("Database");//form sheet     var duplicate = formS.getRange("B9").getValue();      var values = dataS.getDataRange().getValues();    for (var i = 0; i < values.length; i++) {      var row = values[i];      if (row[0] == duplicate) {        SpreadsheetApp.getUi().alert('Duplicate data. Please Check Your Input Data');      }      else {        var values = [[formS.getRange("B9").getValue(), formS.getRange("B7").getValue(),        formS.getRange("B11").getValue(),        formS.getRange("B13").getValue(),        formS.getRange("B15").getValue(),        formS.getRange("B19").getValue(),        formS.getRange("B17").getValue(), formS.getRange("B5").getValue()]]; dataS.getRange(dataS.getLastRow() + 1, 1, 1, 8).setValues(values); clearcell();      }    }  }  

How to bind Query parameter into the datetime using room

Posted: 14 Jul 2022 02:50 AM PDT

I would like to bind a parameter into the datetime method of a sql query. You can see below what I tried. I have tried enum too, but it seems enums are parsed by the name of enum and I can't give -7 days as a value to enum

The query i would like the code to produce looks like this.

SELECT * FROM Part where Timestamp > datetime('now' ,'-7 days')  

Code#1

@Query("SELECT * FROM Part where Timestamp >datetime('now' ,'-'+:days+'days')")  List<Part> getPastDays(int days);  

Produces query#1

(is incorrect as it does not fetch the data)

SELECT * FROM Part where Timestamp >datetime('now' ,'-'+'7'+'days')  

Code#2(Does not compile->error: Unused parameter: days)

@Query("SELECT * FROM Part where Timestamp >datetime('now' ,'- :days days')")  List<Part> getPastDays(int days);  

Code#3

@Query("SELECT * FROM Part where Timestamp >datetime('now' ,'-' /:days/ 'days')")  List<Part> getPastDays(int days);  

Produces Query#3( is incorrect as does not return data)

SELECT * FROM Part where Timestamp >datetime('now' ,'-' /'7'/ 'days')  

Xamarin iOS only crash physical iPhone when you open an app

Posted: 14 Jul 2022 02:50 AM PDT

I'm facing a strange error. App only crashes on physical device. But iOS simulator does not. It working fine.

The strange thing is it crashes when you open an app and FinishedLaunching(UIApplication app, NSDictionary options) method does not call at all.

What possibilities might have this issue?

how to get a particular field from django model

Posted: 14 Jul 2022 02:51 AM PDT

I want a command for getting a query set from the model. The SQL command will be like - SELECT teamName FROM TABLE WHERE userName=userName;

PictureBox with SizeMode = Zoom and image size

Posted: 14 Jul 2022 02:51 AM PDT

I have Large image in PictureBox with SizeMode = Zoom. How can I get pixel coords from image when I click on PictureBox or how get image position and size in this case? Thanks all for any help.

App window

Graphql create object with fragment

Posted: 14 Jul 2022 02:50 AM PDT

I can query a graphql object like this

info {    firstname    lastname    phone    email  }  

I want to create an object contactInfo so I can query contactInfo and put phone and email inside that.

info {    firstname    lastname    ...contactInfo  }  
fragment contactInfo on person {    contactInfo: {       phone       email    }  }    

but this keeps giving me error, how can I use fragment to put phone and email inside contactInfo?

CORS configuration not working in Drupal 9 [closed]

Posted: 14 Jul 2022 02:50 AM PDT

I have a website (static react) "example.com" and a admin website (drupal) "admin.example.com". In Drupal I enabled the rest api json module to fetch the data.

Now at example.com I get an cors error. Understandable.

I tried to fix this by editing services.yml and default.services.yml to the following, but still I get a 500 error from the server when requesting something. If I try to get something with Postman or just the browser, everything works fine.

Access to fetch at 'https://admin.example.com/jsonapi/node/stage' from origin 'https://example.com' has been blocked by CORS policy: The 'Access-Control-Allow-Origin' header contains multiple values '*, https://example.com', but only one is allowed. Have the server send the header with a valid value, or, if an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

cors.config:  enabled: true  # Specify allowed headers, like 'x-allowed-header'.  allowedHeaders: ['x-csrf-token', 'authorization', 'content-type', 'accept', 'origin', 'x-requested-with']  # Specify allowed request methods, specify ['*'] to allow all possible ones.  allowedMethods: ['*']  # Configure requests allowed from specific origins.  allowedOrigins: ['example.com', 'www.example.com', 'http://example.com', 'https://example.com', 'http://www.example.com', 'https://www.example.com', '*']  # Sets the Access-Control-Expose-Headers header.  exposedHeaders: false  # Sets the Access-Control-Max-Age header.  maxAge: false  # Sets the Access-Control-Allow-Credentials header.  supportsCredentials: false  

How to take out unique key value pairs with it's other values as well

Posted: 14 Jul 2022 02:50 AM PDT

Help me in taking out unique fruit without reducing it's repeat count ?

I've been trying to arrange this array in an order to take out the same fruit name objects to a seperate array.

I am trying to get something like this :

 [{fruit:'apple',id:2},{fruit:'apple',id:6},{fruit:'apple',id:5},{fruit:'apple',id:6},{fruit:'apple',id:9},{fruit:'grape',id:3},{fruit:'grape',id:10},{fruit:'orange',id:4},{fruit:'orange',id:8},{fruit:'banana',id:7},{fruit:'banana',id:11}]  

From the array

const arr=  [{fruit:'apple',id:2},{fruit:'grape',id:3},{fruit:'orange',id:4},{fruit:'apple',id:5},              {fruit:'apple',id:6},{fruit:'banana',id:7},{fruit:'orange',id:8},             {fruit:'apple',id:9},{fruit:'grape',id:10},{fruit:'banana',id:11}]  

Android Emulator keep showing allow USB debugging prompt

Posted: 14 Jul 2022 02:51 AM PDT

I just installed Android Studio Bumblebee (2021.1.1 Patch 2)

But when I try to run my emulator, I got allow USB debugging prompt that always showed up even after I press allow, check the always allow option, or even cancel it. I already tried to restart my adb server and remove and create a new emulator, wipe the data and try to cold boot it, but the issue persists.

Does anyone know what is the root cause of this issue and how to solve it?

I can still develop using real device but I do want to know if this issue able to be resolved.

emulator keep showing prompt

Emulator: Google Pixel 3 API 30

PowerBi Service principals and Row level Security

Posted: 14 Jul 2022 02:51 AM PDT

We are using PowerBi and would like to embed a report in another system. We have set up everything so far and can display the reports with a service principal for several users. However, we only want the users to see their own records, so we have created roles that only display a few records based on the username. This works well in the PowerBi Desktop 'view as'. But when we request the embed token from the other system, we get a 400 response code back. I have read the following(https://docs.microsoft.com/en-us/power-bi/enterprise/service-admin-rls):

Service principals cannot be added to an RLS role. Accordingly, RLS won't be applied for apps using a service principal as the final effective identity.

Can I then achieve my goal at all, that a large group of users can view a report and only see their own data? Or is that only possible if I create a separate account for each user?

My report without roles can be embedded. That works. Then I added a role to my report. Role is Owner and DAX is [Owner__c] = USERNAME() enter image description here

And adjusted the body of the API from:

{  "accessLevel": "View",  "datasetId": "8d72284e-f104-4213-9376-606397b2f838"  }  

to

{  "accessLevel": "View",  "allowSaveAs": "false",  "identities": [{      "username": "0015p00005ZSE7wAAH",      "reports": ["7fa1badb-ccb3-45b8-84cb-15e5b2018efa"],      "roles": ["Owner"],      "datasets": ["8d72284e-f104-4213-9376-606397b2f838"]  }]  

}

This is a my datatable enter image description here

Did I miss a point? Do I need to add someone(who?) to this the role under dataset security?

Why is USERPRINCIPALNAME() or USERNAME() not the id, which I defined in the request body? As soon as I add a role to my report(Dax:[Owner__c] = TRUE) or ([Owner__c] = USERNAME() or even hardcoded [Owner__c]='0015p00005ZSE7wAAH') I get a status code 400

How to modify request headers in Next.js

Posted: 14 Jul 2022 02:51 AM PDT

I have a need to add a header to each request to the server.

I do it this using _midleware like this:

export async function middleware(req: NextRequest): Promise<NextResponse> {      req.headers.append('x-custom-header', '1337');      return NextResponse.next();  }  

If I do console.log(req.headers) I see that the request header has been added:

BaseHeaders [Headers] {      [Symbol(map)]: {        accept: [ '*/*' ],        'accept-encoding': [ 'gzip, deflate, br' ],        'accept-language': [ 'en-GB,en-US;q=0.9,en;q=0.8' ],        'cache-control': [ 'no-cache' ],        connection: [ 'keep-alive' ],        cookie: ...,        host: ...,        pragma: [ 'no-cache' ],        referer: ...,        ...,        'x-custom-header': [ '1337' ]      }    }  

However, this does not modify the request: there is no request header in the browser.

Why is the request not modified? Are there alternative ways to modify request headers in Next.js?

How to use v-bind=$attrs in vue 3?

Posted: 14 Jul 2022 02:51 AM PDT

I am migrating vue 2 application to vue 3. In official docs, it is mentioned that $listeners object has been removed in Vue 3. Event listeners are now part of $attrs. It is taking non-prop attributes (class, style) as well. In my vue 2 application, there is one icon-button custom component and it is looking like this below.

Icon-component:

<template>      <vu-button v-bind="buttonProps"                 :class="buttonClass"                  v-on="$listeners"                          @click="buttonToggle">          <vu-icon v-bind="iconProps"><slot/></vu-icon>      </vu-button>  </template>  

It is used in various other components.

Parent component 1:

<vu-icon-button id="sw1" medium style="left:200px;">home</vu-icon-button>  

Parent component 2:

<vu-icon-button class="menu-detail-btn" icon="collapse_menu" icon-type="su" @click="openModal()" size="small"></vu-icon-button>  

As of migration strategy, i removed the $listeners but not sure about those non-prop attributes and v-bind tag. How to modify those so it can be used in parent component with attributes?

std::string::append crashes program with "std::bad_alloc"

Posted: 14 Jul 2022 02:50 AM PDT

I have a text file which contains a list of data relating to name, position, and height. My program parses this data into a vector map, then uses this data to construct an xml file using boost::property_tree. The text file is about 3500 lines, and the program consistently crashes at line 1773 with:

terminate called after throwing an instance of 'std::bad_alloc'    what():  std::bad_alloc  Aborted (core dumped)  

At first I thought maybe the size limit was being reached, but reading up on std::string shows that the target computer should be able to allocate the size required. Regardless, I decided to test with std::string::size , std::string::length, std::string::capacity, std::string::max_size which showed (respectively):

...  ...  6572094845  6572094845 6626476032 9223372036854775807  6579537815  6579537815 6626476032 9223372036854775807  6586984998  6586984998 6626476032 9223372036854775807  6594436394  6594436394 6626476032 9223372036854775807  6601892003  6601892003 6626476032 9223372036854775807  6609351825  6609351825 6626476032 9223372036854775807  6616815856  6616815856 6626476032 9223372036854775807  6624284100  6624284100 6626476032 9223372036854775807  

std::string::capacity was seen to increase once std::string::length == std::string::capacity.

gdb bt after compiling for debug:

(gdb) bt  #0  __GI_raise (sig=sig@entry=6) at ../sysdeps/unix/sysv/linux/raise.c:51  #1  0x00007fd67037e921 in __GI_abort () at abort.c:79  #2  0x00007fd6709d3957 in ?? () from /usr/lib/x86_64-linux-gnu/libstdc++.so.6  #3  0x00007fd6709d9ae6 in ?? () from /usr/lib/x86_64-linux-gnu/libstdc++.so.6  #4  0x00007fd6709d9b21 in std::terminate() () from /usr/lib/x86_64-linux-gnu/libstdc++.so.6  #5  0x00007fd6709d9d54 in __cxa_throw () from /usr/lib/x86_64-linux-gnu/libstdc++.so.6  #6  0x00007fd6709da2dc in operator new(unsigned long) () from /usr/lib/x86_64-linux-gnu/libstdc++.so.6  #7  0x00007fd670a6bb8b in std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >::_M_mutate(unsigned long, unsigned long, char const*, unsigned long) () from /usr/lib/x86_64-linux-gnu/libstdc++.so.6  #8  0x00007fd670a6d133 in std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >::_M_append(char const*, unsigned long) () from /usr/lib/x86_64-linux-gnu/libstdc++.so.6  #9  0x000056104c176f3a in main (argc=1, argv=0x7ffc0af8b9a8) at /home/code/hello_world/createWorld.cpp:224  

Example line in text file being read:

713.258 235.418 ABCD1234567     2898  

Code:

int main(int argc, char **argv)  {      CreateWorld *newWorld = new CreateWorld();      lastModelsParser *lastModels = new lastModelsParser();            /*        Code here reads creates ifs for xml data,         then reads xml successfully into a ptree      */        vector<lastModelsParser::lastModel> _lastModels;        _lastModels = lastModels->getlastModels();        uint16_t lastModelsEntry = 0;      std::string newModelString;        for(auto i:_lastModels){          ptNewModel = newWorld->modelModifier(ptModel,               _lastModels.at(lastModelsEntry).pX,              _lastModels.at(lastModelsEntry).pY,              _lastModels.at(lastModelsEntry).name,               _lastModels.at(lastModelsEntry).height);            boost::property_tree::xml_parser::write_xml_element(modelOSS, ptNewModel.front().first, ptNewModel.back().second, 1, xml_settings);                    newModelString.append(modelOSS.str());              // CRASHES HERE              lastModelsEntry++;              }        // append to world.xml      boost::property_tree::write_xml(worldOSS, ptWorld, xml_settings);           // write xml data into OSStreams      boost::property_tree::write_xml(modelOSS, ptModel, xml_settings);           // write xml data into OSStreams         size_t worldPos = worldOSS.str().find("</world>");        std::string newWorldString = worldOSS.str().insert(worldPos,newModelString+"\n\t");        newWorldFile << newWorldString ;              delete(lastModels);      delete(newWorld);        return EXIT_SUCCESS;  }                                                                                                                                                                                                                             

Edit. Valgrind output

  1. valgrind --tool=massif --massif-out-file=memleak.txt ./createNewWorld
heap_tree=detailed  n2: 6636657886 (heap allocation functions) malloc/new/new[], --alloc-fns, etc.   n2: 6626476282 0x5160B89: std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >::_M_mutate(unsigned long, unsigned long, char const*, unsigned long) (in /usr/lib/x86_64-linux-gnu/libstdc++.so.6.0.25)    n2: 6626476282 0x5162131: std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >::_M_append(char const*, unsigned long) (in /usr/lib/x86_64-linux-gnu/libstdc++.so.6.0.25)     n0: 6626476033 0x149F38: main (in /home/code/hello_world/createNewWorld)     n0: 249 in 2 places, all below massif's threshold (1.00%)    n0: 0 in 2 places, all below massif's threshold (1.00%)   n0: 10181604 in 18 places, all below massif's threshold (1.00%)  
  1. valgrind --leak-check=full --show-leak-kinds=all --track-origins=yes --verbose --log-file=valgrind-out_1.txt ./createNewWorld
...  --4758-- memcheck GC: 1000 nodes, 0 survivors (0.0%)  --4758-- memcheck GC: 1000 nodes, 0 survivors (0.0%)  --4758-- memcheck GC: 1000 nodes, 0 survivors (0.0%)  --4758-- memcheck GC: 1000 nodes, 0 survivors (0.0%)  ==4758== Warning: set address range perms: large range [0xee015040, 0x1b37d5041) (undefined)  

How do I change the color for ng2-charts?

Posted: 14 Jul 2022 02:50 AM PDT

I have added ng2-charts to my project and display 2 charts - donut & barchart. both are displayed in gray since I added

    <base-chart class="chart"                  [colors]="chartColors"                  ...      </base-chart>   

to the component.template.html, and

public chartColors:Array<any> =[      {        fillColor:'rgba(225,10,24,0.2)',        strokeColor:'rgba(11,255,20,1)',        pointColor:'rgba(111,200,200,1)',        pointStrokeColor:'#fff',        pointHighlightFill:'#fff',        pointHighlightStroke:'rgba(200,100,10,0.8)'      }, ... (3x)  

to the component.ts.

Are any other package imports necessary to change the color or is the setup wrong?

Chromes html inspector shows the following html output rendered:

ng-reflect-colors="[object Object],[object Object],[object Object]"  

No comments:

Post a Comment