Thursday, February 17, 2022

Recent Questions - Stack Overflow

Recent Questions - Stack Overflow


Flutter: Get last word before truncation for Text Widget in Flutter

Posted: 17 Feb 2022 12:56 PM PST

I have a multi-line body of text which I want to split across screens. I am using the Text widget with overflow property like this:

Text(      body,      style: Theme.of(context).textTheme.bodyText2,      maxLines: 8,      overflow: TextOverflow.ellipsis,    );  

Now, on the next page, I want to start the text from the word where the previous page got truncated. For example, for the body 'Hello, nice to meet you all. Hope you have a good day!', this is what it would look like:

On Page 1:

Hello, nice to meet you all. Hope...  

On Page 2:

...you have a good day!  

Now, I am trying to find a way for the Text widget to tell me where it truncated the text on Page 1. Anybody got any suggestions on how to go about it?

activeclassname react tailwind not working

Posted: 17 Feb 2022 12:55 PM PST

I am trying to create an active class for the navbar link by the text does dnot change after selection. just wondering where i might be going wrong

            exact              to="/"              activeClassName="text-white"              className="inflex-flex items-center py-6 px-3 mr-4 text-               red-200 hover:text-green-800 text-4xl font-bold cursive               tracking-widest"              activeClassName="text-black"            >              Home            </NavLink>            <NavLink              to="/project"              className="inline-flex items-center py-3 px-3 my-6 rounded text-red-200 hover:text-green-800"              activeClassName="text-red-100 bg-red-700"            >              Projects            </NavLink>            <NavLink              to="/post"              className="inline-flex items-center py-3 px-3 my-6 rounded text-red-200 hover:text-green-800"              activeClassName="text-red-100 bg-red-700"            >              Blog Posts            </NavLink>            <NavLink              to="/about"              className="inline-flex items-center py-3 px-3 my-6 rounded text-red-200 hover:text-green-800"              activeClassName="text-red-100 bg-red-700"            >```    

List of element wit fixed size independent of content and icon on the right side

Posted: 17 Feb 2022 12:55 PM PST

I'm really bad at css and I've been scratching my head all day tried to do something very simple. Google was not helpful (but maybe because I don't know even how to ask the question)

The problem is the following:

I need to show a list of urls and an icon to "delete" the url. But I can not make that the icon is in the same position, independent of the size of the url text. Big texts are no problem because I can remove the last characters (for example, making all urls at most 20 characters), but the problem is when the url is short, and the Delete Icon move to the left

This is how I need it

enter image description here

This is how it is showing now

enter image description here

Any clue of how I can show the icons aligned?

How to create stylesheet file to PySide6 PyQt

Posted: 17 Feb 2022 12:55 PM PST

I started to make a GUI for an app with PyQt and I completed it . when I tried to style the application I started to style its elements one by one with :

object.setStyleSheet('''color : #FFFFFF;                          somecode...''')  

but I see this as a useless method , Is there anyway to style the app with another method ? and how to do that ?

What is the diff between this two arrow functions?

Posted: 17 Feb 2022 12:55 PM PST

Basically, I don't understand why the second arrow function works, and first doesn't.

    //this one doesnt      this.setState = () => {              text: e.target.value,          };          //this one works      this.setState(() => ({              text: e.target.value,          }));  

Numpy - Product of All Unique Combinations or Paths along an axis

Posted: 17 Feb 2022 12:55 PM PST

Given a 2D array, I would like to find the product of all unique "combinations" or "paths" along the last axis.

If the starting array is

[[1, 2, 3, 4, 5, 6],   [7, 8, 9, 10, 11, 12]]  

Then the unique combinations along the last axis would be

[[1, 2, 3, 4, 5, 6],   [1, 2, 3, 4, 5, 12],   [1, 2, 3, 4, 11, 6],   [1, 2, 3, 4, 11, 12],   ...,   [7, 8, 9, 10, 11, 6],   [7, 8, 9, 10, 11, 12]]  

And then you can apply numpy.prod(, axis=-1). However, is there a faster/more efficient way to retrieve these unique combinations without manually iterating through?

Can't pass through "" to powershell using ProcessStartInfo arguments, C#

Posted: 17 Feb 2022 12:55 PM PST

I'm unable to pass through an argument to powershell which contains "". When I use the equivalent code but change the application to cmd the "" are able to pass through.

The argument I'd like powershell to execute is:

Copy-Item -Path "{Working Directory}\W11F-assets\" -Destination "C:\\Windows\W11F-assets" -Recurse        ProcessStartInfo movefile = new ProcessStartInfo("powershell.exe");      string flocation = Directory.GetCurrentDirectory();      movefile.UseShellExecute = true;      movefile.Arguments = "Copy-Item -Path \"" + flocation + "\\W11F-assets\" -Destination \"C:\\Windows\\W11F-assets\" -Recurse";      Process.Start(movefile);  

Is this a valid use of std::forward?

Posted: 17 Feb 2022 12:55 PM PST

My question is if this is a valid use of std::forward (See attached picture). I have a function that accepts a r-value string reference as a parameter. The string contains an SQL query that I forward to another function that executes said query. It works but I'm just wondering if it is good practice. In most cases I would just use a const char* instead of a string but this is a special case.

Here is the code:

void Database::InjectQuery(const std::string&& query)    {    pstmt = con->prepareStatement(std::forward<const std::string>(query));    pstmt->execute();    Entries.clear();    std::cout << "DATABASE_LOG: Query Successfully Executed\n";    }  

Upload simple html file to internet [closed]

Posted: 17 Feb 2022 12:55 PM PST

I'm trying to get a website on the internet through html an css files; not even any js files. They are really simple scripts but just as a birthday present for someone. Probably not more than 1 visit at a time. I have some html files for other urls(/info /contact and so on). And one css file for them all. I have thought about buying a .de domain from google domains but it seems I need more tools like a web hosting service and file transfer protocol and something. I don't want a website builder or anything fancy because I already have all my html and css files ready. Are there some cheap options for simply uploading these files to the different urls to the internet. What do I have to do?

How do I use getline to read from a file and then tokenize it using strtok?

Posted: 17 Feb 2022 12:55 PM PST

I want my program to read words from a file using getline, and then tokenize them using strtok and put it into a two-dimensional array.

I've tried using these threads/sites to refer to for help.

site_1 another stack overflow thread

#include <iostream>  #include <fstream>  #include <cstring>  using namespace std;            int main(int argc, char **argv)      {          char words[100][16]; //Holds the words          int uniquewords[100]; //Holds the amount of times each word appears          int counter; //counter                if (argc = 2)          {              cout << "Success";          }          else          {              cout << "Please enter the names of the files again. \n";              return 1;          }                ifstream inputfile;          ofstream outputfile;                inputfile.open(argv[1]);          outputfile.open(argv[2]);                char *token;          while(inputfile.getline(words, 100))          {              token = strtok(words[100][16], " ");              cout << token;          }      }  

The error message I'm getting is

error: no matching function to call to 'std::basic_ifstream<char>::getline(char [100][16], int)

Apologies if I didn't format the code properly.

Remove duplicate values from array of ObjectIds in MongoDB

Posted: 17 Feb 2022 12:55 PM PST

I have a field on my user documents called _badges which are ObjectIds. I am attempting to remove duplicate values in the array and have been successful using async iterators via Mongoose script but that is a bit too slow for my liking:

async function removeDuplicateBadges() {    // Use async iterator to remove duplicate badge ids    for await(const userDoc of User.find()) {      console.log(userDoc.displayName)      const badgesStringArray = userDoc._badges.map(badge => {        if(badge === null) return        else return badge.toString()      })      const uniqueBadgesArray = [...new Set(badgesStringArray)]      await User.findByIdAndUpdate(        userDoc._id,        {          _badges: uniqueBadgesArray        }      )    }  }  

I tried doing the same using the following aggregation command but that did not seem to remove the duplicate values:

db.getCollection("users").aggregate(      [          {               "$unwind" : {                   "path" : "$_badges"              }          },           {               "$group" : {                   "_id" : "$_id",                   "_badges" : {                       "$addToSet" : "$_badges"                  }              }          }      ])       

Any hints on effective ways to remove duplicate values would be appreciated that are better time efficiency than using the async iterator methodology above.

I need a function to automate the categorization of the number of employees for every company in each year from 2015 to 2020 [closed]

Posted: 17 Feb 2022 12:56 PM PST

I am working on sheet 3 and sheet 4, I need to create a function which picks values of employees from sheet 3 to sheet 4 recognizing the TICKER of every different company in the list and also the year to which the specific number of employees corresponds.

For example in sheet 4, when working on ticker VOW I need to pick the number corresponding to the right year for VOW employees from sheet 3 and fix it for all 2015, then start again for 2016 and so on till 2020.

I tried many combination of VLOOKUP and HLOOKUP plus INDEX function combined with IF, but I haven't been able to solve this problem. I thank you all for your time and help!

sheet 3

sheet4

How to ignore tag inside RegExp

Posted: 17 Feb 2022 12:56 PM PST

In my project, we use a RegExp to display the title of cards that we receive from the deck. And recently I found that from the deck side we sometimes receive different formats and the titles didn't display.

So, before it was always a string like this:

const res =    `<p class="cardTitle" style="font-size: 27.2px">      <span>Some text here</span><span> - Title</span>     </p>`;  

and the RegExp was:

/<p class="cardTitle"[^>]*>[\s]*<span[^>]*>(.+)<\/span><span[^>]*>(.+)<\/span><div[^>]*>(.+)<\/div>+[\s]*<\/p>/i.exec(res);  

Now sometimes we receive res with div and <br> tags inside

const res =     `<p class="cardTitle" style="font-size: 27.2px">      <span>Some text here</span><span> - Title</span>      <div style="font-size: 10px">Title:<br>Some text here</div>     </p>`;  

The question is, how to change the RegEx to ignore this <div>..<br>.</div>?

Here's a demo:

const res =    `<p class="cardTitle" style="font-size: 27.2px">      <span>Some text here</span><span> - Title</span>     </p>`;       const newRes =    `<p class="cardTitle" style="font-size: 27.2px">      <span>Some text here</span><span> - Title</span>      <div style="font-size: 10px">Title:<br>Some text here</div>     </p>`;       const regEx = /<p class="cardTitle"[^>]*>[\s]*<span[^>]*>(.+)<\/span><span[^>]*>(.+)<\/span>+[\s]*<\/p>/i;       const correct = regEx.exec(res);  const broken = regEx.exec(newRes);     console.log('correct', correct);  console.log('broken', broken);

Would be really grateful for any help!

Shopify CLI: Best way to update Ruby for Shopify on OSX 11?

Posted: 17 Feb 2022 12:55 PM PST

PROBLEM

While pulling theme changes, I see a warning the "environment Ruby is outside of the range supported by the CLI".

  • Shopify CLI 2.11.2
  • Ruby 2.6.3
  • Homebrew 3.3.15
  • Mac OSX 11.6.1

THINGS TRIED

Searching revealed conflicting answers about how to update Ruby on OSX. I also updated Brew/Shopify CLI and also tried updating Ruby via Brew using...

$ brew upgrade ruby

But saw another warning...

Warning: ruby 3.1.0 already installed

So assume the OSX version of Ruby is overriding the brew version? Not sure, I have zero Ruby knowledge sorry.


QUESTIONS

  1. What's best way to update Ruby specifically for use with Shopify CLI on OSX 11?

Any help or suggestions welcome. Cheers

SwiftUI when can i use if statement in result builder?

Posted: 17 Feb 2022 12:55 PM PST

I notice that sometimes I am able to use if-else statement in SwiftUI's result builder just fine. For example, inside a body:

struct MyView: View {    var body: some View {      if foo {        Text("foo")      }     }  }  

However, sometimes I can't, for example, inside view modifier:

  func body(content: Content) -> some View {      content        .toolbar {          if foo { Button("foo") {} }        }      }    }  

This above gives me error saying:

Closure containing control flow statement cannot be used with result builder 'ToolbarContentBuilder'  

This is so confusing. Why are they different? When can I use if-else, and when it should be avoided (and in that case, why is it bad? and what should I do? )

Edit:

I tried to put the button under a Group {} under the toolbar. It's not working either:

      .toolbar {          Group {            if true { // can't put if here              Button("foo")  

Got this error:

Closure containing control flow statement cannot be used with result builder 'CommandsBuilder'  

Extracting text from JATS XML file using Dart

Posted: 17 Feb 2022 12:55 PM PST

I'm trying to extract extract data from a scientific journal (provided in JSON format) however one value of the JSON (key = abstract) is returned in a JATS-XML format, the standardized XML format for scientific research publications.

"abstract": "<jats:title>Summary</jats:title>\n             <jats:sec>\n                  <jats:title>Objective</jats:title>\n                <jats:p>To systematically evaluate all the evidence assessing variations in the depth of the curve of Spee (COS) according to the presence/absence of different dentoskeletal characteristics.</jats:p>\n             </jats:sec>\n               <jats:sec>\n                <jats:title>Search methods and eligibility criteria</jats:title>\n                <jats:p>The eligibility criteria were outlined following the PECO framework, as follows: studies evaluating individuals with complete permanent dentition including second molars (P), which compared a group with a certain dentoskeletal variation (E) versus another group without the variation (C), regarding the depth of the COS (O). MEDLINE (via PubMed), Scopus, Web of Science, The Cochrane Library, LILACS and BBO (via Virtual Health Library), OpenGrey, and Google Scholar were searched up to September 2021 to identify eligible reports.</jats:p>\n             </jats:sec>\n               <jats:sec>\n                <jats:title>Data collection and analysis</jats:title>\n                <jats:p>Duplicates were removed from all the records retrieved. The selection process and data collection were performed independently by two review members. The risk of bias was also assessed independently and in duplicate, using the guideline described by Fowkes and Fulton. Several meta-analyses (α = 0.05) were conducted to estimate the mean differences (MD) or standardized mean differences (SMD) in the depth of COS between individuals presenting or not certain dentoskeletal characteristics. The certainty of evidence was assessed using the GRADE tool.</jats:p>\n               </jats:sec>\n             <jats:sec>\n                  <jats:title>Results</jats:title>\n                <jats:p>Thirty-five studies were selected for qualitative synthesis, and 29 of them for quantitative synthesis. All studies had methodological limitations that affected the risk of bias and increased the likelihood that results were due to chance. Syntheses showed that Class II malocclusion (SMD = 0.87; 95% CI: 0.61, 1.13; P &amp;lt; 0.00001; six datasets including 260 subjects analysed), Class II division 1 (SMD = 1.09; 95% CI: 0.62, 1.56; P &amp;lt; 0.00001; 14 datasets including 823 subjects analysed) and Class II division 2 (SMD = 2.65; 95% CI: 1.51, 3.79; P &amp;lt; 0.00001; eight datasets including 476 subjects analysed) had deeper COS than Class I malocclusion. The skeletal Class II also presented higher COS values than skeletal Class I (SMD = 0.57; 95% CI: 0.02, 1.12; P = 0.04; four datasets including 299 subjects analysed). Individuals with Class III malocclusion had flatter COS than the subjects having Class I malocclusion (SMD = −0.57; 95% CI: −1.07, −0.08; P = 0.02; nine datasets including 505 individuals analysed). No difference was shown in the COS depth between skeletal Class III and Class I (P &amp;gt; 0.05). Deep bite individuals had higher COS depth than those with normal overbite (MD = 0.61; 95% CI: 0.41, 0.82; P &amp;lt; 0.00001; two datasets including 250 subjects analysed). In addition, hypodivergent individuals presented deeper COS than normodivergents (SMD = 0.62; 95% CI: 0.37, 0.86; P &amp;lt; 0.00001; six datasets including 305 subjects analysed), and there was no significant difference in the COS depth between hyperdivergent and normodivergent individuals (P = 0.66). The certainty of evidence was rated as very low for all the syntheses.</jats:p>\n               </jats:sec>\n               <jats:sec>\n                <jats:title>Limitations</jats:title>\n                  <jats:p>All the quantitative syntheses included results from studies with methodological flaws. Therefore, they are potentially biased. Moreover, the evidence was also mainly affected in terms of the inconsistency of the results and the imprecision of the estimates.</jats:p>\n               </jats:sec>\n             <jats:sec>\n                  <jats:title>Conclusions</jats:title>\n                <jats:p>Although an apparent influence of dentoskeletal Class II, Class III malocclusion, deep bite, and the hypodivergent skeletal pattern on the depth of the COS is suggested, it is not possible to make definitive conclusions on the matter due to the very low certainty of the evidence. Further high-quality research is necessary.</jats:p>\n               </jats:sec>"  

I have tried using the Dart XML package but without any luck.

import 'package:flutter/material.dart';  import 'package:http/http.dart' as http;  import 'dart:convert';  import 'package:deep_pick/deep_pick.dart';  import 'package:xml/xml.dart';      Future<void> main() async {    final response =        await http.get(Uri.parse( < api > ));    final json = jsonDecode(response.body);    final abstract = pick(json, 'abstract').asStringOrThrow();     final abstractParse = XmlDocument.parse(abstract);  print(XmlDocument.parse(abstract).toXmlString(pretty: true));  

Call dynatrace.gradle groovy function from kotlin

Posted: 17 Feb 2022 12:56 PM PST

I have a gradle script dynatrace.gradle, which contains some functions

apply plugin: 'com.dynatrace.instrumentation'  dynatrace {      configurations {          sampleConfig {              autoStart {                  applicationId 'getApplicationId()'                  beaconUrl 'getBeaconUrl()'              }          }      }  }    def getApplicationId(){  ...  }  

I want to call this getApplicationId() function from Kotlin class also. Is there any way to achieve this in Android application?

.Net Core Windows Authentication Login

Posted: 17 Feb 2022 12:55 PM PST

We are trying to make an internal application with .Net Core 5 MVC. Due to the application is internal, we want to make logins with Windows authentication.

We tried to follow microsoft link. We can get the user as domain/user with WindowsIdentity.GetCurrent().Name. But we want to define couple domain/user s and let only them to use the app. Can we somehow add a policy to startup.cs to define those users?

"Refreshing" a cloned repo using git

Posted: 17 Feb 2022 12:55 PM PST

Context:

  • working on a large project with thousands of files
  • project is built using gradle -- build process is not documented; several files are generated and spread across a number of directories
  • generated files shouldn't be added to git
  • project has no clean task -- once built, generated files must be removed manually

Is there a way to undo the state of the project after build using git? only a subset of the output files is of interest and the others can be ignored but, as it stands, these files are not easy to find.

Can the state after build be reverted to the clean state (after clone)?

One solution would be to add the generated files to a separate branch and work on that. Once built, the project is too large to be pushed to the repo.

Is there another way?

Run:

git clean -d . -f   

where

  • -d . tells git to recurse into all directories starting from root (that has the .git dir)
  • -f just delete everything and don't prompt

Any workaround for JSONPATH wildcard not supported in Spark SQL

Posted: 17 Feb 2022 12:55 PM PST

spark.sql("""select get_json_object('{"k":{"value":"abc"}}', '$.*.value') as j""").show()  

This results in null while it should return 'abc'. It works if I replace * with k.

I'm aware of limited JSONPath support (https://cwiki.apache.org/confluence/display/Hive/LanguageManual+UDF#LanguageManualUDF-get_json_object)

but is there a way to achieve this is Spark SQL.

How can I list all service accounts (also those created by GCP) with the "gcloud" CLI?

Posted: 17 Feb 2022 12:55 PM PST

When using gcloud iam service-accounts list I only see those service accounts created by me. But for script reasons I'd like to obtain also those created by GCP.

Especially I am looking for 815330817453@cloudbuild.gserviceaccount.com. Since I am creating my GCP infrastructure with terraform I can not depend on 815330817453 as an identifier and therefore need to look for the service account manually via gcloud.

However gcloud iam service-accounts list does not list the cloudbuild.gserviceaccount.com service account (nor any other like compute.gserviceaccount.com`

