Thursday, April 22, 2021

Recent Questions - Stack Overflow

Recent Questions - Stack Overflow


Relaxation of equality and inequality linear constraints

Posted: 22 Apr 2021 08:08 AM PDT

This question is a followup of this one : Relaxation of linear constraints?

In th eprevious question, we had an optimisation problem under linear matrix-vector constraints Ax=b, where A is a matrix, x is a variable and b is a constant vector. The solution was:

  • Find an intial solution x0 to the constraint equation Ax=b
  • Use a SVD to decompose A into A = USV, and denote by Vt the lasts columns of V corresponding to zero eigen-values.
  • construct solutions as x = x0 + c'Vt where c are any vector.

We indeed constructed the affine space representation of these constraints.

What now if, on top of linear constraints, i have a box constraints x_i >= 0 for all i ?

I can still use x = x0 + c'Vt to obtain my variable, that satisfy the linear constraints, from any c, but all x_i might not be positive. Is there a way to propagate this positivity constraint onto c ?

when I upload it on Github and test on the website, I got an error message "API is not defined" what should I do?

Posted: 22 Apr 2021 08:08 AM PDT

//config.js  const api = {       rapidApiKey : '12345'    }    
//.gitignore  config.js  
//script.js  function covidStates() {          const options = {      method: 'GET',      url: 'https://vaccovid-coronavirus-vaccine-and-treatment-tracker.p.rapidapi.com/api/covid-ovid-data/sixmonth/USA',      headers: {        'x-rapidapi-key': api.rapidApiKey,        'x-rapidapi-host': 'vaccovid-coronavirus-vaccine-and-treatment-tracker.p.rapidapi.com'      }    };        axios.request(options).then(function (response) {      console.log(response.data);        let totalDeaths = document.querySelector('.total_deaths');      totalDeaths.innerHTML = response.data[0].total_deaths;      }).catch(function (error) {      console.error(error);    });    }  covidStates();  

I hid my API-key in 'config.js' and add the file on '.gitignore'.

when I test on my computer, I could get data without problem.

but when I upload it on Github and test on the website, I got an error message "API is not defined"

what should I do???

Drop duplicates based on two columns in python

Posted: 22 Apr 2021 08:08 AM PDT

I have a dataset with 100 columns, how can I delete duplicated rows based on two columns (i.e. Column B and Column D).

Thank you for your help!

How to read value from properties using picocli and using it connect postgres

Posted: 22 Apr 2021 08:08 AM PDT

I using picocli and i want build cli get data from database and send it to another service. So i config look like

object Student : Table("student") {      val id = integer("student_id").autoIncrement().primaryKey()      val name = varchar("name", 50)      val grade = integer("grade")  }    class App() : Callable<Integer> {      @CommandLine.Option(names = ["-ho", "--host"], description = arrayOf("Host database"), defaultValue = "localhost")      var host: String? = null        @CommandLine.Option(names = ["-p", "--port"], description = arrayOf("port database"), defaultValue = "5432")      var port: String? = null        @CommandLine.Option(names = ["-d", "--database"], description = arrayOf("database"), defaultValue = "postgres")      var database: String? = null        @CommandLine.Option(names = ["-u", "--username"], description = arrayOf("username of database"), defaultValue = "postgres")      var username: String? = null        @CommandLine.Option(names = ["-w", "--password"], description = arrayOf("password off database"), defaultValue = "password")      var password: String? = null        override fun call(): Integer {         connectDB()         createStudent()         return Integer(0)      }        fun createStudent() {          println("Begin create student")          transaction {              create(Student)          }          println("End create student")      }        fun connectDB() {          try {              Database.connect("jdbc:postgresql://${this.host}:${this.port}/${this.database}", "org.postgresql.Driver",this.username.toString(),this.password.toString())              print("Connect db")          } catch (e : Exception) {              println("Connect db fail with error ${e.message}")          }      }    }    fun main(args: Array<String>) {      val existCode = CommandLine(App()).execute(*args)      System.exit(existCode);  }  

when i excute it connect success. But i don't want parse value from args. I want read from my file properties example : db.properties or db.yml. How to do do it ? I search doccument picocli but i can't find anything it. So now i using org.jetbrains.exposed:exposed crud to my postgres.It work together with picoli ? Any suggest framework if when get data from database and send it to another api ? Thanks you so much

