Tuesday, January 4, 2022

Recent Questions - Stack Overflow

Recent Questions - Stack Overflow


Increase values from vector for each call

Posted: 04 Jan 2022 05:05 AM PST

I want to use a function for a vector multiple times and for each call to increment the vector's value. How could I do it ?

#include <iostream>  #include <vector>  using namespace std;    struct A  {         void pri(std::vector<int> a)      {          std::cout<<"0: " << a[0] << std::endl;          std::cout<<"1: " << a[1] << std::endl;      }            void priUse(std::vector<int> a)      {          pri(a);          **pri(a + 1);** // to work this      }  };    int main()  {     std::vector<int> a = {1, 2};      A aa;      aa.priUse(a);        return 0;  }  

Nuxt CDN: How to host JS files?

Posted: 04 Jan 2022 05:05 AM PST

Nuxt has a default configuration for CDN. You just have to do:

// nuxt.config.js  module.exports = {    //...    build: {      publicPath: "https://you-cdn-url.com/_nuxt/"    }  }  

But when I go to my console, the application just gets images from the CDN. I was hoping it would also load CSS and JS files.

Can I make it work?

(The Nuxt app is SSR)

Java - compare LocalDates with 2 and 4 digit years

Posted: 04 Jan 2022 05:05 AM PST

I am trying to compare two LocalDate variables. One is created by me by hand, so to say, and the other I obtain it through running a Spring JPA query on a Oracle db. If I try to print the one from Oracle db it returns "0022-01-31" while my "by-hand" LocalDate comes out as "2022-01-31". Now, as I understand, the formatting should not matter when comparing the dates themselves. Still, when I try to check that the two dates are equal, I get false.

Here is my code:

LocalDate lastDayOfTheMonth = LocalDate.now().with(TemporalAdjusters.lastDayOfMonth());    List<MyEntity> myEntityList= pPassPpCardRepository.findAll();    LocalDate expDate = myEntity.get(0).getExpDatePP();    System.out.println("LocalDate lastDayOfTheMonth: " + lastDayOfTheMonth.toString());  System.out.println("myEntityList.get(0).getExpDatePP().toString(): " + myEntityList.get(0).getExpDatePP().toString());    System.out.println("EQUALS attempt1: " + lastDayOfTheMonth.isEqual(expDate));  System.out.println("EQUALS attempt2: " + (lastDayOfTheMonth.compareTo(expDate) == 0));  

Console :

LocalDate lastDayOfTheMonth:   2022-01-31  myEntityList.get(0).getExpDatePP().toString(): 0022-01-31  EQUALS attempt1: false  EQUALS attempt2: false  

Why is that ? What am I doing wrong ?

ngrx component store select returns anonymousSubject instead of Observable

Posted: 04 Jan 2022 05:05 AM PST

I am using the ngrx component store to get search results from the backend. However, I am unable to get a single value of the state, but instead I get an anonymousSubject. This anonymousSubject has the needed data but it is nested very deep in the object.

When I iterate over the returned observable in the html, I can get the right values, but now I need just a specific value (state.result[0]) but I cant do this.

Could someone clarify how I can acces a single value from the anonymousSubject? Thanks in advance!

Component.store