How I can solve a sqflite conflicting with sdk in android studio?

Posted: 17 Feb 2022 12:56 PM PST

I have a problem when add sqflite to my project(flutter) to dependencies in SDK 31.0.0 and the console make like this when make run :

FAILURE: Build failed with an exception.    * What went wrong:  Could not determine the dependencies of task ':sqflite:compileDebugAidl'.  > Failed to find Build Tools revision 30.0.2    * Try:  Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.    * Get more help at https://help.gradle.org    BUILD FAILED in 13s  Exception: Gradle task assembleDebug failed with exit code 1  

Chartjs React Typescript moving x axis labels above chart

Posted: 17 Feb 2022 12:55 PM PST

I'm using chartjs to generate a bar chart, and one of the requirements is to have the x-axis labels appear at the top of the chart rather than the bottom. (Even though I disagree with this, apparently there is no leeway from the client) and I'm having trouble following the documentation and any examples I find are for older versions.

The relative packages I'm using are:

"chart.js": "^3.7.1",  "react-chartjs-2": "^4.0.0",  

Secondly they want the labels to wrap rather being a single line based on bar width, since it's responsive. I was experimenting with using arrays to break up the words as an example, but wondering if this can be done within chartjs. Here is the code I have setup so far (I had to use some lorem ipsum cause of sensitive data):