Nearest neighbor interpolation in GLSL

Posted: 22 Apr 2021 08:08 AM PDT

I have a GLSL fragment shader as part of a pipeline that renders slices of two 3D volumes blended together. For one of the volumes, I would like to use nearest neighbor interpolation since it is a "segmentation mask" (i.e. at each voxel indicates, which structure the voxel in the other image belongs to, e.g. 0 for background, 1 for target structure; see purple overlay in the image below), since the default trilinear interpolation creates undesired artifacts at the borders (green line at the border in the image below)

enter image description here

How would I have to modify the fragment shader code below to use nearest neighbor interpolation on the segmentation mask (vol2)?

uniform sampler3D vol1;  uniform sampler3D vol2;  uniform sampler2D lut1;  uniform sampler2D lut2;    uniform float maskAlpha = 0.5;    void main()  {      float data1 = texture3D(vol1, gl_TexCoord[0].xyz).r;      float data2 = texture3D(vol2, gl_TexCoord[0].xyz).r;      vec4 col1 = texture2D(lut1, vec2(data1));      vec4 col2 = texture2D(lut2, vec2(data2));            gl_FragColor = col1 + col2 * maskAlpha;  }  

Improve pronounciation of a model

Posted: 22 Apr 2021 08:08 AM PDT

I fine-tuned a dataset of Nvidia Tacotron2. While working reasonably well, there are some mispronounciations of words(I train a german dataset).

How do I filter a new set of phrase-audiofile-combinations to include those mainly that teach the model those pronounciations that are missing?

KNN prediction with L1 (Manhattan distance)

Posted: 22 Apr 2021 08:08 AM PDT

I can run a KNN classifier with the default classifier (L2 - Euclidean distance):

def L2(trainx, trainy, testx):        from sklearn.neighbors import KNeighborsClassifier      # Create KNN Classifier      knn = KNeighborsClassifier(n_neighbors=1)        # Train the model using the training sets      knn.fit(trainx, trainy)        # Predict the response for test dataset      y_pred = knn.predict(testx)      return y_pred  

However, I want to use L1 (Manhattan) distance as my distance function.

The following is invalid (even though I thought I was following the documentation):

def L1(trainx, trainy, testx):        from sklearn.neighbors import NearestNeighbors      from sklearn.neighbors import DistanceMetric      dist = DistanceMetric.get_metric('manhattan')      # Create KNN Classifier      knn = NearestNeighbors(n_neighbors=1, metric=dist)        # Train the model using the training sets      knn.fit(trainx, trainy)        # Predict the response for test dataset      y_pred = knn.predict(testx)      return y_pred  

There is no predict() for NearestNeighbors, and my use of metric=dist is also wrong.

I want\need to do a prediction using KNN with the Manhattan distance function. Is this possible?

finding the least common multiple

Posted: 22 Apr 2021 08:07 AM PDT

a=int(input(''))  b=int(input(''))  g=0  def fac(n):      if n <= a :          return a      else:          return n*fac(n-1)  numbers=[]  i=a  while a <= i <= b:      if a <= i <= b:          numbers.append(i)          i += 1      else:          break        for k in range(b,fac(b)):      for l in numbers:          if k % l == 0:              g=k            

print(g)

I am making a code that calculates the least common multiple of the numbers in range. I have checked the fac function and the while(if,else) I think there is a problem in the for part. I cant find the wrong part.

How to apply parent data attribute value to dynamically inserted button

Posted: 22 Apr 2021 08:07 AM PDT

I have some markup like this:

<table id="fcm_table">      <tbody>          <tr>              <td class="hs_button" data-buttonID="<?php echo $buttonID; ?>"></td>          </tr>      </tbody>  </table>  

I need to insert an anchor tag in the and apply the "button ID" as the href, however I cannot target the parent td's data-buttonID value. I keep getting undefined.

function hs_button_dyn() {     var button_ID = $(this).parent('td.hs_button').data('buttonID');     var content = '<a id="bar" href="' + button_ID + '">foo</a>';     $('#fcm_table tbody tr td.hs_button').prepend(content);  }    $(function(){      hs_button_dyn();  });  

Get name of enum variant as string - serde - Rust

Posted: 22 Apr 2021 08:07 AM PDT

I'm trying to get the name of an enum variant as the string serde would expect/create.

For example, say I have the following enum:

#[derive(Serialize, Deserialize)]  #[serde(rename_all="camelCase")]  pub enum SomeEnum {      WithoutValue,      withValue(i32),  }  

How can I then get the serde names of the variants, something like

serde::key_name(SomeEnum::WithoutValue) // should be `withoutValue`  serde::key_name(SomeEnum::WithValue)    // should be `withValue`  

I can use a hack with serde_json, for variants without a value I can do:

serde_json::to_string(SomeEnum::WithoutValue).unwrap(); // yields `"withoutValue"` with quotation marks  

This is not the best solution as I then need to strip the quotation marks, but can technically work.

Even worse is when the enum variant has a value, e.g.

serde_json::to_string(SomeEnum::WithValue(0)).unwrap(); // yields `"{\"second\":0}"  

This becomes much more messy.

So my question is, is there a clean way to achieve this? I can't find a serde api to get key name as a string

Nginx Lua extension read multipart-form body leaving it in tact (proxy)

Posted: 22 Apr 2021 08:07 AM PDT

I am using OpenResty. The objective is to create some middle ware with Lua, on Nginx so that I can check the body for certain fields, however leave the body intact after I read the fields. Infact in some cases I would like to remove the fields from the body.

In the case of application/x-www-form-urlencoded I am able to use

ngx.req.read_body()  local args = ngx.req.get_post_args()  

and the body does indeed make it through to my backend without being affected.

In the case of application/json I am able to use

ngx.req.read_body()  local args = json.decode(ngx.req.get_body_data())  

However when the content-type is multipart/form-data and I am attempting to use resty.upload I cannot work out how to leave the body attached to the request, let alone edit it if I wanted to do so.

In it's most basic form, using the resty.upload library requires reading the multipart form with

local form, err = upload:new(chunk_size)  

The moment I do this however, The backend server receives no body content.

There seems to be two open pull requests for this code, namely 1 and 2 although I have attempted to use both these versions of upload.lua to no avail.

I have seen that there are libraries that aim to handle this situation such as

However both of these suffer from larger uploaded files and I can't be restricted by this. In both cases they suggest using the resty.upload library that I am using.

Ultimately I am looking in the body regardless of the above content-type for a field called X_CUSTOM_FIELD and if it is there, log it and strip it out of the request completely.

I have not managed to work out how to strip it from the body, but step 1 is to make sure I can atleast read it without tampering. Any help greatly appreciated

changing background-color of a <tr> in react with useRef

Posted: 22 Apr 2021 08:07 AM PDT

I created a plain dynamic table in react (not using react-table). I want to change the background color of a clicked row. I added ref to table: but I'm not getting access to children ().

How can I change the style of a clicked row by id in a table in react?