export interface SearchResultState {    result: Array<any>;  }    const defaultState: SearchResultState = {    result: []  };    @Injectable()  export class SearchStore extends ComponentStore<SearchResultState> {    constructor(      private readonly _http: HttpClient,      private readonly _notificationHandler: NotificationHandlerService    ) {      super(defaultState);    }    readonly loadSearchResult = this.effect((trigger$: Observable<{ query: string; apiLinks: Array<string> }>) =>      trigger$.pipe(        debounceTime(200),        switchMap((action) => {          if(!action.query.length) {            return of(SearchActions.searchSuccess({result: {}}));          }          const headers: any = {            'Content-Type': 'application/x-www-form-urlencoded',            Accept: 'application/json',          };          const httpOptions: { headers: HttpHeaders } = {headers: new HttpHeaders(headers)};            const apiCalls = [];          for (const apiLink of action.apiLinks) {            apiCalls.push(this._http.get(`${API_URL}${apiLink}${action.query}`,  httpOptions).pipe(              map((resp: any) => resp),            ));          }            return forkJoin(apiCalls).pipe(            map((result) => {              console.log(result); //prints the right result              return this.setSearchResult({result});            }),            catchError(async error => {              this._notificationHandler.showError();              return SearchActions.searchFailed({error});            })          );        })      )    );      readonly setSearchResult = this.updater((state, result: any) => ({...state, result}));    readonly searchResult$: Observable<Array<any>> = this.select(state => {      console.log( 'state', state); //prints nothing unless used in the html      return state.result;    });  

Component.ts (partly)

  public _searchResult$ = this.searchStore.searchResult$;      public search($event: string): void {      this.searchStore.loadSearchResult({query: $event, apiLinks: this.apiLinks});      console.log(this._searchResult$); //prints the anonymousObject      this.searchResults.emit(this._searchResult$);    }    

Heroku R10 (Boot timeout) - Node.js

Posted: 04 Jan 2022 05:05 AM PST

So I have got into this problem while deploying my website with heroku. I have seen other solutions in which I have tried to change the scripts in package.json and Procfile aswell but no luck for me Please help me. This website runs well locally Here is my index.js main function

app.get("/", function(req, res){  const fact = facts.space  res.render("home", {fact: fact});  });  

Here is my listen function.

const port = 3000 || process.env.PORT  app.listen(port, function () {  console.log("@ working");  })  

Here is my packages.json packages.json Here is my Procfile Procfile Here is the error that I am getting Error Here are all of my files All files

Store JWT tokens in cookies with django-rest-framework-social-oauth2 library

Posted: 04 Jan 2022 05:05 AM PST

I wanted to securely store my JWT token. Up until now, I have used local storage, but I have read that using local storage is not secure. Hence, I wanted to start using HttpOnly cookies to store my JWT tokens. I was going to use CSRF protection inbuilt into Django to mitigate the security issues with cookies. However, I can't figure out how to use cookies with the Django-rest-framework-social-oauth2 library. There doesn't need to be any other library that has social auth and JWT auth. So my first question, is there a secure storage method that doesn't need cookies. If not, how does use django-rest-framework-social-oauth2 library with cookies?

performance of Typed arrays vs Non typed arrays in Javascript

Posted: 04 Jan 2022 05:05 AM PST

Learning about typed arrays, I read typed arrays normally should be more efficient/performant than non-typed ones.

I run this simple test:

    const a = [1,2,3,"4"]      const b = new Uint8Array([1,2,3,4])        const compare = (arr) => { for (let i = 0; i<4; i++) arr[i] }        let run=0        const init = performance.now()        while(run<10e7){      compare(b)      run++ }        const finish = performance.now()      console.log(finish-init)

array contains mixed string and number types.

But maybe I am not getting some idea here...

Should those be expected to differ more? Example?

how to make the picture still at same resolution but in small in file

Posted: 04 Jan 2022 05:05 AM PST

i read some of post that tell how to not resize the picture, they say if i use png it got no effect when i send it to firebase,but when i send to firebase the picture is blurry, this is my code

@Override      protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {          super.onActivityResult (requestCode, resultCode, data);          if(requestCode == 100) {              Bitmap bitmap = (Bitmap) data.getExtras ( ).get ("data");              ByteArrayOutputStream bytes = new ByteArrayOutputStream ( );              bitmap.compress (Bitmap.CompressFormat.PNG, 100, bytes);              String path = MediaStore.Images.Media.insertImage (getApplicationContext ( ).getContentResolver ( ), bitmap, String.valueOf (UUID.randomUUID()), null);              imageUri3 = Uri.parse (path);              imageView.setImageURI (imageUri3);                Log.e("Original   dimensions", bitmap.getWidth()+" "+bitmap.getHeight());          }      }  

and this is my log when i try to check the resolution

enter image description here

and this is the image result, the i mage became so small when i open it on web

enter image description here

sorry if i might send a dup question, just tell me the answer and i will delete the question directly if it works :)

Importing Eclipse to github [closed]

Posted: 04 Jan 2022 05:06 AM PST

I'm trying to upload an automation project on github, i did all the steps required when it comes to sharing the project, the option is unclickable 'it's grayed out'

im using eclipse and java language. the steps i did:

  1. created github account 2.from eclipse i opened perspective then created git
  2. i added the url of my git project
  3. tried to share the project by right clicking on it then teams but the option is faded

what should i do to add the project on github?

Generic method (bounded type) vs inheritance

Posted: 04 Jan 2022 05:05 AM PST

I have a typical question what is better and I think as always the answer is it depends, but I'd like to clarify it anyway. So there are two methods:

public static <A extends Animal, F extends Food> void feed(A animal, F food) {      animal.setFood(food);  }    public static void feed(Animal animal, Food food) {      animal.setFood(food);  }  

And the logic:

Cat cat = new Cat(); // Cat is a child of Animal  Dog dog = new Dog(); // Dog is a child of Animal    Pork pork = new Pork(); // Pork is a child of Food  pork.setName("Whiskas");  Beef beef = new Beef(); // Beef is a child of Food  beef.setName("Pedigree");    AnimalService.feed(cat, beef);  AnimalService.feed(dog, pork);    cat.eat(); // prints I'm eating Pedigree  dog.eat(); // prints I'm eating Whiskas  

I understand that there is a conflict of method signatures due to the type erasure, so my question is not "Why I can't have these two methods in the same time?", but rather "Which method would you choose?".

Create Table in a Loop inside Stored Procedure Oracle SQL

Posted: 04 Jan 2022 05:05 AM PST

I am attempting to create a Oracle stored procedure which creates partitioned tables based off of a table containing the table names and the column to be partitioned with. A separate PL/SQL block iterates through the table and calls the procedure with the table name and the column name.

Procedure:

create or replace PROCEDURE exec_multiple_table_create (      table_name  IN VARCHAR2,      column_name IN VARCHAR2  ) IS      stmt       VARCHAR2(5000);      tablename  VARCHAR2(50);      columnname VARCHAR2(50);  BEGIN      tablename := table_name;      columnname := column_name;  --    DBMS_OUTPUT.PUT_LINE(tablename);  --    DBMS_OUTPUT.PUT_LINE(columnname);      stmt := 'create table '              || TABLENAME              || '_temp as (select * from '              || COLUMNNAME              || ' where 1=2)';      EXECUTE IMMEDIATE stmt          USING IN table_name, column_name;      stmt := 'alter table '              || tablename              || '_temp modify partition by range('              || columnname              || ')              (PARTITION observations_past    VALUES LESS THAN (TO_DATE(''20000101'',''YYYYMMDD'')),                   PARTITION observations_CY_2000 VALUES LESS THAN (TO_DATE(''20010101'',''YYYYMMDD'')),                   PARTITION observations_CY_2001 VALUES LESS THAN (TO_DATE(''20020101'',''YYYYMMDD'')),                   PARTITION observations_CY_2002 VALUES LESS THAN (TO_DATE(''20030101'',''YYYYMMDD'')),                   PARTITION observations_CY_2003 VALUES LESS THAN (TO_DATE(''20040101'',''YYYYMMDD'')),                   PARTITION observations_CY_2004 VALUES LESS THAN (TO_DATE(''20050101'',''YYYYMMDD'')),                   PARTITION observations_CY_2005 VALUES LESS THAN (TO_DATE(''20060101'',''YYYYMMDD'')),                   PARTITION observations_CY_2006 VALUES LESS THAN (TO_DATE(''20070101'',''YYYYMMDD'')),                   PARTITION observations_CY_2007 VALUES LESS THAN (TO_DATE(''20080101'',''YYYYMMDD'')),                   PARTITION observations_CY_2008 VALUES LESS THAN (TO_DATE(''20090101'',''YYYYMMDD'')),                   PARTITION observations_CY_2009 VALUES LESS THAN (TO_DATE(''20100101'',''YYYYMMDD'')),                   PARTITION observations_CY_2010 VALUES LESS THAN (TO_DATE(''20110101'',''YYYYMMDD'')),                   PARTITION observations_FUTURE  VALUES LESS THAN ( MAXVALUE ) )';      EXECUTE IMMEDIATE stmt          USING IN table_name, column_name;      RETURN;      END exec_multiple_table_create;  

The PL/SQL block which is using the stored proc is:

BEGIN      FOR partition_item IN (          SELECT              table_name,              partition_column          FROM              partition_table      ) LOOP          exec_multiple_table_create(partition_item.table_name, partition_item.partition_column);      END LOOP;  END;  

Now, when I try executing the thing, this is what I am seeing:

Error report -  ORA-06550: line 9, column 9:  PLS-00905: object SCG_MYACCT_CUSTOMPC.EXEC_MULTIPLE_TABLE_CREATE is invalid  ORA-06550: line 9, column 9:  PL/SQL: Statement ignored  06550. 00000 -  "line %s, column %s:\n%s"  *Cause:    Usually a PL/SQL compilation error.  *Action:  

I have a feeling that I am missing something. Please let me know what it is. The table containing the reference data exists and contains data.

I have tried refreshing the table, rewriting and modifying the pl/sql block & the procedure code. Nothing seems to be working.

Thanks in advance.

UPDATE 1: There was a glitch in the stored procedure where I needed to refer to the tablename rather than the columnname in the code above. However, I am getting a different error right now.

Error report -  ORA-06546: DDL statement is executed in an illegal context  ORA-06512: at "SCG_MYACCT_CUSTOMPC.EXEC_MULTIPLE_TABLE_CREATE", line 18  ORA-06512: at line 9  ORA-06512: at line 9  06546. 00000 -  "DDL statement is executed in an illegal context"  *Cause:    DDL statement is executed dynamically in illegal PL/SQL context.             - Dynamic OPEN cursor for a DDL in PL/SQL             - Bind variable's used in USING clause to EXECUTE IMMEDIATE a DDL             - Define variable's used in INTO clause to EXECUTE IMMEDIATE a DDL  *Action:   Use EXECUTE IMMEDIATE without USING and INTO clauses to execute             the DDL statement.  

Please help me out with this as well.

UPDATE 2: I removed the USING part of the EXECUTE IMMEDIATE statement. That seemed to take care of the error I posted. Getting a different error with versions now:

Error starting at line : 1 in command -  BEGIN      FOR partition_item IN (          SELECT              table_name,              partition_column          FROM              partition_table      ) LOOP          exec_multiple_table_create(partition_item.table_name, partition_item.partition_column);      END LOOP;  END;  Error report -  ORA-00406: COMPATIBLE parameter needs to be 12.2.0.0.0 or greater  ORA-00722: Feature "Conversion into partitioned table"  ORA-06512: at "SCG_MYACCT_CUSTOMPC.EXEC_MULTIPLE_TABLE_CREATE", line 37  ORA-06512: at line 9  ORA-06512: at line 9  00406. 00000 -  "COMPATIBLE parameter needs to be %s or greater"  *Cause:    The COMPATIBLE initialization parameter is not high             enough to allow the operation. Allowing the command would make             the database incompatible with the release specified by the             current COMPATIBLE parameter.  *Action:   Shutdown and startup with a higher compatibility setting.  

React dependency warning from console log when using useEffect

Posted: 04 Jan 2022 05:05 AM PST

const [order, setOrder] = useState({});    useEffect(() => {      fetch(`https://localhost/services/${id}`)          .then(res => res.json())          .then(data => setOrder(data))    }, [])  

why filter result getting empty result?

Posted: 04 Jan 2022 05:05 AM PST

why I am getting empty result while apply date filter query . I am using mongoose as ORM. through mongo compass . i am getting correct result .but through mongoose it doesn't works

I am doing like this

console.log('-------------11-----------');        var a  = await this.orderModel          .where('assigned_user')          .equals(getLawyerAssignedOrderInput.user);          console.log("**************1********");        console.log(a);        console.log("**************2********");        console.log("**************244444444********");        console.log("**************5555********",new Date (getLawyerAssignedOrderInput.start_date.toString()));        console.log("**************6666********",getLawyerAssignedOrderInput.end_date.toString());        console.log("**************66666677777777********",getLawyerAssignedOrderInput.start_date);        console.log("**************66666677777777********",getLawyerAssignedOrderInput.start_date);        var b  = await this.orderModel          .where('assigned_user')          .equals(getLawyerAssignedOrderInput.user)          .where({            created_at: {              $gt: new Date(getLawyerAssignedOrderInput.start_date.toString()),              $lt:  new Date(getLawyerAssignedOrderInput.end_date.toString()),            },          })          console.log("**************2********");        console.log("**************b********");        console.log(b);  

a variable has correct value getting four or 4 collection object . but after date filter I am getting empty array why ?

my console output

**************1********  [    {      is_api_call_tried: false,      updated_at: 2022-01-03T13:00:11.569Z,      created_at: 2022-01-03T11:08:31.427Z,      order_frozen: false,      status: 2,      _id: 61d2d92e46e16328d033080b,      category_id: 'dGVybTozNQ==',      country_code: 91,      coupon_code: '',      coupon_code_discount_type: '',      coupon_discount: 0,      currency: 'INR',      discount: 33,      products: [ [Object] ],      subtotal: 50,      tax: 9,      total_amount: 59,      user: 61889ea9a67c2bafe7ebae88,      user_email: 'hrithikpvkr@icloud.com',      user_phone: 8894425572,      call_schedule: [],      required_documents: [],      deliverables: [],      __v: 0,      paytm_order_id: 'Order_43830PM',      paytm_transaction_token: 'd00b3d0aad22469db4ebe8346918a99f1641208111337',      razorpay_order_id: 'order_IfFONbvVGn3f6p',      payment_method: 9,      payment_status_gateway: true,      payment_status_user: true,      frozen_by: 'cron',      invoice_generation_date: 1641208501020,      invoice_id: 237,      invoice_url: 'https://ezylegal-uploaded-documents.s3.ap-south-1.amazonaws.com/1qyrh81641208501543.pdf',      assigned_date: 2022-01-03T13:00:11.569Z,      assigned_user: 617a111e35bc91fa7dcd5316    },    {      is_api_call_tried: false,      updated_at: 2022-01-03T11:24:50.445Z,      created_at: 2022-01-03T11:20:00.844Z,      order_frozen: false,      status: 2,      _id: 61d2dbe046e16328d0330863,      category_id: 'dGVybTozNQ==',      country_code: 91,      coupon_code: '',      coupon_code_discount_type: '',      coupon_discount: 0,      currency: 'INR',      discount: 33,      products: [ [Object] ],      subtotal: 50,      tax: 9,      total_amount: 59,      user: 618898f0a67c2bafe7ebad97,      user_email: 'solankiaman520@gmail.com',      user_phone: 9958936497,      call_schedule: [],      required_documents: [],      deliverables: [],      __v: 0,      paytm_order_id: 'Order_45000PM',      paytm_transaction_token: '95aec11ff241482ebbb0a789463d94fb1641208800723',      razorpay_order_id: 'order_IfFaW5iftxcxTI',      payment_method: 9,      payment_status_gateway: true,      payment_status_user: true,      assigned_date: 2022-01-03T11:24:50.445Z,      assigned_user: 617a111e35bc91fa7dcd5316    },    {      is_api_call_tried: false,      updated_at: 2022-01-03T12:56:39.634Z,      created_at: 2022-01-03T11:31:57.710Z,      order_frozen: false,      status: 2,      _id: 61d2dead46e16328d033090c,      category_id: 'dGVybTozNA==',      country_code: 91,      coupon_code: '',      coupon_code_discount_type: '',      coupon_discount: 0,      currency: 'INR',      discount: 63,      products: [ [Object], [Object], [Object] ],      subtotal: 89,      tax: 18,      total_amount: 107,      user: 618898f0a67c2bafe7ebad97,      user_email: 'solankiaman520@gmail.com',      user_phone: 9958936497,      call_schedule: [],      required_documents: [],      deliverables: [],      __v: 0,      paytm_order_id: 'Order_50157PM',      paytm_transaction_token: '2a260e03d902463d9cf8bd89d995d1cf1641209517600',      razorpay_order_id: 'order_IfFn8bpY8B944r',      payment_method: 9,      payment_status_gateway: true,      payment_status_user: true,      frozen_by: 'cron',      invoice_generation_date: 1641210120032,      invoice_id: 239,      invoice_url: 'https://ezylegal-uploaded-documents.s3.ap-south-1.amazonaws.com/ryonpo1641210120043.pdf',      assigned_date: 2022-01-03T12:56:39.634Z,      assigned_user: 617a111e35bc91fa7dcd5316    },    {      is_api_call_tried: false,      updated_at: 2022-01-04T05:48:52.504Z,      created_at: 2022-01-03T12:53:00.591Z,      order_frozen: false,      status: 2,      _id: 61d2f1ab46e16328d0330a88,      category_id: 'dGVybTozNQ==',      country_code: 91,      coupon_code: '',      coupon_code_discount_type: '',      coupon_discount: 0,      currency: 'INR',      discount: 14,      products: [ [Object] ],      subtotal: 20,      tax: 4,      total_amount: 24,      user: 618898f0a67c2bafe7ebad97,      user_email: 'solankiaman520@gmail.com',      user_phone: 9958936497,      call_schedule: [],      required_documents: [],      deliverables: [],      __v: 0,      paytm_order_id: 'Order_62259PM',      paytm_transaction_token: 'f5f3f364c7854cf587f4db8029d91ecf1641214380360',      razorpay_order_id: 'order_IfHAkLpMy7MHju',      payment_method: 9,      payment_status_gateway: true,      payment_status_user: true,      assigned_date: 2022-01-04T05:48:52.504Z,      assigned_user: 617a111e35bc91fa7dcd5316    }  ]  **************2********  **************244444444********  **************5555******** 2019-12-31T18:30:00.000Z  **************6666******** Mon Jan 03 2022  **************66666677777777******** Wed Jan 01 2020  **************66666677777777******** Wed Jan 01 2020  Mongoose: orders.find({ assigned_user: ObjectId("617a111e35bc91fa7dcd5316"), created_at: { '$gt': new Date("Tue, 31 Dec 2019 18:30:00 GMT"), '$lt': new Date("Sun, 02 Jan 2022 18:30:00 GMT") }}, { projection: {} })  **************2********  **************b********  []  

my collection structure

{"_id":{"$oid":"61d2d92e46e16328d033080b"},"is_api_call_tried":false,"updated_at":{"$date":"2022-01-03T13:00:11.569Z"},"created_at":{"$date":"2022-01-03T11:08:31.427Z"},"order_frozen":false,"status":2,"category_id":"dGVybTozNQ==","country_code":91,"coupon_code":"","coupon_code_discount_type":"","coupon_discount":0,"currency":"INR","discount":33,"products":[{"updated_at":{"$date":"2021-12-30T08:40:24.478Z"},"created_at":{"$date":"2021-12-30T08:40:24.478Z"},"status":0,"discount":40,"tax":9,"regular_price":83,"sale_price":50,"_id":{"$oid":"61d2d92e46e16328d033080c"},"amount":50,"assigned_user":{"$oid":"61889ea9a67c2bafe7ebae88"},"calltime_purchased":null,"product_id":"cHJvZHVjdF92YXJpYXRpb246NTA4","product_name":"Will - Document draft - Customize","deliverables":[]}],"subtotal":50,"tax":9,"total_amount":59,"user":{"$oid":"61889ea9a67c2bafe7ebae88"},"user_email":"hrithikpvkr@icloud.com","user_phone":8894425572,"call_schedule":[],"required_documents":[],"deliverables":[],"__v":0,"paytm_order_id":"Order_43830PM","paytm_transaction_token":"d00b3d0aad22469db4ebe8346918a99f1641208111337","razorpay_order_id":"order_IfFONbvVGn3f6p","payment_method":9,"payment_status_gateway":true,"payment_status_user":true,"frozen_by":"cron","invoice_generation_date":1641208501020,"invoice_id":237,"invoice_url":"https://ezylegal-uploaded-documents.s3.ap-south-1.amazonaws.com/1qyrh81641208501543.pdf","assigned_date":{"$date":"2022-01-03T13:00:11.569Z"},"assigned_user":{"$oid":"617a111e35bc91fa7dcd5316"}}  

any suggestion ?

Implementing Merge Sort algorithm

Posted: 04 Jan 2022 05:05 AM PST

def merge(arr,l,m,h):      lis = []      l1 = arr[l:m]      l2 = arr[m+1:h]      while((len(l1) and len(l2)) is not 0):          if l1[0]<=l2[0]:              x = l1.pop(0)          else:          x = l2.pop(0)          lis.append(x)      return lis    def merge_sort(arr,l,h): generating them      if l<h:          mid  = (l+h)//2          merge_sort(arr,l,mid)          merge_sort(arr,mid+1,h)          arr = merge(arr,l,mid,h)      return arr    arr = [9,3,7,5,6,4,8,2]  print(merge_sort(arr,0,7))  

Can anyone please enlighten where my approach is going wrong ? I get only [6,4,8] as the answer. I'm trying to understand the algo and implement the logic my own way. Please help.

bartlett fourier transform has strange peaks

Posted: 04 Jan 2022 05:05 AM PST

I am trying to compute and plot the DTFT of bartlett window in dB scale but strange peaks appear instead of the round ones. I first compute the DTFT transform of the window, I am also shifting the DTFT and freqs, I compute the abs of the DTFT and I normalize the values of the shifted DTFT but the strange shapes/peaks appear as seen in the image below. I know that the DTFT of bartlett window is smoother. Am I doing something wrong?

N = 100  lobeWidth = 1 / fo  # creating the barlett window  bartlett = windows.bartlett(N,  sym = True)  plt.plot(bartlett)  plt.show()    bartlett_fft = np.fft.fft(bartlett)  bartlett_freq = freq(bartlett_fft.shape[-1])    db_psd = 10 * np.log10(np.abs(shift((bartlett_fft + 0.00000000000001) / abs(bartlett_fft).max())))  plt.plot(shift(bartlett_freq), db_psd)  plt.show()  

strange bartlett window

primereact functionality of adding a new row in DataTable

Posted: 04 Jan 2022 05:05 AM PST

is there any way of adding a new row on button click in datatable in primereact like in primefaces. i didn't found any functionality in primereact in documentation however there is option available in primefaces. https://www.primefaces.org/primereact/datatable/

Laravel Vue add Vue-router to component

Posted: 04 Jan 2022 05:05 AM PST

I need add Vue router in Laravel project with Vue 3. I have multiple components, which im using in laravel blade but i need add router to only one of them(not to whole Vue app). Its possible?

Thanks

EDIT:

app.js

import { createApp, defineAsyncComponent } from 'Vue';    const app = createApp({      components: {          ReferenceList: defineAsyncComponent(() =>              import('./components/ReferenceList.vue')          ),          OnlineView: defineAsyncComponent(() =>              import('./components/OnlineView.vue')          ),      },  });    app.mount('#app');  

OnlineView.vue

<template>      <div>          <h1>Router app</h1>      </div>  </template>    <script>  import { reactive, toRefs } from 'vue'    export default {      setup () {          const state = reactive({              count: 0,          })                return {              ...toRefs(state),          }      }  }  </script>    

master.blade.php

<main id="app">      @yield('content')  </main>  

reference.blade.php

...      <reference-list />  ...  

online.blade.php

...      <online-view />  ...  

How is HttpServletResponse entangled with the fetch API when making a GET request for a BLOB?

Posted: 04 Jan 2022 05:06 AM PST

Using Spring Boot, I am trying to implement a REST controller, which can handle a GET request asking to return a BLOB object from my database.

Googling around a little bit, and putting pieces together, I have created the following code snippet:

@GetMapping("student/pic/studentId")  public void getProfilePicture(@PathVariable Long studentId, HttpServletResponse response) throws IOException {      Optional<ProfilePicture> profilePicture;      profilePicture = profilePictureService.getProfilePictureByStudentId(studentId);      if (profilePicture.isPresent()) {          ServletOutputStream outputStream = response.getOutputStream();          outputStream.write(profilePicture.get().getPicture());          outputStream.close();      }  }  

I am sending the GET request using VanillaJS and the fetch-API:

async function downloadPicture(profilePic, studentId) {    const url = "http://localhost:8080/student/pic/" + studentId;    const response = await fetch(url);    const responseBlob = await response.blob();    if (responseBlob.size > 0) {      profilePic.src = URL.createObjectURL(responseBlob);    }   }  

Somehow, this works. That's great, but now I would like to understand the usage of HttpServletResponse in this context, which I am not familiar with. It seems to me that the fetch-API makes use of HttpServletResponse (maybe even creates it), since I am not creating this object or do anything with it.

What is very strange to me is that the return-type of my controller method getProfilePicture() is void, and still I am sending a response, which is most definitely not void.

Also, if the profilePicture was not found in my database, for example due to a non-existing studentId being passed, my controller-method does not do anything. But still, I am getting a response code of 200. That's why I have added the responseBlob.size > 0 part in my Javascript to check for a positive response.

Can someone explain this magic to me, please?

Write splunk query to fetch the number of working days greater than zero

Posted: 04 Jan 2022 05:06 AM PST

I am trying to write a splunk query where I need to fetch the user details with the number of working days if it is greater than zero. For example I have the below data

I, [2022-01-04T01:32:10.165065 #21461]  INFO -- : fetched user details for user_id: 5612 with working_days: 0    I, [2021-01-04T01:32:10.165065 #21461]  INFO -- : fetched user details for user_id: 5619 with working_days: 10    I, [2021-02-04T01:28:10.165065 #21461]  INFO -- : fetched user details for user_id: 8901 with working_days: 0    I, [2021-03-04T01:18:10.165065 #21461]  INFO -- : fetched user details for user_id: 306561 with working_days: 35  

I need to fetch user_id along with working_days. The only condition is working days more than 0

fetched user details for user_id: 5619 with working_days: 10  fetched user details for user_id: 306561 with working_days: 35  

The below query is not giving the correct result. Any help is appreciated

"fetched user details for user_id: "   | rex field=_raw "fetched user details for user_id:(?<user_id>.*) with working_days:(?<working_days>.*)"   | table user_id,working_days  

Update 1

I have tried following ways but none of it works

"fetched user details for user_id: "   | rex field=_raw "fetched user details for user_id:(?<user_id>.\d+) with working_days:(?<working_days>.\d+)"   | where working_days > 0 | table user_id,working_days    "fetched user details for user_id: "   | rex field=_raw "fetched user details for user_id:(?<user_id>.\d+) with working_days:(?<working_days>.\d+)"   | where 'working_days' > 0 | table user_id,working_days    "fetched user details for user_id: "   | rex field=_raw "fetched user details for user_id:(?<user_id>.\d+) with working_days:(?<working_days>.\d+)"   | where working_days > '0' | table user_id,working_days    "fetched user details for user_id: "   | rex field=_raw "fetched user details for user_id:(?<user_id>.\d+) with working_days:(?<working_days>.\d+)"   | where "working_days" > '0' | table user_id,working_days    "fetched user details for user_id: "   | rex field=_raw "fetched user details for user_id:(?<user_id>.\d+) with working_days:(?<working_days>.\d+)"   | where not working_days == 0 | table user_id,working_days  

i have promoted GraphicsLayoutWidget in QT Designer and custom X Axes- need to hide middle tickts to keep space between overlapped custom tickts

Posted: 04 Jan 2022 05:05 AM PST

hello to everyone and Happy New Year) does anybody know how to work with custom AxisItems in GraphicsLayoutWidget - i have X axis with many of time tickts on it, and while scaling needs to hide middle tickts to keep distance between them(because they starts to overlapping...) here is my example screenshot and also code:

from PyQt5 import QtWidgets, uic  import pyqtgraph as pg    app = QtWidgets.QApplication([])  ui = uic.loadUi("try.ui")      def DRAW(xtickts, xValue, listY):      graph = ui.widgetGraph      size_of_graph = graph.size()      bottomAxis = pg.AxisItem(maxTickLength=3, orientation='bottom', linkView = size_of_graph)      pp = ui.widgetGraph.addPlot(axisItems={'bottom': bottomAxis})      pp.plot(xValue, listY)      bottomAxis.setTicks(xtickts)      listY = [0, 0, 0, 0, 11, 0, 6, 0, 0, 0, 15, 0, 0, 0, 0, 0, 6, 12, 0, 0, 0]  listX = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]    xtickts = [([(0, '13:51'), (1, '13:52'), (2, '13:53'), (3, '13:54'), (4, '13:55'), (5, '13:56'),               (6, '13:57'), (7, '13:58'), (8, '13:59'), (9, '14:00'), (10, '14:01'), (11, '14:02'),               (12, '14:03'), (13, '14:04'), (14, '14:05'), (15, '14:06'), (16, '14:07'), (17, '14:08'),               (18, '14:09'), (19, '14:10'), (20, '14:11')])]    DRAW(xtickts, listX, listY)    ui.show()  app.exec()  

Priority Version Number

Posted: 04 Jan 2022 05:06 AM PST

Is there a way to get the Priority Version number via the Web SDK or REST API?

Specifically I need to be able to know which side of a breaking change a particular version is at to know how to proceed.

How to add a second example app to a Flutter plugin project?

Posted: 04 Jan 2022 05:05 AM PST

When creating a plugin project in Flutter, an example app, that is using the plugin, is added in a subfolder of the plugin project. What needs to be done to add a second "example" app to the plugin folder?

So far I have:

  1. Copied and renamed the example folder to (let's call it) app2.

  2. Adjusted the package names at the android manifest files of app2.

  3. Renamed pluginrootfolder/app2/pluginname_example.iml to pluginrootfolder/app2/pluginname_app2.iml (to reflect the name of the second app).

  4. In the .iml file of the plugin project (the root folder): Copied and adjusted the exclude folder directive to reflect app2

      <excludeFolder url="file://$MODULE_DIR$/app2/.dart_tool" />    <excludeFolder url="file://$MODULE_DIR$/app2/.pub" />    <excludeFolder url="file://$MODULE_DIR$/app2/build" />  
  5. Run Flutter clean and Flutter pub get in both the plugins root directory and app2's directory.

Problem now is that app2 causes 1k+ Target of URI doesn't exist: error messages - from packages (like provider and json_annotation) to classes in the plugin's root project. Do you have any ideas what's wrong here or how to fix it?

Angular TSLint - Cannot find builder "@angular-devkit/build-angular:tslint"

Posted: 04 Jan 2022 05:05 AM PST

When I try to run command ng lint --fix cli throws this error:

An unhandled exception occurred: Cannot find builder "@angular-devkit/build-angular:tslint".  See "C:\Users\MOE89A~1.ZAR\AppData\Local\Temp\ng-Ijc3an\angular-errors.log" for further details.  

My lint confing in angular.json:

"lint": {    "builder": "@angular-devkit/build-angular:tslint",    "options": {      "tsConfig": [        "projects/wepod-app/tsconfig.app.json",        "projects/wepod-app/tsconfig.spec.json",        "projects/wepod-app/e2e/tsconfig.json"      ],      "exclude": [        "**/node_modules/**"      ]    }  },  

My package.json:

{    "name": "wepod-clients",    "version": "3.2.3",    "scripts": {      "ng": "ng",      "start": "node patch.js && ng serve",      "build": "node patch.js && node --max_old_space_size=8192 ./node_modules/@angular/cli/bin/ng run wepod-app:app-shell:production && ng run wepod-app:auth-standalone:production",      "server": "npm run build && http-server -p 9090 -c-1 dist",      "test": "ng test",      "lint": "ng lint --fix",      "e2e": "ng e2e",      "postinstall": "node patch.js && ngcc",      "postbuild": "node post-build.js",      "prepare": "husky install",      "build-latest": "git pull origin production && npm run build"    },    "private": true,    "dependencies": {      "@angular/animations": "^13.0.0",      "@angular/cdk": "^13.0.0",      "@angular/cli": "^13.0.1",      "@angular/common": "^13.0.0",      "@angular/compiler": "^13.0.0",      "@angular/core": "^13.0.0",      "@angular/forms": "^13.0.0",      "@angular/localize": "^13.0.0",      "@angular/platform-browser": "^13.0.0",      "@angular/platform-browser-dynamic": "^13.0.0",      "@angular/platform-server": "^13.0.0",      "@angular/router": "^13.0.0",      "@angular/service-worker": "^13.0.0",      "@types/video.js": "^7.3.27",      "animate.css": "^4.1.1",      "assert": "^2.0.0",      "bowser": "^2.11.0",      "buffer": "^6.0.3",      "bundle-loader": "^0.5.6",      "compare-version": "^0.1.2",      "constants-browserify": "^1.0.0",      "crypto-browserify": "^3.12.0",      "crypto-js": "^4.1.1",      "d3": "^6.5.0",      "hammerjs": "^2.0.8",      "https-browserify": "^1.0.0",      "jalali-moment": "^3.3.10",      "lottie-web": "^5.7.13",      "lzutf8": "^0.6.0",      "net": "^1.0.2",      "ng-gallery": "^5.1.1",      "ng2-jalali-date-picker": "^2.4.2",      "ngx-device-detector": "^1.5.2",      "ngx-doughnut-chart": "0.0.4",      "ngx-infinite-scroll": "^8.0.2",      "ngx-lottie": "^7.0.4",      "ngx-owl-carousel-o": "^3.1.1",      "ngx-skeleton-loader": "^2.10.1",      "ngx-toastr": "^12.1.0",      "os-browserify": "^0.3.0",      "podchat-browser": "^10.14.13",      "rxjs": "^6.6.7",      "stream-browserify": "^3.0.0",      "stream-http": "^3.2.0",      "tls": "0.0.1",      "tslib": "^2.0.0",      "uuid": "^8.3.2",      "video.js": "^7.15.4",      "videojs-record": "^4.5.0",      "zone.js": "~0.11.4"    },    "devDependencies": {      "@angular-devkit/build-angular": "^13.0.1",      "@angular-devkit/core": "^13.0.1",      "@angular/compiler-cli": "^13.0.0",      "@angular/language-service": "^13.0.0",      "@egjs/hammerjs": "^2.0.17",      "@types/hammerjs": "^2.0.40",      "@types/jasmine": "~3.6.0",      "@types/jasminewd2": "^2.0.10",      "@types/node": "^12.20.36",      "codelyzer": "^6.0.0",      "colors": "^1.4.0",      "git-tag-version": "^1.3.1",      "gulp": "^4.0.2",      "gulp-gzip": "^1.4.2",      "http-server": "^14.0.0",      "husky": "^7.0.4",      "jasmine-core": "~3.6.0",      "jasmine-spec-reporter": "~5.0.0",      "karma": "^6.3.7",      "karma-chrome-launcher": "~3.1.0",      "karma-coverage-istanbul-reporter": "^2.1.0",      "karma-jasmine": "~4.0.0",      "karma-jasmine-html-reporter": "^1.5.0",      "protractor": "^7.0.0",      "ts-node": "^8.10.2",      "tslint": "^6.1.3",      "typescript": "4.4.4",      "zip-dir": "^2.0.0"    },    "browser": {      "fs": false,      "path": false,      "os": false    }  }  

How to export data as csv format from Druid that already exits in the Druid?

Posted: 04 Jan 2022 05:06 AM PST

I loaded data (almost 1-billion row data) from hdfs (Hadoop) to Apache Druid. Now, I am trying to export this data set as a CSV to my local. Is there any way to do this in Druid?

There is a download icon on the druid SQL. However, when you click it, it allows you to download the data up to which page you are on. I have soo many pages, so I cannot go through all pages to download all data.

How to stream audio data from Android to WebSocket server?

Posted: 04 Jan 2022 05:05 AM PST

I've working on RTC mobile app. I have a nodejs server over a WebSocket connection - I got the connection. But I'm really confusing about how to stream audio in kotlin. MediaCodec or AudioRecord? I've ready the docs, but I confess I don't know how to proceed. Thanks!

"interrupted by signal 5: SIGTRAP" Android emulator - macos

Posted: 04 Jan 2022 05:06 AM PST

Trouble with emulator on my Mac.I got the message say :

"Emulator: Process finished with exit code 133 (interrupted by signal 5: SIGTRAP)"

I tried almost everything, reinstall android studio ...

Any suggest.

How to force cpanm to use HTTPS insted of Using HTTP for installing dependencies

Posted: 04 Jan 2022 05:05 AM PST

Hi I am trying to install perl modules using cpanm.But my firewall is not letting the cpanm to use http. Even when I am forcing it to use https using the --mirror option, its still uses http to install the dependencies. How can i force cpanm to use only https://mirror-address .

Perl Version 5.16.3  Cpanm Version 1.6922  

How can I dynamically resize an SVG rect based on text width?

Posted: 04 Jan 2022 05:05 AM PST

In an SVG graph I create node elements consisting of a rectangle and some text. The amount of text can differ significantly, hence I'd like to set the width of the rect based on the width of the text.

Here's the creation of the rectangles with D3.js (using fixed width and height values):

var rects = nodeEnter.append("rect")      .attr("width", rectW)      .attr("height", rectH);  

followed by the text element:

var nodeText = nodeEnter.append("text")      .attr("class", "node-text")      .attr("y", rectH / 2)      .attr("dy", ".35em")      .text(function (d) {          return d.data.name;      });  nodeText // The bounding box is valid not before the node addition happened actually.      .attr("x", function (d) {          return (rectW - this.getBBox().width) / 2;      });  

As you can see, currently I center the text in the available space. Then I tried to set the widths of the rects based on their text, but I never get both, the rect element and the text HTML element (for getBBox()) at the same time. Here's one of my attempts:

rects.attr("width",          d => this.getBBox().width + 20      );  

but obviously this is wrong as it refers to rects not the text.

What's the correct approach here?

How to exclude multiple properties in FluentAssertions ShouldBeEquivalentTo()

Posted: 04 Jan 2022 05:05 AM PST

Using FluentAssertions:
I'm able to exclude a single property using ShouldBeEquivalentTo.

x.ShouldBeEquivalentTo(y, opts => opts.Excluding(si => !si.PropertyInfo.CanWrite));  

But, how do I exclude more then 1 property when using ShouldBeEquivalentTo() ?

Docker Swarm Service - force update of latest image already running

Posted: 04 Jan 2022 05:06 AM PST

environment

  • docker 1.12
  • clusted on Ubuntu 16.04

Is there a way to force a rolling update to a docker swarm service already running if the service update is not changing any parameters but the docker hub image has been updated?

Example: I deployed service:

docker service create --replicas 1 --name servicename --publish 80:80 username/imagename:latest  

My build process has updated the latest image on docker hub now I want to pull the latest again.

I have tried running:

docker service update --image username/imagename:latest servicename  

When I follow this process, docker does not pull the latest, I guess it assumes that since I wanted latest and docker already pulled an image:latest then there is nothing to do.

The only work around I have is to remove the service servicename and redeploy.

No comments:

Post a Comment