import * as React from 'react';  import {    Chart as ChartJS,    CategoryScale,    LinearScale,    BarElement,    Title,    Tooltip,    Legend,    ChartOptions  } from 'chart.js';  import { Bar } from 'react-chartjs-2';  import { Chart } from 'react-chartjs-2';    ChartJS.register(    CategoryScale,    LinearScale,    BarElement,    Title,    Tooltip,    Legend  );    // added as an example. if there is a negative value, the bar color changes.  const generateBgColors = (data : number[]) => {    const bgColors = [];      for(let i = 0; i < data.length; i++) {      const value = data[i];      if(value > 0) {        bgColors.push('rgba(53, 162, 235, 0.5)');      } else {        bgColors.push('rgba(255, 99, 132, 0.5)');      }    }    return bgColors;  }    const options =  {    responsive: true,    maintainAspectRatio: true,    plugins: {      legend: {        display: false      }    },    scales: {    }  }   var data = [2.0, -2.0, 0.5, 1.5];  const labels = [    ['Lorem ipsum dolor sit amet,', ' consectetur adipiscing elit.', ' Integer eget auctor felis.'],    ['label2'],    ['label3'],    ['label4'],  ];  const chartData = {    labels: labels,    datasets: [      {        data: [2.0, -2.0, 0.5, 1.5],        backgroundColor: generateBgColors(data)      }    ]  }  const BeliefsChart : React.FunctionComponent = (props) => {    const chartRef = React.useRef<ChartJS>(null);    return (      <React.Fragment>        <Chart type="bar" ref={chartRef} options={options} data={chartData} height={50} />      </React.Fragment>    );  }  

