Monday, June 7, 2021

Recent Questions - Stack Overflow

Recent Questions - Stack Overflow

Recent Questions - Stack Overflow


why is it displaying incorrect no. of bindings supplied ? i have followed the code thoroughly

Posted: 07 Jun 2021 08:46 AM PDT

im trying to insert data into database the following is my code,

planet_data = [ ('Mercury' ,' 0.33010^24' , '2439.5', '5427', '3.7',' 4.3', '1407.6', '4222.6', '57.910^6', '46.010^6' , '69.810^6',' 88.0', '47.4', '7.0', '0.205', '0.034', '167', '0' ), ('Venus', '4.8710^24', '6052', '5243', '8.9', '10.4', '-5832.5','2802.0', '108.210^6', '107.510^6', '108.910^6', '224.7', '35.0', '3.4', '0.007', '177.4', '464', '0' ), ('Earth', '5.9710^24', '6378', '5514', '9.8', '11.2', '23.9', '24.0', '149.610^6', '147.110^6', '152.110^6', '365.2', '29.8', '0.0 ' , '0.017', '23.4', '15', '1' ), ('Moon', '0.07310^24', '1737.5', '3340', '1.6', '2.4', '655.7', '708.7', '0.38410^6', '0.36310^6', '0.40610^6', '27.3', '1.0' , '5.1', '0.055' , '6.7', '-20', '0' ), ('Mars', '0.64210^24', '3396', '3933', '3.7', '5.0', '24.6', '24.7', '227.910^6', '206.610^6', '249.210^6', '687.0', '24.1', '1.9', '0.094', '25.2', '-65', '2'), ('Jupiter', '189810^24', '71492', '1326', '23.1', '59.5', '9.9', '9.9', '778.610^6', '740.510^6', '816.610^6', '4331', '13.1', '1.3', '0.049', '3.1', '-110', '79'), ('Saturn', '56810^24', '60268', '687', '9.0', '35.5', '10.7', '10.7', '1433.510^6', '1352.610^6', '1514.510^6', '10747', '9.7', '2.5', '0.057', '26.7', '-140', '82'), ('Uranus', '86.810^24', '25559', '1271', '8.7', '21.3', '-17.2', '17.2', '2872.510^6', '2741.310^6', '3003.610^6', '30589', '6.8', '0.8', '0.046', '97.8', '-195', '27' ), ('Neptune', '10210^24', '24764', '1638', '11.0', '23.5', '16.1', '16.1', '4495.110^6', '4444.510^6' , '4545.710^6', '59800', '5.4', '1.8', '0.011', '28.3', '-200', '14' ), ('Pluto', '0.014610^24', '1185', '2095', '0.7', '1.3', '-153.3', '153.3', '5906.410^6', '4436.810^6', '7375.910^6', '90560', '4.7' ,'17.2', '0.244', '0.244', '122.5', '-225', '5') ] c.execute("INSERT INTO planetary_factsheet_metric VALUES ( ?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,? )", planet_data)

but im getting the following error:

File "e:\Database\appdata.py", line 17, in c.execute("INSERT INTO planetary_factsheet_metric VALUES ( ?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,? )", planet_data) sqlite3.ProgrammingError: Incorrect number of bindings supplied. The current statement uses 18, and there are 10 supplied.

Angular Request & response body into application insights

Posted: 07 Jun 2021 08:46 AM PDT

I have seen a lot of articles on Request & response body into application insights for C# API's. I was wondering if anyone had any examples of doing this in angular. I already have insights working in my SPA solution but am not sure how to specifically get HTTP Response & Requests to show from the Angular SPA into insights.

I would be looking for something similar to this ( https://www.azureblue.io/how-to-log-http-request-body-with-asp-net-core-application-insights/) but for angular.

How to get the exact size of a Redshift Cluster?

Posted: 07 Jun 2021 08:45 AM PDT

I used the below Query on a REDSHIFT CLUSTER

SELECT sum("size") from svv_table_info ;  

Output : 321,563,805 (in MB) [ this is the Disk Space consumed ]


And Using another query I got the MAX DISK CAPACITY of the REDSHIFT CLUSTER by below query

SELECT SUM(capacity) AS total   FROM   stv_partitions   WHERE  part_begin = 0 ;  

Output: 400,691,024 (in MB) [ max Disk capacity]


NOTE: svv_table_info and stv_partitions are both SYSTEM TABLES

But when I am validating the same by checking Disk Used by REDSHIFT CLUSTER on AWS REDSHIFT CONSOLE

It is showing

total size is 288TB in cluster - 100.00% (288.00 of 288 TB used)

Q1) Why is the REDSHIFT CONSOLE showing 288 TB as 100% where as the above query is showing 400,691,024 (in MB) as max capacity?

Q2) Why is it not the same on both ? what is the reason ? Is there any other way to get the exact size of Cluster/Table ?

update react state in all clients in a socket.io room

Posted: 07 Jun 2021 08:45 AM PDT

I am building an online multiplayer tic tac toe game using node, socket.io, and react,

in this, two users join a room using socket.io and I assign user1 symbol 'X' and user2 symbol 'O' and set react state currentPlayer to 'X' , when user's symbol is equal to the currentPlayer state user is allowed to make a move which emit "make-move" to server and server emit "made-move" to all clients in the room and in the client side function is called which show the user symbol in board and change the currentPlayer from "X" to "O" or vice versa.

the problem is currentState should update in both the clients and which is not happening.

server side code