import React, { useEffect, useRef } from 'react'  import './TableBox.css'    const TableBox = ({ table_data }) => {        const myTable = useRef(null);        useEffect(() => {          console.log("myTable", myTable.current);      });          const handlerRowClicked = (event) => {          // console.log('clicked')          // myTable.current.backgroundColor='blue'        }        return (          <div>              <table ref={myTable}>                  <thead>                      <tr >                          {Object.keys(table_data[0]).map((title) => (                              <th key={title}>{title}</th>                          ))}                      </tr>                  </thead>                  <tbody>                        {table_data.map((row, index) => (                          <tr key={index} id={index} onClick={handlerRowClicked}>                              {                                  Object.keys(row).map((key) => (                                       <td key={row[key]}>{row[key]}</td>                                  ))                              }                          </tr>                      ))                        }                    </tbody>              </table>          </div>      )  }    export default TableBox  

Undefined index: updatefolder in C:\xampp\htdocs\OJT\process.php on line 15

Posted: 22 Apr 2021 08:07 AM PDT

Hello Good Day Im having Problem in Updating a folder name this is my code for html sorry in advance if the code is screen shot cause i dont know how to edit it here in body section sorry enter image description here

and this is where the problem begin he access the file which is proccess.php which contains the updating code but it seems that my input value not storing my inputted data the code below is the proccess.php

enter image description here

Angular custom library doesn't work with Electron

Posted: 22 Apr 2021 08:07 AM PDT

I'm trying to use a custom Angular component library which I´ve made in an Electron project. I have already use this library in an Angular project and it does work correctly, so I'm assuming the problem is something related with the library and Electron.

After installing all dependencies and setting all up, I can start the app, but it starts completly white as if nothing is loading. Only one error at console:

Console error

After some research, I couldn't find any workaround as the error isn't descriptive.

If there is any file or setting that can help for the answer, ask for it in a comment and I'll edit the post to add it!

Running a function in a for loop

Posted: 22 Apr 2021 08:08 AM PDT

I have a simulator which rolls a 6 sided dice:

def diceRoll6():      return random.randint(1,6)  

and now I want to repeat this roll with a for loop, but also to be able to change which simulator I am using in the function, e.g. maybe I have another function which rolls 2 dice and takes the product.

def frequencies(sim,n):      output = []      for i in range(n):          result = sim          output.append(result)      return output  

However whenever I run frequencies(diceRoll6(),10) it just has the same output 10 times, rather than running the simulator 10 separate times and getting different outputs.

Proper way to pass optional parameter if not null Javascript

Posted: 22 Apr 2021 08:08 AM PDT

Is there a way to pass optional parameter into a function only if its not null in Javascript? Else, do not pass this parameter at all.

For example, the below function, how to not insert c parameter if var_c is null

function({  a:var_a,  b:var_b||'b', //if b is null, set is as string b  c:var_c||null //how to check if c is null and do not insert this parameter at all into function  })   

How to extract part of the properties' keys of an object as a union type?

Posted: 22 Apr 2021 08:07 AM PDT

In Typescript, I'd like to do the following:

Typescript playground

type MY_OBJECT = {    fooA: string,    fooB: string,  }    type SOME_PROPS = Extract<keyof MY_OBJECT, "fooA" | "fooB" | "fooC">  

I'd like Typescript to "know" that there's no "fooC" available on keyof MY_OBJECT and warn me about that.

In other words, I'd like to extract part of the properties of an object and a union type and I'd like to keep it all strongly typed.

For example, if I ever change fooA to fooAAA on MY_OBJECT, I'd like to know immediately that I need to fix something on that Extract<> type, since fooA would no longer exist.

Is it possible?

Cannot return badrequest mvc in the controller

Posted: 22 Apr 2021 08:07 AM PDT

Why Can't I return a bad request here? In other examples it works just fine.

    [HttpGet("getPrediction/{dateTime}/{filterUnit}/{filterLocation}/{filterContent}")]      public int GetFillLevelForDateTime(string dateTime, bool filterUnit, int unit, bool filterLocation,          double latitude, double longitude, bool filterContent, string containerContent)      {          try          {              bool tempExists = predictionService.CheckIfMessagesExist(unit, latitude, longitude, filterUnit, filterLocation);              if (tempExists)              {                  return GetFillLevelPrediction(dateTime, filterUnit, unit, filterLocation, latitude, longitude, filterContent, containerContent);              }          } catch (Exception ex)          {              return BadRequest();          }      }  

Paypal Sandbox issue with Woocomerce

Posted: 22 Apr 2021 08:08 AM PDT

I am using woocomerce and PayPal sandbox, whenever I am placing an order it shows me a successful message at the end of the sandbox but in woocomerce, I get the message "Pending payment". I have tried everything that is on google but not able to solve this issue.

Kindly help me out with this.

AWS RDS MySQL Error: Index column size too large. The maximum column size is 767 bytes

Posted: 22 Apr 2021 08:08 AM PDT

I've unsuccessfully been through the AWS forum and Stack Overflow trying to find a solution to the following error: Index column size too large. The maximum column size is 767 bytes

I am running a WordPress website with 1.5M records in the postmeta table. I recently added an index to the postmeta table, and all was testing ok. However I had an incident with my server today (botnet scan dwindled my RDS credits), and restarted both my Lightsail instance and my RDS MySQL instance. After the restart I noticed that the site wasn't working properly and upon further investigation found the postmeta table was returning the error Index column size too large. The maximum column size is 767 bytes.

I'm running on MySQL 8.0.20

The table is:

    Engine = InnoDB        Charset = utf8mb4        Collation = utf8mb4_0900_ai_ci        Row Format = Compact    

Many existing "solutions" talk about recreating the table, however I need the data that's currently in the table. Unfortunately this issue is present in my oldest AWS RDS Snapshot, so back ups don't appear to be an option.

Every time I try run an ALTER or SELECT statement, I get the same error, Index column size too large. The maximum column size is 767 bytes. I've tried:

  • Changing the ROWFORMAT=DYNAMIC
  • Converting the charset and records to utf8
  • Changing the meta_value column from 255 to 191
  • Removing the custom index
  • Dumping the table

I can see that the default ROWFORMAT is now "DYNAMIC", however this table is still "COMPACT" from when it was running on MySQL 5.7

I've also tried updating the AWS RDS MySQL from 8.0.20 to 8.0.23, however the update fails cause it reports the table is corrupt in PrePatchCompatibility.log.
Ref: https://dba.stackexchange.com/questions/234822/mysql-error-seems-unfixable-index-column-size-too-large#answer-283266

There are some other suggestions about modifying the environment and file system, and running "innodb_force_recovery".
https://dba.stackexchange.com/questions/116730/corrupted-innodb-table-mysqlcheck-and-mysqldump-crash-server
However being an RDS instance, I don't have access to this lower level of the instance.

I suspect this issue is the column length and utf8mb4, however my main priority is getting the data from the currently in the table.
I also understand that changing the ROWFORMAT to DYNAMIC should fix this issue - however getting the same error.

Ref: http://mysql.rjweb.org/doc.php/limits#767_limit_in_innodb_indexes

I have also tried the "RDS Export to S3" option with no luck.

Please help, I'm lost as to what else to try.

How to add a class name to ul li in angular 11

Posted: 22 Apr 2021 08:08 AM PDT

Tried to add a class name like active to ul li using div class name wrapper. But, It is not working. How to access the class name to add a class name to ul li in typescript. I do not know how to do it. So, please help to find the solution.

app.component.html:

<div class="wrapper">  <ul>  <li class="active">test1</li>  <li>test2</li>  <li>test3</li>  </ul>  </div>    <button (click)="activeTab('test1')"> Test 1 </button>  <button (click)="activeTab('test2')"> Test 2 </button>  <button (click)="activeTab('test3')"> Test 3 </button>  

app.component.ts

  activeTab(tabname: any) {        let el = this.elRef.nativeElement                 .querySelector(".wrapper")                 .querySelector("ul")                 .querySelectorAll("li");           el.forEach(name => {              console.log(name.innerHTML);              var tname = name.innerHTML;        if (tname == tabname) {           this.renderer.addClass(el, "active");        } else {           this.renderer.removeClass(el, "active");        }        });    }  

Demo: https://stackblitz.com/edit/angular-ivy-nwycmk?file=src%2Fapp%2Fapp.component.ts

How to fix Mann-whitney u for error: len() of unsized object pyspark?

Posted: 22 Apr 2021 08:07 AM PDT

I have a pyspark dataframe. A sample is as shown below:

+----------+----------+---------+  |      date|    before|    after|  +----------+----------+---------+  |2018-01-17|      3084|     3252|  |2019-01-16|      1298|     1845|  |2018-01-27|      3533|     3405|  |2018-01-28|      4756|     4532|  |2018-02-27|      3312|     6785|  |2018-03-17|      6757|     2432|  |2018-03-22|      2353|     4554|  |2018-03-23|      1234|     2345|  +----------+----------+---------+  

I want to perform mannwhitneyu test on two columns: before (dtype: bigint )and after(dtype: bigint)

I tried this:

1)

results = mannwhitneyu(df['before'], df['after'])  
data_1 = df['before']  data_2 = df['after']  results = mannwhitneyu(data_1, data_2)    But I get the following error:     7147     x = np.asarray(x)     7148     y = np.asarray(y)  -> 7149     n1 = len(x)     7150     n2 = len(y)     7151     ranked = rankdata(np.concatenate((x, y)))    TypeError: len() of unsized object  

Please suggest.

FMX aplication - Access violation at address

Posted: 22 Apr 2021 08:07 AM PDT

When try execute below code on Android 10 get error: Access violation at address C0BB2EF4. accessing address 46CC0000

var      BS: TBlobStream;      BlosStream:TStream;      FS: TFileStream;      begin            OraQuery1.Close;      OraQuery1.Active;      OraQuery1.Open;            BlosStream := OraQuery1.CreateBlobStream(OraQuery1.FieldByName('image'),TBlobStreamMode.bmRead);            try           try              FS :=  TFileStream.Create(System.IOUtils.TPath.Combine(System.IOUtils.TPath.GetDownloadsPath, 'image.jpg'), fmCreate or fmOpenWrite);              try                 FS.CopyFrom(BlosStream, BlosStream.Size);              finally                 FS.Free;              end;           finally              BS.Free;           end;     except on E: Exception do       ShowMessage('e.Message);     end;                 

Any solution? before few years on other android app all is work fine.

Count time when a message arrives from server (mqtt)

Posted: 22 Apr 2021 08:08 AM PDT

I have a mqtt client that subscribes to a publisher. I have used the example code from here.

The messages are published irregularly (not at regular intervals). I want to start a timer when a message arrives, so that I can call another function if "X" seconds have passed. Could someone please suggest me as to how can I do this(an example would be really helpful).

class callback : public virtual mqtt::callback, public virtual mqtt::iaction_listener      {          void message_arrived(mqtt::const_message_ptr msg) override          {              std::cout << "Message arrived" << std::endl;          }        public:          callback(mqtt::async_client& cli, mqtt::connect_options& connOpts, std::string topic)              : nretry_(0), cli_(cli), connOpts_(connOpts), subListener_("Subscription"), TOPIC(topic)          {              tEth = std::thread(&callback::checkTimeBwMsgs, this);          }                double getElapsedTimeBwMsgs()          {              auto t_now = std::chrono::system_clock::now();              elapsed_time_ms = std::chrono::duration<double, std::milli>(t_now - timerStart).count();              //timerStart = std::chrono::system_clock::now();                    return elapsed_time_ms;          }                bool getIsData()          {              return isData;          }                void checkTimeBwMsgs()          {              double timeDur = getElapsedTimeBwMsgs();              std::cout << timeDur << std::endl;              if(timeDur > 1000.0)                  // do something          }                ~callback()          {              tEth.join();          }      };  

The method 'message_arrived' is called when the client receives a message from the broker/publisher. I create a std::thread in the constructor which should be able to measure the time elapsed between 2 messages and if the time passed is greater than 5 seconds then call another method.

This method calculates the elapsed time only once. I want it to do it as long as the program is running. I am not sure if my approach is correct.

Is there any way in mqtt paho library that can give the time elapsed after receiving a message, whenever asked for.

METHOD 2:

int main()  {      mqtt::async_client client(SERVER_ADDRESS, CLIENT_ID);      mqtt::connect_options connOpts;      connOpts.set_keep_alive_interval(5);      connOpts.set_clean_session(true);        callback cb(client, connOpts, TOPIC);      client.set_callback(cb);            std::thread tEth(ThreadFunc, cb);  }  

Here, I create a thread in the main function and pass the object of the callback class as an argument. This gives the following error:

enter image description here

Insert dynamic column names into Mcode

Posted: 22 Apr 2021 08:07 AM PDT

I wish to modify the M code below so that the names of a Table are dynamically inserted, such that if a user changes the name of the table, the logic still flows. A lot of sources out there that describe how to dynamically change the name of a column, however I wish to also be able to apply transformations to the data regardless of what the column name is changed to. This seems possible since you can create a searchable list of the column names using:

DynamicHeaderName = Table.ColumnNames(#"Changed Type"),

And using {0}, {1}, {2} etc to pull the desired name.

Working non Dynamic M Code:

let      Source = Excel.CurrentWorkbook(){[Name="Table1"]}[Content],      #"Changed Type" = Table.TransformColumnTypes(Source,{{"Column1", type text}, {"Column2", type text}, {"Column3", type text}}),          DynamicHeaderName = Table.ColumnNames(#"Changed Type"),    //combine the columns      #"Added Custom" = Table.AddColumn(#"Changed Type", "Custom", each let               L1 = if [Column2] = "-" then {[Column1]}                      else List.Combine({{[Column1]},Text.Split([Column2],"#(lf)")}),              L2 = if [Column1] = "-" then {[Column3]}                      else List.Combine({{"-"},Text.Split([Column3],"#(lf)")})                      in               List.Zip({L1,L2}))  

This sample of code is really just for example and isn't that important. The code just sorts the data between the columns where Column 2 cell usually contains multiple lines of data (split by #"(lf)" in the code )

As a test using Test = DynamicHeaderName{0} returns Column1, so It seems possible that I can replace [Column1] with [DynamicHeaderName{0}] or equivalent. However having a list within [] causes some syntax conflict I cant work out.

Im no expert when it comes to programming languages, so If anyone could explain what I am doing wrong that would be appreciated.

How to insert 10 rows for each Id in the same table

Posted: 22 Apr 2021 08:07 AM PDT

I have created loop for inserting data into a table 10 times with ProjectId hardcoded And my code looks something like this

DECLARE @IndexNumber INT  SELECT @IndexNumber  = 1    WHILE @OrderIndex >=1 AND @OrderIndex <= 10      BEGIN           INSERT INTO [tablename] (@IndexNumber [a], [b], [c], [ProjectId])           VALUES (a, b, c, 50)           SELECT @IndexNumber = @IndexNumber + 1      END  

But now i want create a loop to insert same data but with ProjectId value incrementing after inserting ten rows for exapmple:

ten rows with a, b, c, 50

ten rows with a, b, c, 51

ten rows with a, b, c, 53

ten rows with a, b, c, 54

...

How to let users import from subfolders of my NPM package

Posted: 22 Apr 2021 08:08 AM PDT

I want to let users import from the subfolders of my TypeScript NPM package. For example, if the directory structure of the TypeScript code is as follows,

- lib  - src    - server    - react  

users of my package should be able to import from subfolders as package-name/react, package-name/server etc.

My tsconfig.json is as follows.

{      "compilerOptions": {        "target": "es5",        "module": "commonjs",        "declaration": true,        "outDir": "./lib",        "strict": true,        "jsx": "react",        "esModuleInterop": true      },      "include": ["src"],      "exclude": ["node_modules", "**/__tests__/*"]    }  

I could do this when "outDir" was set to the project root, but then the file structure is messy. Can someone point me a way out to do this (importing from submodules) while preserving "outDir": "./lib"? Helpful answers are highly appreciated. Thanks in advance.

How to read raster as array?

Posted: 22 Apr 2021 08:07 AM PDT

  from pyrsgis import raster    from pyrsgis.convert import changeDimension      # Assign file names      greenareaband1='Sentinel-2  (2)dense.tiff'    greenareaband2='Sentinel-2 L1C  (3)dense.tiff'    greenareaband3='Sentinel-2 L1C  (4)dense.tiff'        # Read the rasters as array    df,myimage=raster.read(greenareaband1,bands='all')        AttributeError: 'NoneType' object has no attribute 'ReadAsArray'  

I keep getting this error but i'm sure that i have uploaded these images using from google.colab import files files.upload()

Laravel Livewire component not refreshing/reloading automatically after refreshing it

Posted: 22 Apr 2021 08:07 AM PDT

So, I'm currently using Laravel Livewire in one of my projects. But when I try emit an event from one component to another component by magic mathod $refresh , its refreshing (got the dom in xhr request ) the total component but the Front end is not updating realtime.

ProductReviewForm.php Component

  public function save()      {          //some functionalities ....               $this->emit('reviewSectionRefresh');          }  

ProductReviewSection.php Component

 protected $listeners = [          'reviewSectionRefresh' => '$refresh',      ];        public function render()      {          $this->review_lists = ProductReview::orderBy('id', 'DESC')->get();            return view('livewire.desktop.product-review-section');      }  

So I want to emit the reviewSectionRefresh event to be emitted whenever I call save() function from First component, That should be listened by $listeners from other component. This is working fine. also in xhr I'm getting the refreshed dom but the component in frontend is not updating. Hoping anyone working with Livewire may help with that.

CoinMarketCap API to Angular request

Posted: 22 Apr 2021 08:08 AM PDT

I have my head in water with the new CoinMarketCap API.

Below is an example of a request in Node. How can I make a request in Angular? Any suggestions? Thanks.

 /* Example in Node.js ES6 using request-promise, concepts should translate    to your language of choice */     const rp = require('request-promise');   const requestOptions = {   method: 'GET',   uri: 'https://pro-api.coinmarketcap.com/v1/cryptocurrency/listings/latest',   qs: {     start: 1,     limit: 5000,     convert: 'USD'   },   headers: {    'X-CMC_PRO_API_KEY': 'API_KEY_HERE'   },   json: true,   gzip: true  };    rp(requestOptions).then(response => {    console.log('API call response:', response);  }).catch((err) => {   console.log('API call error:', err.message);  });  

No comments:

Post a Comment