How can I query room availability in a hotel reservation database?

Posted: 17 Feb 2022 12:55 PM PST

I'm working on a hotel reservation system and I'm stuck on checking room availability.

This is my DB structure:

  1. Rooms: roomId, roomName, roomCapacity
  2. Reservation: rsId, rsroomId, date_in, date_out

I want to create a search function to query available rooms. I can't get the ones which are available and which are not booked within a date range.

I have tried lots of things but can't solve this issue. This is my latest code:

   function search ($name, $date_in, $date_out) {        $this->db->select('*')->from('Rooms');        $this->db->join('Reservation', 'rooms.roomid = reservation.rsroomId', 'LEFT');        $this->db->like('date_in', $date_in);        $this->db->like('date_out', $date_out);        $this->db->like('roomName', $name);        return $this->db->get()->result_array();     }  

Thank You

Delete connections in aws documentdb

Posted: 17 Feb 2022 12:55 PM PST

In aws documentDb is there a way to delete open connections from mongo cli?

When I run

db.serverStatus()  

I see there are about 1k connections, I am trying to delete those. I tried using

db.adminCommand( { killSessions: []})  

Is there a command that I can use or do I need to restart the cluster or block IP of application that has active connection.

RepositoryNotFoundError: No repository for "User" was found. Looks like this entity is not registered in current "default" connection? Typeorm