io.on("connection", socket => {        //code is room name      socket.on("join-game", ({userName, code}) => {                  const user = userJoin(socket.id, userName, code) //push user to users array          socket.join(user.code)            socket.emit('joined', 'you have joined the room')            socket.broadcast          .to(user.code)          .emit('message',`${user.username} has joined the room`);            io.in(user.code).emit('roomUsers', {              users: getRoomUsers(user.code), // get users associated with room          });            socket.on('make-move', ({row, col}) => {              io.in(user.code).emit('made-move', ({row,col})) //sends to all clients in room          })      })  })  

client side code

const [currentPlayer, setCurrentPlayer] = useState('')  const [symbol, setSymbol] = useState('')  const [allState, setAllState] = useState(          [              [0,0,0],              [0,0,0],              [0,0,0]          ]      )    useEffect(() => {    socket.on('roomUsers', ({ users }) => {                   setCurrentPlayer('X')         if(users[0].id === socket.id) {             setSymbol('X')         }         if(users[1].id === socket.id) {             setSymbol('O')         }    });  }, [])    useEffect(() => {    socket.on('made-move', ({row, col}) => {       let thisAllState = allState.slice()       thisAllState[row][col] = currentPlayer === 'X' ? 1 : -1       setAllState(thisAllState)       let nextPlayer = currentPlayer === 'X' ? 'O' : 'X'       setCurrentPlayer(nextPlayer)    })    return () => socket.off('made-move')  }, [socket])    const handlePress = (row, col) => {      if(currentPlayer === symbol) {         socket.emit('make-move', ({row, col}))      }  }    const showIcon = (row, col) => {     let temp = allState[row][col]     switch (temp) {        case 1:           return 'X'        case -1:           return 'O'        default:            return      }  }    <div className="tileContainer">    <button className="tile" onClick={() => handlePress(0,0)}>       {showIcon(0,0)}    </button>    <button className="tile"  onClick={() => handlePress(0,1)}>      {showIcon(0,1)}    </button>    <button className="tile" onClick={() => handlePress(0,2)}>      {showIcon(0,2)}    </button>  </div>  

in this user1 which is 'X' make a move which shows in both the clients board and now the currentPlayer state should update from 'X' to 'O' which doesn't and user2 is not able to make a move.

thanks

Prisma one to many relation ship insert and update

Posted: 07 Jun 2021 08:45 AM PDT

Model

datasource db {    provider = "postgresql"    url      = env("DATABASE_URL")  }    generator client {    provider = "prisma-client-js"  }    generator dbml {    provider = "prisma-dbml-generator"  }    model Inventory {    id        Int       @id @default(autoincrement())    userId    String    @map("user_id")    type      String    @unique    currency  String    active    String    @default("Y")    createdAt DateTime  @default(now()) @map("created_at")    updatedAt DateTime? @default(now()) @map("updated_at")    createdBy String?   @map("created_by")    updatedBy String?   @map("updated_by")    products  Product[]      @@map("inventory")  }    model Category {    id             Int       @id @default(autoincrement())    categoryName   String    @unique@map("category_name")    categoryConfig String    @map("category_config")    categoryType   String    @default("SERVICE") @map("category_type")    createdAt      DateTime  @default(now()) @map("created_at")    updatedAt      DateTime  @default(now()) @map("updated_at")    createdBy      String?   @map("created_by")    updatedBy      String?   @map("updated_by")    products       Product[]  }    model Product {    id                           Int        @id @default(autoincrement())    categories                   Category?  @relation(fields: [categoryId], references: [id])    inventories                  Inventory? @relation(fields: [inventoryId], references: [id])    categoryId                   Int?       @map("category_id")    inventoryId                  Int?       @map("inventoryId")    productName                  String     @unique @map("product_name")    productDescription           String     @map("product_description")    productUnitPrice             Float      @map("product_unit_price")    productUnitOfMeasure         Int?       @map("product_unit_of_measure")    productInStock               Int?       @map("product_in_stock")    productStatus                Boolean    @default(true) @map("product_status")    productSize                  Float?     @map("product_size")    productColour                String?    @map("product_colour")    productModel                 String?    @map("product_model")    productSlug                  String?    @map("product_slug")    productAvatar                String?    @map("product_avatar")    productDeliveryCharges       Int?       @map("product_delivery_charges")    productDeliveryFrequencyRate Int        @map("product_delivery_frequency_rate")    productAverageRating         Int?       @map("product_average_rating")    createdAt                    DateTime?  @default(now()) @map("created_at")    updatedAt                    DateTime?  @map("updated_at")    createdBy                    String?    @map("created_by")    updatedBy                    String?    @map("updated_by")      @@map("products")  }  

InventoryDTO

 export class InventoryDTO {        @ApiProperty() @IsNotEmpty() readonly userId: string;        @ApiProperty() @IsNotEmpty() readonly type: string;        @ApiProperty() @IsNotEmpty() readonly currency: string;        @ApiProperty() readonly products: prisma.ProductCreateNestedManyWithoutInventoriesInput;      }  

Controller:

@Post('add')    async addInventory(      @Body() inventoryDTO: InventoryDTO,    ): Promise<InventoryEntity> {      let data = this.inventoryService.addInventory(inventoryDTO);      let result = await data.then((result) => {        return classToClass(new InventoryEntity(result));      });      return result;    }  

Service

async addInventory(data: Prisma.InventoryCreateInput): Promise<Inventory> {      let recordExists = this.getInventory({ type: data.type });      let result = await recordExists.then((result) => {        return result;      });        if (result == null) {        return this.prismaService.inventory.create({          data,          include: {            products: true,          },        });      } else {        this.logger.error(ERROR_INVENTORYTYPE_MUST_BE_UNIQUE);        throw new HttpException(          ERROR_INVENTORYTYPE_MUST_BE_UNIQUE,          HttpStatus.BAD_REQUEST,        );      }    }  

I have attached all my code, When I try send data in inventyDTO from UI with multiple products. Like below

{  ...InventoryData,  ...products : [{           }]  }  

I would like to insert records in both inventory and products table thru addInventory methods. Some one please help on this request.??

FYI,Prisma generate following model,

Prisma.InventoryCreateInput      export type InventoryCreateInput = {      type: string      currency: string      active?: string      userId: string      createdAt?: Date | string      updatedAt?: Date | string | null      createdBy?: string | null      updatedBy?: string | null      products?: ProductCreateNestedManyWithoutInventoriesInput    }  

How to fix KeyError

Posted: 07 Jun 2021 08:45 AM PDT

Im trying to code Minesweeper on python for a school. I watched a youtube video about that and copied it a little bit. But now im stuck because of this error:

File "e:\Schule\Spiele\Minesweeper\Minesweeper.py", line 63, in draw image = self.images["norm_zelle.gif"] KeyError: 'norm_zelle.gif'

I tried to change image = self.images["norm_zelle.gif"] to image = self.images.get("norm_zelle.gif") but that causes another error with a None Thing

import pygame  import os        class Settings(object):      def __init__(self):          self.size = (9,9)          self.screenSize = (800, 800)        class Board(object):      def __init__(self):          self.settings = Settings()          self.setBoard()        def setBoard(self):          self.board = []                    for row in range(self.settings.size[0]):              row= []                for col in range(self.settings.size[1]):                  piece = None                  row.append(piece)              self.board.append(row)        def getSize(self):          return self.settings.size      class Game(object):      def __init__(self) :          self.settings = Settings()          self.board = Board()          self.pieceSize = self.settings.screenSize[0] // self.board.getSize()[1], self.settings.screenSize[1] // self.board.getSize()[0]          self.loadImages()            def run(self):          pygame.init()          self.screen = pygame.display.set_mode(self.settings.screenSize)            running = True            while running:              for event in pygame.event.get():                  if (event.type == pygame.QUIT):                      running = False              self.draw()                pygame.display.flip()          pygame.quit  

This is the function that causes the error but i dont know how to fix this. It should create a grid with that images

    def draw(self):          pass          topLeft = (0,0)            for i in range(self.board.getSize()[0]):              for n in range(self.board.getSize()[1]):                  image =  self.images["norm_zelle.gif"]                  self.screen.blit(image , topLeft)                  topLeft = topLeft[0] + self.pieceSize[0] , topLeft[1]              topLeft = 0, topLeft[1] + self.pieceSize[1]                      def loadImages(self):          self.images = {}          file_path = os.path.dirname(os.path.abspath(__file__))          image_path = os.path.join(file_path, "images")          sound_path = os.path.join(file_path, "sounds")                  if __name__ == '__main__':      os.environ['SDL_VIDEO_WINDOWS_POS'] = "50, 1100"      pygame.init()      game = Game()      game.run()      pygame.quit()  

How does making an Azure Function asynchronous affects the caller

Posted: 07 Jun 2021 08:45 AM PDT

When Azure Function is declared to be async, how does it affect the client that calls it?

Take an example of an Angular HTTP client that calls the Azure Function. What is the difference if the Angular app calls asynchronous vs synchronous function? Wouldn't the HTTP client object still wait for the response from the function in either case?

How to write() to a file byte by byte or in chunks in C

Posted: 07 Jun 2021 08:45 AM PDT

I'm trying to write byte by byte, 2 bytes, 4 bytes etc in chunks to a file. I currently have this code however am stuck.

#include <unistd.h>  #include <stdio.h>  #include <stdlib.h>  #include<stdio.h>  #include<fcntl.h>  #include<errno.h>      int main(int argc, char* argv[]){        char buf[1];        //creating output file      int outfile = open(argv[1], O_CREAT | O_APPEND | O_RDWR, 0666);        int infile = open(argv[2], O_RDONLY);        fread = read(infile, buf, 1);      printf("%s\n", buf);      write(outfile);      close(infile);      close(outfile)    }  

4K Clip Editing with moviepy

Posted: 07 Jun 2021 08:45 AM PDT

I hope to zoom a 4k video. The reason is simply I don't have a high resolution monitor.

from moviepy.editor import VideoFileClip  import moviepy.video.fx.all as vfx  clip = VideoFileClip(file_name)  resized_clip = clip .crop(clip, x1=0, y1=0, x2=1920, y2=1080)  

It is the code I used to cut off the upper-right of 4k clip. This type of size modifying was worked for other sizes of video, but not worked for 4k. How can I fix it?

Cannot build project in android-studio

Posted: 07 Jun 2021 08:45 AM PDT

When trying to build the projects, got this err:

2021-06-07T17:42:28.929+0200 [DEBUG] [org.gradle.internal.operations.DefaultBuildOperationRunner] Completing Build operation 'Snapshot outputs after executing task ':app:processDebugMainManifest''  2021-06-07T17:42:28.518+0200 [LIFECYCLE] [class org.gradle.internal.buildevents.TaskExecutionLogger]   Execution failed for task ':app:mergeDebugResources'.  > A failure occurred while executing com.android.build.gradle.internal.res.ResourceCompilerRunnable  > Resource compilation failed. Check logs for details.    * Try:  Run with --stacktrace option to get the stack trace.  Run with --scan to get full insights.  

Find the value of a column over a set of columns in a data frame in R

Posted: 07 Jun 2021 08:45 AM PDT

I'm struggling with the way to find the value of a column across other columns of a data.frame. I'd be thankful if anyone could help me. These are a simplified form of my data:

library(data.table)    df<-data.table(personid<-c(101, 102, 103, 104, 105, 201, 202, 203, 301, 302, 401),         hh_id<-c(1, 1, 1, 1, 1, 2, 2, 2, 3, 3, 4),         fatherid<-c(NA, NA, 101, 101, 101, NA, NA, 201, NA, NA, NA),         fatherid_1<-c(NA,101, 101, 101, NA, NA, 201, NA, NA, NA, NA),         fatherid_2<-c(101, 101, 101, NA, NA, 201, NA, NA, NA, NA, NA),         fatherid_3<-c(101, 101, NA, NA, NA, NA, NA, NA, NA, NA, NA),         fatherid_4<-c(101, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA),         fatherid_5<-c(NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA))  

(the real one is 185000 rows and has up to 17 variables such as "fatherid_1, fatherid_2... fatherid_17")

What I'm trying to do is to create a variable that checks whether the value of variable "personid" of a given row is the same as any of the values of variables "fatherid_1" to "fatherid_5" in the same row. For the given data, the outcome should be:

df$result<-c(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0)   

but I need something to do it automatically, over 17 columns such as "fatherid_1", and a lot of rows

In case you want to understand the sense of my calculations, I'm trying to build household grids without using only information in the same row

Thank you very much in advance!

C# tally values in a list of JSON records and write to a Dictionary

Posted: 07 Jun 2021 08:45 AM PDT

I'm reading a JSON file with the following simple structure and I need to tally the 'Ord Qty' for each record with the same 'Ord No' field, and store the total in another lookup list with a single record for every 'Ord No'. The input file looks like

[    {      "Ord No": "41035",      "Ord Date": "05/06/2021",      "Stock No": "TW2807",      "Ord Qty": "3"    },    {      "Ord No": "41035",      "Ord Date": "05/06/2021",      "Stock No": "TW2809",      "Ord Qty": "1"    },    {      "Ord No": "41035",      "Ord Date": "05/06/2021",      "Stock No": "TW280S",      "Ord Qty": "3"    },    {      "Ord No": "41034",      "Ord Date": "05/06/2021",      "Stock No": "TW290L",      "Ord Qty": "17"    },    {      "Ord No": "41034",      "Ord Date": "05/06/2021",      "Stock No": "TW2830S",      "Ord Qty": "2"    },    {      "Ord No": "41034",      "Ord Date": "05/06/2021",      "Stock No": "CCDW12",      "Ord Qty": "15"    },    {      "Ord No": "41034",      "Ord Date": "05/06/2021",      "Stock No": "APXCSS",      "Ord Qty": "12"    }  ]  

I need to transform the data into another structure, and to be able to reference it with a key pair i.e.

public class OrderTally  {      public string OrdNo { get; set; }      public string TotalOrdQty { get; set; }  }  

...for the structure, and I'm looking to end up with this, which I will use as a look up.

[    {      "Ord No": "41035",      "Total Ord Qty": "7"    },    {      "Ord No": "41034",      "Total Ord Qty": "29"    }  ]  

I originally I thought I needed to be using System.Collections.Dictionary class to be doing this, but the code I've produced so far hasn't even gotten me close to where I'm successfully tallying the quantity for the new record.

PostgreSQL UPSERT (INSERT ... ON CONFLICT UPDATE) fails

Posted: 07 Jun 2021 08:46 AM PDT

I have a row in my postgresql database that I want to update.

=> SELECT * FROM reading_group_reading_session  WHERE group_id = 439     AND group_type = 'focus_group'     AND reg_user_id = 28056     AND device_id = ''    AND reading_date = '2021-06-03';    id   | group_id | group_type  | reg_user_id | device_id | reading_date | seconds_reading | num_syncs   -------+----------+-------------+-------------+-----------+--------------+-----------------+-----------   35532 |      439 | focus_group |       28056 |           | 2021-06-03   |            3310 |         4  (1 row)    Time: 1.820 ms  =>     

My code generates this SQL statement to insert else update the one field that's changed:

=> INSERT INTO  [more] - >   INSERT INTO reading_group_reading_session    (group_id,group_type,reg_user_id,device_id,reading_date,seconds_reading)  VALUES    (439,'focus_group',28056,'','2021-06-03',3320)  ON CONFLICT    (group_id, group_type, reg_user_id, device_id, reading_date)  DO UPDATE SET      seconds_reading = 3320;  ERROR:  23502: null value in column "num_syncs" violates not-null constraint  DETAIL:  Failing row contains (115399, 439, focus_group, 28056, , 2021-06-03, 3320, null).  SCHEMA NAME:  public  TABLE NAME:  reading_group_reading_session  COLUMN NAME:  num_syncs  LOCATION:  ExecConstraints, execMain.c:1700  Time: 3.017 ms  =>   

What I don't understand is that I can select that one row and it is present with a non-NULL num_syncs. But the UPSERT is failing because it doesn't (re)set num_syncs (value 4 unchanged).

Anyone see what I'm missing?

Fwiw, the table definition is this:

                                  Table "public.reading_group_reading_session"       Column      |      Type       |                                 Modifiers                                    -----------------+-----------------+----------------------------------------------------------------------------   id              | integer         | not null default nextval('reading_group_reading_session_id_seq'::regclass)   group_id        | integer         | not null   group_type      | group_type_name |    reg_user_id     | integer         | not null   device_id       | text            |    reading_date    | date            |    seconds_reading | integer         | not null   num_syncs       | integer         | not null  Indexes:      "reading_group_reading_session_pkey" PRIMARY KEY, btree (id)      "reading_group_reading_session_idx_dgid" UNIQUE, btree (group_id, group_type, reg_user_id, device_id, reading_date)  Check constraints:      "reading_group_reading_session_group_id_check" CHECK (group_id > 0)      "reading_group_reading_session_minutes_reading_check" CHECK (seconds_reading >= 0)      "reading_group_reading_session_num_syncs_check" CHECK (num_syncs >= 0)      "reading_group_reading_session_reg_user_id_check" CHECK (reg_user_id >= 0)    =>    

Swashbuckle.AspNetCore + Blazor - Dynamically Add/Remove custom .css file at runtime

Posted: 07 Jun 2021 08:45 AM PDT

I have Blazor Webassembly ASP.NET Core hosted and I installed Swashbuckle.AspNetCore to display endpoints that my Blazor app has (/swagger endpoint).
My Startup.Configure looks like this (only swagger part):

            app.UseSwagger();              app.UseSwaggerUI(c =>              {                  foreach (var description in provider.ApiVersionDescriptions)                  {                      c.SwaggerEndpoint($"{description.GroupName}/swagger.json", $"v{description.GroupName.ToUpperInvariant()}");                  }                    c.InjectStylesheet("/css/swaggerDark.css");              });  

As you can see, I inject custom .css file which works.

In my Blazor app, I inject swagger so my page looks like this (.razor page):

<iframe src="swagger"/>  

Again, it works correctly, swagger documentation is displayed and it has dark theme.

I have noticed (to no suprise) that this iframe has a link to this .css file:

<link href="/css/swaggerDark.css" rel="stylesheet" media="screen" type="text/css">  

Removing this link brings the default swagger look (light theme).

The user of my app can choose which theme he wants (light/dark) of the whole application. My question is, how do I dynamically inject/remove (or maybe enable/disable) this .css file so depending on which theme the user chooses, the swagger will either display default (light) or dark theme (using that .css file)?

I couldn't find any relevant info on this issue so I decided to create this question. I appreciate any help. Thank you.

Replace part of text

Posted: 07 Jun 2021 08:45 AM PDT

I have the following text:

Send to <a class="tipo9" id="1">Example Mark</a> and <a class="tipo0" id="3">Testing James</a> a new Document  

And would like to obtain the following code:

Send to <per>1</per> and <per>3</per> a new Document  

The number between the tags is the id number.

I have found a very complicated solution like:

function convert(f) {      var str=f;      str=str.replaceAll('<a class="', '[per]');      str=str.replaceAll('/a>', '[/per]');      str=str.replaceAll(/tipo\d/g, '');      str=str.replaceAll(/['"]+/g, '');      str=str.replaceAll('"', '');      str=str.replaceAll(' id=', '');      str=str.replaceAll(/\s*\>.*?\<\s*/g, "")      str=str.replaceAll('[per]', '<per>');      str=str.replaceAll('[/per]', '</per>');      str=str.trim();      document.getElementById('testoHTML').value=str;  }  

but it gives different problems. I know that it should exist another solution with regex but I was not able to obtain a working result.

Hope to find some good solution :)

Wrong timezone Angular / Node.js

Posted: 07 Jun 2021 08:46 AM PDT

I'm using node.js with the mssql 6.3.1 package, and I'm getting a little confused with the returned results. In node.js I use a function which contains this query:

SELECT getdate() AS DateOfRequest FROM logRequests  

The HTTP response returns (when requesting at 12:56):

{      DateOfRequest: 2021-06-07T12:56:50.497Z  }  

The issue is that using this fields ins Angular, with the datepipe, it is getting converted to string correctly but it adds another hour, due to the timezone. I found that if we remove the Z from the string before using the pipe it works... but is there another option? To make the pipe ignore the Z?

get selected multiple rows of checkbox by inserting no of rows in input box

Posted: 07 Jun 2021 08:45 AM PDT

enter image description here

How can i get selected checkbox of the datatable by inputing numbers

I'm trying to code a bootstrap data table which able to select check box of the rows by inserting no of rows in the input box

I dont have any idea about how to do it.

e.g: I typed number three in the input box then automatically checkbox table of two rows will get selected at [the beginning -> no problem]

<!DOCTYPE html>  <html><head>      <link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css">      <link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/bootstrap-table/1.10.1/bootstrap-table.min.css">          <script src="//code.jquery.com/jquery.js"></script>          <script src="//maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script>              <script src="//cdnjs.cloudflare.com/ajax/libs/bootstrap-table/1.10.1/bootstrap-table.min.js"></script>      </head>  <body>  <div class="container text-center">  <label for="fname">insert number for select multiple check box</label>  <input type="number" id="selectcheckbox" name="selectcheckbox">  <table data-toggle="table"          data-classes="table table-hover table-condensed"         data-row-style="rowColors"         data-striped="true"         data-sort-name="Quality"         data-sort-order="desc"         data-pagination="true"         data-click-to-select="true"         >      <thead>      <tr>          <th data-field="state" data-checkbox="true"></th>          <th class="col-xs-1" data-field="Product_Name" data-sortable="true">Product Name</th>          <th class="col-xs-1" data-field="Quality" data-sortable="true">Quality</th>          <th class="col-xs-6" data-field="Quantity" >Quantity</th>      </tr>      </thead>      <tbody>     <tr id="tr-id-2" class="tr-class-2">          <td></td>          <td>Wheat</td>          <td>Good</td>          <td>200 Bags</td>      </tr>      <tr id="tr-id-2" class="tr-class-2">          <td></td>          <td>Rice</td>          <td>Good</td>          <td>100 Bags</td>      </tr>      <tr id="tr-id-2" class="tr-class-2">          <td></td>          <td>Rice</td>          <td>Good</td>          <td>100 Bags</td>      </tr>      <tr id="tr-id-2" class="tr-class-2">          <td></td>          <td>Sugar</td>          <td>Prime</td>          <td>200 Bags</td>      </tr>                  <tr id="tr-id-2" class="tr-class-2">          <td></td>          <td>Maze</td>          <td>Fine</td>          <td>10 Packs</td>      </tr>                  <tr id="tr-id-2" class="tr-class-2">          <td></td>          <td>Sugar</td>          <td>Prime</td>          <td>200 Bags</td>      </tr>       <tr id="tr-id-2" class="tr-class-2">          <td></td>          <td>Sugar</td>          <td>Prime</td>          <td>200 Bags</td>      </tr>       <tr id="tr-id-2" class="tr-class-2">          <td>Sugar</td>          <td>Prime</td>          <td>200 Bags</td>      </tr>       <tr id="tr-id-2" class="tr-class-2">          <td></td>          <td>Sugar</td>          <td>Prime</td>          <td>200 Bags</td>      </tr>       <tr id="tr-id-2" class="tr-class-2">          <td></td>          <td>Sugar</td>          <td>Prime</td>          <td>200 Bags</td>      </tr>       <tr id="tr-id-2" class="tr-class-2">          <td></td>          <td>Sugar</td>          <td>Prime</td>          <td>200 Bags</td>      </tr>              </tbody>      </table>  </div>    <script>  function queryParams() {      return {          type: 'owner',          sort: 'updated',          direction: 'desc',          per_page: 100,          page: 1      };  }  function rowColors(row, index) {      var classes = ['active', 'success', 'info', 'warning', 'danger'];            if (index % 2 === 0 && index / 2 < classes.length) {          return {              classes: classes[index / 2]          };      }      return {};  }  </script>    </body>  </html>

Generate random consecutive dates with variable length in Python

Posted: 07 Jun 2021 08:46 AM PDT

I'd like to generate random consecutive dates in a given time frame. I've seen some approaches for generating random dates, and I have one attempt below in a function, but I think there is a more compact way to do it. Any help is appreciated!

The function does a few things:

  1. Creates consecutive dates from a random starting point in a date window
  2. The variable length of those consecutive dates is between 2-5 days
  3. the function ensures that the consecutive dates are chosen between the given beginning and end date.

The code is below. Is there a more compact way to generate this function?

def illness(start_date,end_date):    funct_ill_list=[]   #list that will store all dates       #randomly choosing first date    diff = end_date - start_date    random_number = random.randint(0,diff.days-5)             temp = start_date + datetime.timedelta(random_number)    #temp = 1 march + "random_number" days     funct_ill_list.append(temp)                              #adding the first date to list          #adding next 'n' (2-5) consecutive dates after our last element in list(most recently added date in list)    # ----------------FOR EXAMPLE - funct_ill_list = ['4 march','5 march','6 march']; random_number=3       while funct_ill_list[-1]<=end_date:                              #stop when last element in list (most recently added date in list) exceeds end_date        random_number = random.randint(2,5)                           #for 2-5 random days (consecutive) - get a random integer between 2 to 5        last = funct_ill_list[-1]+datetime.timedelta(random_number)   #'last' variable stores maximum possible date we will have with chosen random_number        if last>end_date:             funct_ill_list.pop()          break        else:                                          #else add next 'random_number' dates to list          ref_date = funct_ill_list[-1]                #last element of list          for i in range(1,random_number):             #'i' takes values from 1 to (random_number-1).            temp = ref_date + datetime.timedelta(i)    #each time add 'i' days to ref_date to get new date 'temp'            funct_ill_list.append(temp)                #add this new date to list.                #for next random date        # --------------FOR EXAMPLE - funct_ill_list = ['4 march','5 march','6 march','25 march']        diff = end_date - funct_ill_list[-1]                        #get no. of days remaining b/w end_date and last element added to list        if diff.days>=2:                                            #if diff.days=0 or 1, ie. last element in list is either end_date or end_date-1,                                                                    #No point of adding more dates for next round (since 2-5 consecutive days won't be possible), else add.                   random_number = random.randint(2,diff.days)                   #randomly choose a number          temp = funct_ill_list[-1] + datetime.timedelta(random_number) #adding "random_number" days to last element of list          funct_ill_list.append(temp)                                   #adding it to list    return funct_ill_list        ill_start_date = datetime.date(2020, 2, 1)  ill_end_date = datetime.date(2020, 4, 30)  month_time_frame = [3,5] #static two months time frame (Looks at matching dates in March and May months)  

how to use PHP:strval() in a correct way [closed]

Posted: 07 Jun 2021 08:45 AM PDT

Good evening, I am a beginner, can someone help me how to use strval() in a correct way, I am trying to fetch a value from 'xyz_position' field from 'department' table, and use only the first 2 digit number as an id of a selected option.

This is what I am trying to achieve for example:

<?php  $xyz_position=219;  $con=strval($xyz_position);  $result=substr($con, 0, 2);  echo $result;  ?>  //output: 21  

This is my current code:

<?php       $sql="SELECT Department_Name, xyz_position FROM department";      $query=$dbh->prepare($sql);      $query->execute();      $results=$query->fetchAll(PDO::FETCH_OBJ);      $xyz_pos='$results["xyz_position"]';      echo "<script>alert('$xyz_pos');</script>";      $code=strval($xyz_pos);      $ress=substr($code, 0, 2);      $cnt=1;      if($query->rowCount() > 0){         foreach($results as $result){?>              <option id="<?php echo htmlentities($ress);?>" value="<?php echo htmlentities($result->Department_Name);?>"><?php echo htmlentities($result->Department_Name);?></option>  <?php }} ?>  

I tried to echo the value of my '$xyz_pos' but the are no results, can someone tell me how to use the str() in a proper way or tell me what is the correct syntax for it.

DispatchQueue alternative to better match Label Changes to Animation?

Posted: 07 Jun 2021 08:45 AM PDT

This is a GIF illustrating what it's supposed to do, I think the animation is perfect except that it de-synced the longer it went on and I could never fully eliminate it as mentioned.

here is a video of what the animation was, which was fine but it started to desync the longer it went on

What de-synced was the label changes from the animation

I WAS using dispatchQueue but I was informed in a post that it isn't the best way to do this for timing reasons. So my question is what's the best way to accomplish this?

//                DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 12.5) { [self] in  //                                self.mainFocusLabel.text = self.foclabel2Text  //                                manifestationImg.sd_setImage(with: URL(string: imglabel2URL))  //  //                DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 12.5) { [self] in  //                                self.mainFocusLabel.text = self.foclabel3Text  //                                manifestationImg.sd_setImage(with: URL(string: imglabel3URL))  //  //                DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 12.5) { [self] in  //                                self.mainFocusLabel.text = self.foclabel4Text  //                                manifestationImg.sd_setImage(with: URL(string: imglabel4URL))  //  //                DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 12.5) { [self] in  //                                self.mainFocusLabel.text = self.foclabel5Text  //                                manifestationImg.sd_setImage(with: URL(string: imglabel5URL))  

I have some animated loops for the size changing and the opacity changing. This is what I'm trying to match the label changes up with.

self.FocusStack.alpha = 0  //              //AniamtionGlowLOOP              UIView.animate(withDuration: 7, delay: 0, options: [.autoreverse, .repeat], animations: { self.mainFocusLabel.layer.shadowRadius = 5.0; self.mainFocusLabel.layer.shadowOpacity = 1.0 })                //AnimationBreathSizeLOOP              UIView.animateKeyframes(withDuration: 7, delay: 0, options: [ .autoreverse, .repeat], animations: {                  UIView.addKeyframe(withRelativeStartTime: 0.0, relativeDuration: 1.0) { self.mainFocusLabel.transform = CGAffineTransform(scaleX: 1.3, y: 1.3) }              })                            //AnimationOpacityLOOP              UIView.animateKeyframes(withDuration: 7, delay: 0, options: [ .autoreverse, .repeat], animations: {                  UIView.addKeyframe(withRelativeStartTime: 0.0, relativeDuration: 0.15) { self.FocusStack.alpha = 1 }              })      }  

PS. I've tried using keyframes but it doesn't seem to change the labels, for some reason this code only shows the second keyframe?

 UIView.animateKeyframes(withDuration: 28, delay: 0, options: [ .calculationModePaced], animations: {                                    UIView.addKeyframe(withRelativeStartTime: 0.0, relativeDuration: 0.5) {                      self.mainFocusLabel.text = self.foclabel7Text                      self.manifestationImg.sd_setImage(with: URL(string: ""))                  }                                    UIView.addKeyframe(withRelativeStartTime: 0.5, relativeDuration: 0.5) {                      self.mainFocusLabel.text = self.foclabel1Text                      self.manifestationImg.sd_setImage(with: URL(string: self.imglabel1URL))                  }                })            

Uncaught TypeError: jQuery.easing is undefined [closed]

Posted: 07 Jun 2021 08:45 AM PDT

I get Uncaught TypeError: jQuery.easing is undefined error in my wordpress site. it occures when I want to post a comment and doesn't show the button!

function(t, e) {      jQuery.easing.jswing = jQuery.easing.swing, jQuery.extend(jQuery.easing, {                  def: "easeOutQuad",                  swing: function(t, e, n, r, i) {                      return jQuery.easing[jQuery.easing.def](t, e, n, r, i)                  },  

my website url

ERROR - "export 'ɵ9' (imported as 'i64') was not found

Posted: 07 Jun 2021 08:45 AM PDT

ERROR in ./src/app/admin/admin.module.ngfactory.js 117:13330-13336 "export 'ɵ9' (imported as 'i64') was not found in './admin-routing.module'

This is my admin-routing.module file

import { NgModule } from '@angular/core';  import { Routes, RouterModule } from '@angular/router';    // Components Imports  import { AdminComponent } from './admin.component';  import { LoginComponent } from './components/login/login.component';  import { DashboardComponent } from './components/dashboard/dashboard.component';  import { PageNotFoundComponent } from './components/page-not-found/page-not-found.component';  import { AdminUsersComponent } from './components/admin-users/admin-users.component';  import { LanguageComponent } from './components/language/language.component';  import { EditLanguageComponent } from './components/language/edit-language/edit-language.component';  import { AddLanguageComponent } from './components/language/add-language/add-language.component';  import { LanguageKeyPairComponent } from './components/language-key-pair/language-key-pair.component';  import { LanguageKeyPairContentComponent } from './components/language-key-pair/language-key-pair-content/language-key-pair-content.component';  import { LanguageKeyPairEditComponent } from './components/language-key-pair/language-key-pair-content/language-key-pair-edit/language-key-pair-edit.component';  import { LanguageKeyPairAddComponent } from './components/language-key-pair/language-key-pair-add/language-key-pair-add.component';  import { RatingQuestionComponent } from './components/rating-question/rating-question.component';  import { AddAdminUserComponent } from './components/admin-users/components/add-admin-user/add-admin-user.component';  import { EditAdminUserComponent } from './components/admin-users/components/edit-admin-user/edit-admin-user.component';  import { PushNotificationComponent } from './components/push-notification/push-notification.component';  import { CancelationPolicyComponent } from './components/cancelation-policy/cancelation-policy.component';  import { PrivacyPolicyComponent } from './components/privacy-policy/privacy-policy.component';  import { AboutComponent } from './components/about/about.component';  // Guard Imports  import { AuthGuard } from './guards/auth.guard';  import { from } from 'rxjs';  import { ProvidersAgreementComponent } from './components/providers-agreement/providers-agreement.component';  import { ProviderOnboardingSMSComponent } from './components/provider-onboarding-sms/provider-onboarding-sms.component';    const routes: Routes = [    { path: '', redirectTo: 'dashboard', pathMatch: 'full' },      { path: 'login', component: LoginComponent },    {      path: '',      component: AdminComponent,      children: [        { path: 'dashboard', component: DashboardComponent },        { path: 'client', loadChildren: () => import('./components/client/client.module').then(m => m.ClientModule) },        { path: 'user', loadChildren: () => import('./components/user/user.module').then(m => m.UserModule) },        { path: 'service-provider', loadChildren: () => import('./components/service-provider/service-provider.module').then(m => m.ServiceProviderModule) },        { path: 'pricing', loadChildren: () => import('./components/pricing/pricing.module').then(m => m.PricingModule) },        { path: 'admin-users', component: AdminUsersComponent },        { path: 'admin-users/edit/:id', component: EditAdminUserComponent },        { path: 'admin-users/add', component: AddAdminUserComponent },        { path: 'content', loadChildren: () => import('./components/content/content.module').then(m => m.ContentModule) },        { path: 'appointment', loadChildren: () => import('./components/appointment/appointment.module').then(m => m.AppointmentModule) },        { path: 'treatment', loadChildren: () => import('./components/treatment/treatment.module').then(m => m.TreatmentModule) },        { path: 'pets', loadChildren: () => import('./components/pets/pets.module').then(m => m.PetsModule) },        { path: 'faq', loadChildren: () => import('./components/faq/faq.module').then(m => m.FaqModule) },        { path: 'contact-us', loadChildren: () => import('./components/contact-us/contact-us.module').then(m => m.ContactUsModule) },        { path: 'rating-questions', component: RatingQuestionComponent },        { path: 'push-notifications', component: PushNotificationComponent },        { path: 'languages', component: LanguageComponent },        { path: 'languages/edit/:id', component: EditLanguageComponent },        { path: 'languages/add', component: AddLanguageComponent },        { path: 'languages-key', component: LanguageKeyPairComponent },        { path: 'languages-key/add', component: LanguageKeyPairAddComponent },        { path: 'languages-key/:id', component: LanguageKeyPairContentComponent },        { path: 'languages-key/edit/:id', component: LanguageKeyPairEditComponent },        { path: 'cancelation-policy', component: CancelationPolicyComponent },        { path: 'privacy-policy', component: PrivacyPolicyComponent },        { path: 'about', component: AboutComponent },        { path: 'providers-agreement', component: ProvidersAgreementComponent },        { path: 'providers-onboarding-sms', component: ProviderOnboardingSMSComponent }          ],      canActivate: [AuthGuard]    },    { path: '**', component: PageNotFoundComponent }  ];    @NgModule({    imports: [RouterModule.forChild(routes)],    exports: [RouterModule]  })  export class AdminRoutingModule { }    export const AdminRoutesComponent = [    DashboardComponent,    AdminUsersComponent,    PageNotFoundComponent,    LanguageComponent,    EditLanguageComponent,    AddLanguageComponent,    LanguageKeyPairComponent,    LanguageKeyPairContentComponent,    LanguageKeyPairEditComponent,    LanguageKeyPairAddComponent,    RatingQuestionComponent,    AddAdminUserComponent,    EditAdminUserComponent,    PushNotificationComponent,  ];  

This is admin.module file

import { NgModule } from '@angular/core';  import { CommonModule } from '@angular/common';    import { ReactiveFormsModule } from '@angular/forms';  import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http';  import { CKEditorModule } from '@ckeditor/ckeditor5-angular';    import { AdminRoutingModule } from './admin-routing.module';  import { AdminComponent } from './admin.component';  import { LoginComponent } from './components/login/login.component';    // NgRx Imports  import { StoreModule } from '@ngrx/store';  import { StoreDevtoolsModule } from '@ngrx/store-devtools';  import { EffectsModule } from '@ngrx/effects';  import { rootReducer } from './store/rootReducer';  import { rootEffect } from './store/rootEffects';    // Theme Imports  import {SharedModule} from './shared/shared.module';  import {    NgbPopoverModule,    NgbProgressbarModule,    NgbTabsetModule,    NgbButtonsModule,    NgbDropdownModule,    NgbTooltipModule  } from '@ng-bootstrap/ng-bootstrap';    import { NavigationItem } from './layout/navigation/navigation';    // Guards and Services  import { AuthService } from './services/auth.service';  import { TokenInterceptorService } from './services/token-interceptor.service';  import { LanguageService } from './services/language.service';  import { LanguageKeyPairService } from './services/language-key-pair.service';  import { AppointmentService } from './services/appointment.service';  import { ClientService } from './services/client.service';  import { TreatmentService } from './services/treatment.service';  import { PetService } from './services/pet.service';  import { FaqService } from './services/faq.service';  import { ServiceProviderService } from './services/service-provider.service';  import { ContentService } from './services/content.service';    import { AuthGuard } from './guards/auth.guard';    // Components Imports  import { AdminRoutesComponent } from './admin-routing.module';    import { NavigationComponent } from './layout/navigation/navigation.component';  import { NavContentComponent } from './layout/navigation/nav-content/nav-content.component';  import { NavGroupComponent } from './layout/navigation/nav-content/nav-group/nav-group.component';  import { NavCollapseComponent } from './layout/navigation/nav-content/nav-collapse/nav-collapse.component';  import { NavItemComponent } from './layout/navigation/nav-content/nav-item/nav-item.component';  import { NavBarComponent } from './layout/nav-bar/nav-bar.component';  import { NavRightComponent } from './layout/nav-bar/nav-right/nav-right.component';  import { ConfigurationComponent } from './layout/configuration/configuration.component';      import { ToggleFullScreenDirective } from './shared/full-screen/toggle-full-screen';  // Enviornment Import  import { environment } from '../../environments/environment';  import { UniquDataPipe } from './pipes/uniqu-data.pipe';  import { CancelationPolicyComponent } from './components/cancelation-policy/cancelation-policy.component';  import { PrivacyPolicyComponent } from './components/privacy-policy/privacy-policy.component';  import { AngularEditorModule } from '@kolkov/angular-editor';  import { AboutComponent } from './components/about/about.component';  import { ProvidersAgreementComponent } from './components/providers-agreement/providers-agreement.component';  import { ProviderOnboardingSMSComponent } from './components/provider-onboarding-sms/provider-onboarding-sms.component';  import {UserModule} from "./components/user/user.module";        @NgModule({    declarations: [      AdminComponent,      LoginComponent,      AdminRoutesComponent,        ConfigurationComponent,      NavBarComponent,      NavRightComponent,      NavigationComponent,      NavContentComponent,      NavCollapseComponent,      NavGroupComponent,      NavItemComponent,      ToggleFullScreenDirective,      UniquDataPipe,      CancelationPolicyComponent,      PrivacyPolicyComponent,      AboutComponent,      ProvidersAgreementComponent,      ProviderOnboardingSMSComponent    ],    imports: [      CommonModule,      AdminRoutingModule,      ReactiveFormsModule,      HttpClientModule,      AngularEditorModule,      CKEditorModule,      // Theme Imports      SharedModule,      NgbProgressbarModule,      NgbPopoverModule,      NgbTabsetModule,      NgbButtonsModule,      NgbDropdownModule,      UserModule,      NgbTooltipModule,      StoreModule.forRoot(rootReducer),      StoreDevtoolsModule.instrument({        maxAge: 25, // Retains last 25 states        logOnly: environment.production, // Restrict extension to log-only mode      }),      EffectsModule.forRoot(rootEffect)    ],    providers: [      AuthService,      LanguageService,      LanguageKeyPairService,      ClientService,      AppointmentService,      TreatmentService,      PetService,      FaqService,      ServiceProviderService,      ContentService,      AuthGuard,      {        provide : HTTP_INTERCEPTORS,        useClass : TokenInterceptorService,        multi : true      },      NavigationItem    ],  })  export class AdminModule { }  

When i do ng serve , it is giving me the error which I mentioned above. Meanwhile, it is important to tell that this error started when I added user componet. I first created user component in admin/component and also I created user module and router module using ng g m user --routing --flat in the user component folder. Then, I added its route in admin-routing module. Any help will be appreciated.

Thanks in advance :)

Find common features of the group that make it different from another

Posted: 07 Jun 2021 08:45 AM PDT

I have two groups of patients (ill and healthy). Each patient has features with ranks like so:

healthy_patient1 <- data.frame(feature=c("a", "b", "c", "d", "e", "f"), rank = c(0.001, 0.002, 0.002, 0.003, 0.05, 0.067))  healthy_patient2 <- data.frame(feature=c("a", "d", "e", "f", "g", "h", "q"), rank = c(0.001, 0.008, 0.01, 0.02, 0.05, 0.067, 1.2))  healthy_patient3 <- data.frame(feature=c("c", "d", "e", "g", "k", "l"), rank = c(0.003, 0.005, 0.01, 0.02, 0.05, 0.08))  healthy_patient4 <- data.frame(feature=c("b", "e", "g", "d", "k", "q", "o"), rank = c(0.001, 0.008, 0.01, 0.021, 0.054, 0.078, 1.1))    ill_patient1 <- data.frame(feature=c("c", "d", "e", "f", "o", "p", "q"), rank = c(0.002, 0.004, 0.005, 0.006, 0.02, 0.067, 0.09))  ill_patient2 <- data.frame(feature=c("e", "f", "o", "p", "r"), rank = c(0.001, 0.003, 0.02, 0.02, 0.03))  ill_patient3 <- data.frame(feature=c("c", "e", "o", "n", "k", "r"), rank = c(0.003, 0.005, 0.01, 0.03, 0.04, 0.08))  ill_patient4 <- data.frame(feature=c("b", "e", "o", "h", "n", "r", "s"), rank = c(0.002, 0.007, 0.01, 0.02, 0.03, 0.068, 1.1))  

ranks show the specificity of the feature in a particular patient, the lower the rank, the more important is the feature. I want to find common features among healthy patients that differ them from ill patients. And vice versa features that are common for ill patients that differ them from healthy patients.

Also, I need to know the common features' ranks sum

I tried this:

healthy_comm <- intersect(intersect(healthy_patient1$feature, healthy_patient2$feature),intersect(healthy_patient3$feature, healthy_patient4$feature))  ill_comm <- intersect(intersect(ill_patient1$feature, ill_patient2$feature),intersect(ill_patient3$feature, ill_patient4$feature))  setdiff(healthy_comm, ill_comm)        healthy_comm   [1] "d" "e"      ill_comm   1] "e" "o"      setdiff(healthy_comm, ill_comm)   [1] "d"  

I can go back and find "d"'s rank sum in the original data, but in my real datasets, I have a lot more patients and features. So, maybe there is a more elegant and efficient solution to this problem

Problems with DCP rules in CVXR

Posted: 07 Jun 2021 08:45 AM PDT

I am using the CVXR modelling package to solve a convex optimization problem. I know for sure that the problem is convex and that it follows the DCP rules, but if I check the DCP rules using CVXR it returns False. However, if I take the exact same problem and check it using CVXPY it returns True (as expected)

What is happening here? I attach a minimal reproducible example of this behavior in R and Python:

R code using CVXR

library(splines2)  library(CVXR)  deriv_basis = splines2::dbs(seq(0, 1, length.out=100), degree=3, intercept=T, df=30, derivs=2)  R = t(deriv_basis) %*% deriv_basis  beta_var = CVXR::::Variable(nrow(R))  q = CVXR::quad_form(beta_var, R)  CVXR::is_dcp(q)    [1] FALSE    write.table(x=R, file='R.csv'), row.names=F, sep=';')  

Python code using CVXPY

import cvxpy  import pandas as pd    R = pd.read_csv('R.csv', sep=';').values  beta_var = cvxpy.Variable(R.shape[1])  q = cvxpy.quad_form(beta_var, R)  q.is_dcp()    Out[1]: True  

Can someone explain what is happening here and how to solve it so I can use CVXR?

C++ Custom Exception classes

Posted: 07 Jun 2021 08:46 AM PDT

i am making a program and decided to make my own exceptions so i wrote the following header-only file:

#ifndef ARGUMENT_EXCEPTIONS  #define ARGUMENT_EXCEPTIONS    #include <exception>      namespace AAerr {        class ArgumentException : public std::exception {      private:          const char* msg;          static constexpr char* funcName = (char*)"ArgumentException";      public:          ArgumentException(const char* msg_) {              msg = msg_;          }            const char* getMessage() {              return msg;          }            virtual const char* what() const throw() {              return funcName;          }      };          class WrongReturnType : public ArgumentException {      private:          const char* msg = "Wrong Type";          char requestedType;          char ofType;          static constexpr char* funcName = (char*)"WrongReturnType";      public:          WrongReturnType(const char requested, const char is) : ArgumentException(msg) {              requestedType = requested;              ofType = is;          }              char get_requested_type() {              return requestedType;          }              char get_of_type() {              return ofType;          }            virtual const char* what() {              return funcName;          }      };    }    

No comments:

Post a Comment