Posted: 17 Feb 2022 12:54 PM PST

I am having a fun issue trying to get TypeOrm to work in my nestjs project.

I have the below code to configure my project, yes everything loads, and yes I am able to connect to my database.

import { CacheModule, Module } from '@nestjs/common';  import { JwtModule } from '@nestjs/jwt';  import { PassportModule } from '@nestjs/passport';  import { TypeOrmModule } from '@nestjs/typeorm';  import { User } from './entities/user.entity';  import { ConfigModule } from '@nestjs/config';  import { AuthenticationController } from './controllers/authentication.controller';  import { AuthenticationService } from './services/authentication.service';  import { Connection } from 'typeorm';  import { BaseEntity } from './entities/base.entity';    @Module({    imports: [      ConfigModule.forRoot(),      TypeOrmModule.forRoot({          type: 'postgres',          host: 'localhost',          port: 5432,          username: 'postgres',          password: process.env.POSTGRE_PASSWORD,          database: process.env.DATABASE,          migrationsTableName: 'migration_table',          entities: [User, BaseEntity],          migrations: [__dirname + '/migrations/**/*.ts'],          subscribers: [__dirname + '/subscribers/**/*.ts'],          cli: {            entitiesDir: '/entitys',            migrationsDir: '/migrations',            subscribersDir: '/subscribers',          },          synchronize: true,          autoLoadEntities: true,      }),      CacheModule.register(),      PassportModule,      JwtModule.register({        secret: 'myprivatekey',        signOptions: { expiresIn: '1d' },      }),    ],    controllers: [AuthenticationController],    providers: [AuthenticationService],  })  export class AppModule {    constructor(private connection: Connection) {}  }  

and here are the entities:

import {    Column,    BeforeUpdate,    BeforeInsert,  } from 'typeorm';    export class BaseEntity {    @Column()    created_at: Date;      @Column({      default: new Date(),    })    updated_at: Date;      @BeforeUpdate()    updateUpdatedAt() {      this.updated_at = new Date();    }      @BeforeInsert()    updateCreatedAt() {      this.created_at = new Date();    }  }  
import {    Entity,    Column,    PrimaryGeneratedColumn,    Generated,  } from 'typeorm';    import { BaseEntity } from './base.entity';    @Entity('users')  export class User extends BaseEntity {    @PrimaryGeneratedColumn()    id: number;      @Column()    @Generated('uuid')    uuid: string;      @Column()    first_name: string;      @Column()    last_name: string;      @Column()    email: string;      @Column()    password: string;      @Column({      default: false,    })    confirmed: boolean;      @Column({      default: null,    })    seller_id: string;      @Column({      default: null,    })    auth_token: string;      @Column({      default: false,    })    is_admin: boolean;  }  

I originally tried doing a glob pattern match, to no avail, so now I am directly importing in my Entities until I can get something to run. Also note, that all my modules load prior to the error above and the error is from using the @InjectRepository() decorator within either the AuthenticationController or AdminController. Everywhere I have looked has said its because my entities are not being loaded, which I am not sure how that is possible. Thanks.

How to clear terminal command history in VS code?

Posted: 17 Feb 2022 12:56 PM PST

In VS Code Powershell Terminal, you can simply press up and down arrow keys to navigate through the history of commands entered, even after a restart. However, when there are same commands entered, it will also cycle through these duplicated histories instead of just making them distinct, making it hard to find cycle back to some old history. Is there a way to clear this history entirely?

How to parse a CSV file in Bash?

Posted: 17 Feb 2022 12:56 PM PST

I'm working on a long Bash script. I want to read cells from a CSV file into Bash variables. I can parse lines and the first column, but not any other column. Here's my code so far:

    cat myfile.csv|while read line    do      read -d, col1 col2 < <(echo $line)      echo "I got:$col1|$col2"    done  

It's only printing the first column. As an additional test, I tried the following:

read -d, x y < <(echo a,b,)

And $y is empty. So I tried:

read x y < <(echo a b)

And $y is b. Why?

How to use TimeZoneInfo to get local time during Daylight Saving Time?

Posted: 17 Feb 2022 12:56 PM PST

I'm trying to use DateTimeOffset to convey a specific moment in time across any time zone. I can't figure out how to use TimeZoneInfo to deal with daylight saving time.

var dt = DateTime.UtcNow;  Console.WriteLine(dt.ToLocalTime());    var tz = TimeZoneInfo.FindSystemTimeZoneById("Central Standard Time");  var utcOffset = new DateTimeOffset(dt, TimeSpan.Zero);  Console.WriteLine(utcOffset.ToOffset(tz.BaseUtcOffset));  

This prints out:

6/2/2010 4:37:19 PM  6/2/2010 3:37:19 PM -06:00

I am in the central time zone, and and we are currently in daylight saving time. I am trying to get the second line to read:

6/2/2010 4:37:19 PM -05:00

BaseUtcOffset apparently doesn't change based on DST.

How can I get the the right time with the proper offset value?

How do I write standard error to a file while using "tee" with a pipe?

Posted: 17 Feb 2022 12:56 PM PST

I know how to use tee to write the output (standard output) of aaa.sh to bbb.out, while still displaying it in the terminal:

./aaa.sh | tee bbb.out  

How would I now also write standard error to a file named ccc.out, while still having it displayed?

No comments:

Post a Comment