Sunday, April 25, 2021

Recent Questions - Stack Overflow

Recent Questions - Stack Overflow


Execution strategy 'SqlServerRetryingExecutionStrategy' does not support user-initiated transactions

Posted: 25 Apr 2021 07:39 AM PDT

I have a .net 5 (core) web MVC application, working with Entity Framework EF5 (also core).

We implement web components, like Grid or Spredsheet (we work with Telerik). When I do some changes in the component, and then try to save the changes, the component calls my ApplicationDbContext.SaveChanges. And then I get the following error:

System.InvalidOperationException: 'The configured execution strategy 'SqlServerRetryingExecutionStrategy' does not support user-initiated transactions. Use the execution strategy returned by 'DbContext.Database.CreateExecutionStrategy()' to execute all the operations in the transaction as a retriable unit.'

enter image description here

Here is my StartupSetup class:

public static void AddDbContext(this IServiceCollection services, string connectionString) =>      services.AddDbContext<ApplicationDbContext>(options =>      {          options.UseSqlServer(connectionString,              providerOptions =>              {                  providerOptions                      .EnableRetryOnFailure(                          maxRetryCount: 5,                           maxRetryDelay: TimeSpan.FromSeconds(30),                          errorNumbersToAdd: null)                      .UseQuerySplittingBehavior(QuerySplittingBehavior.SplitQuery);              });          options.EnableSensitiveDataLogging();            /*           * Compiling a query which loads related collections for more than one collection navigation            * either via 'Include' or through projection            * but no 'QuerySplittingBehavior' has been configured.            * By default Entity Framework will use 'QuerySplittingBehavior.SingleQuery'            * which can potentially result in slow query performance.            * See https://go.microsoft.com/fwlink/?linkid=2134277 for more information.            * To identify the query that's triggering this warning call            * 'ConfigureWarnings(w => w.Throw(RelationalEventId.MultipleCollectionIncludeWarning))'           */          options.ConfigureWarnings(w => w.Throw(RelationalEventId.MultipleCollectionIncludeWarning));      }); // will be created in web project root  

That error does not happen systematically. For sure when I try to save to DB multiple elements. But also when only one element. Does not happen when I edit or same an element one by one, in a classic form, only when it happens in multiple objects scenario (grid or spreadsheet)

How can we make use of apple m1 neural engine as a programmer

Posted: 25 Apr 2021 07:39 AM PDT

I did lots of research on this subject but didn't find anything valuable for a python programmer. How can I use M1 neural engine efficiency for my models using python, C++, javascript whatever it is but swift? Is there a beginner-friendly roadmap to doing this without using external libraries?

Guna.UI app not opening, even the dll's merged

Posted: 25 Apr 2021 07:39 AM PDT

I'm creating a cleaning application, you know, system maintenance in general. Anyway, my project is finished. I wanted to compress dlls. I used ILMerge and costura.fody for this. The result was successful, but the program did not open even though I squeezed/merged the DLLs into exe. I tried on other dll's (like a metro framework etc.) there was no error. I realized that the trouble was with the Guna.UI dll. How can I fix this error? (Sorry for my bad english :()

JavaFX, using button to display information within a .txt file in a text field

Posted: 25 Apr 2021 07:39 AM PDT

I need to accomplish this:

A "Read File" button that when pressed will open and read the file ("FileName.txt") and initialize the different expense or payment objects. You will need to read separately from "expenses.txt" and "payments.txt".

I haven't been able to figure out a code that allows me to open a .txt file and display it in a text field. Everything I've tried just show the last word in the text file or just shows up as an error. If you were to fun the code I have now it would show the GUI, but none of the buttons really work at the moment. I read the "Read File" button to open a .txt file that is already made if possible.

package gui;    import expenses.MyExpenses;  import javafx.application.Application;  import javafx.event.ActionEvent;  import javafx.event.EventHandler;  import javafx.fxml.FXML;  import javafx.fxml.FXMLLoader;  import javafx.scene.Parent;  import javafx.scene.Scene;  import javafx.scene.control.TextArea;  import javafx.scene.control.TextField;  import javafx.scene.layout.GridPane;  import javafx.scene.layout.HBox;  import javafx.scene.layout.StackPane;  import javafx.stage.FileChooser;  import javafx.stage.Stage;  import javafx.scene.control.Button;  import org.w3c.dom.Text;    import java.awt.*;  import java.io.*;  import java.util.Scanner;        public class MyExpensesGUI extends Application {        public static void main(String[] args) {            launch(args);          MyExpenses m = new MyExpenses();          m.init();          m.print();          m.read();        }        private Text actionStatus;      private Stage savedStage;        @Override      public void start(Stage primaryStage) {            TextArea textArea = new TextArea();          textArea.setEditable(false);            TextField nameTxt = new TextField();          nameTxt.setPromptText("FileName.txt");            Button fileBT = new Button();          fileBT.setText("Read File");          fileBT.setOnAction(ActionEvent -> {              try (Scanner scanner = new Scanner(new File("C:\\Users\\debor\\IdeaProjects\\expenses.txt"))) {                    while (scanner.hasNext())                      textArea.setText(String.valueOf(scanner.next()));                } catch (FileNotFoundException e) {                  e.printStackTrace();              }                  });                Button allB = new Button();          allB.setText("Print All Expenses & Payments");                TextField numberTxt = new TextField();          numberTxt.setPromptText("ExpenseRefNumber");              Button pep = new Button();          pep.setText("Print Expenses & Payments");          pep.setOnAction(ActionEvent -> {              textArea.setText(String.valueOf(numberTxt));          });                Button teB = new Button();          teB.setText("Print Total Expenses");            Button totB = new Button();          totB.setText("Print Total Balance");            GridPane grid = new GridPane();          grid.setVgap(20);          grid.setHgap(10);          grid.addRow(0, nameTxt, fileBT);          grid.addRow(1, numberTxt, pep, textArea);          grid.addRow(2, allB);          grid.addRow(3, teB);          grid.addRow(4, totB);            primaryStage.setTitle("Deborah Barbeau");              Scene scene = new Scene(grid, 900, 400);          primaryStage.setScene(scene);          primaryStage.show();      }  }  

Duplicate rows in Python Pygame Tetris clone

Posted: 25 Apr 2021 07:39 AM PDT

I've been looking at this problem for awhile now and have draw a blank so would appreciate some help.

I'm making a simple Tetris clone using Python and Pygame. The problem is that the process of detecting completed rows sometimes adds a cloned row to the new GRID so anything effecting the original also effects the cloned row too.

here is the code for removing completed rows:

# create an empty grid  newGRID = []    fullRowsCount = 0  for row in reversed(GRID):      # count number of non-zero blocks in row      rowBlockCount = sum(col > 0 for col in row)            # if number of non-zero blocks is less than the width of grid then copy to newGRID      if rowBlockCount < GRID_SIZE.width:            # insert non-full row into newGRID          newGRID.insert(0, row)        else:          # increment this counter in order to know number of blank rows to add to top of newGRID          fullRowsCount += 1    # if there are any full rows then they're not included in newGRID so blank rows need adding to the top  if fullRowsCount:      newGRID = [[0] * GRID_SIZE.width] * fullRowsCount + newGRID      # update GRID to the newGRID      GRID = newGRID  

Thank you for your time :)

Communicating between threads

Posted: 25 Apr 2021 07:39 AM PDT

I'm trying to build a multithreaded app but, how would I implement this?

Thread 1 (Input Thread): Reads a message from the user
Thread 2 (Client Thread): When a message is read, send the message data to the server. (and also receive data, but this is easy to implement)

The problem is, send/recv is blocking. Can I just communicate between threads to make thread1 ask thread2 to send a message?

for loop does not work when using crontab in Apple M1

Posted: 25 Apr 2021 07:38 AM PDT

Just a simple shell script:

#!/bin/zsh    for file in ~/Desktop/*  do      echo ${file}  done  

When it runs in terminal, the output is like:

$ ./test  /Users/onns/Desktop/Screen Shot 2021-04-25 at 19.48.46.png  /Users/onns/Desktop/Screen Shot 2021-04-25 at 19.52.42.png  /Users/onns/Desktop/Screen Shot 2021-04-25 at 19.53.38.png  /Users/onns/Desktop/Screen Shot 2021-04-25 at 19.54.03.png  

Everything is ok, but when I test it via crontab, the output is:

/Users/onns/Desktop/test:3: no matches found: /Users/onns/Desktop/*  

* does not expand when using crontab, does anyone know why?

the cron task is:

* * * * * /bin/zsh /Users/onns/Desktop/test >>/Users/onns/Desktop/out.log 2>>/Users/onns/Desktop/err.log  

Unable to compile the project listed in https://github.com/technologiestiftung/giessdenkiez-de

Posted: 25 Apr 2021 07:38 AM PDT

I am trying to compile the project listed under GitHub on my local machine. I have a basic knowledge in Python and struggling to start the compilation.

Can someone please help me to write the command to start the project.

I am trying the run npm start but it is complaining me to setup BUILD_TARGET and NODE_ENV which I set like

npm start BUILD_TARGET=demo NODE_ENV=test  

It is giving me the error

cross-env BUILD_TARGET=DEFAULT NODE_ENV=development webpack-dev-server --config webpack/dev.config.js "BUILD_TARGET=demo" "NODE_ENV=test"  

Can you please tell me what I am missing? I have windows machine with npm version 6.14.12 and Pyhon version 3.9.3

GroupBy by a condition and create different anonymous model per group EF6

Posted: 25 Apr 2021 07:38 AM PDT

I am using EF6 + sql server. I want to make a query to one of my tables and to map the result by a condition into 2 groups. In each group the results should be fetched as a different kind of model. The idea here is that there are lots of fields I need in 1 case but not in the other one, and I, of course, prefer to get all the data in 1 trip to the db.

So I am trying to do something like:

IEnumerable<long> idsWithFullModel = new[] { 1, 2 };      var groups = context.MyTable     .GroupBy(        x => idsWithFullModel.Contains(x.id),        x => idsWithFullModel.Contains(x.id) ?          new          {            field1 = x.field1,            feild2 = x.feild2,         } :          new          {            field1 = x.field1,         });  

When I am trying to do it I receive "Cannot convert lambda expression to type 'IEqualityComparer because it is not a delegate type' compiler error.

Is it possible to make this kind of query?

How to make a body background image reponsive with bootstrap 4

Posted: 25 Apr 2021 07:38 AM PDT

I have an image on body tag that needs to be made responsive with bootstrap 4

How can this be done?

I am setting the body tag with background image property

What is the underlying technology in RPA that enables features/capabilities like the recorder, executing functions, etc

Posted: 25 Apr 2021 07:38 AM PDT

Let me start by apologizing if this is not the appropriate place for my question.

I am working on a project where I am trying to highlight the capabilities of RPA. Rather than just on the surface use cases and how RPA can revolutionize automation I am trying to understand the underlying technology that RPA is built from. (I have zero coding or computer science experience)

I have identified the following key features that enable RPA to be a true innovation and not just screen scraping.

  • Scrapping data even when the application is hidden
  • Recognizing controls
  • Working off images when in VMs like Citirix
  • Record Functionality
  • Unattended Robots
  • Market place for new features

What I am hoping to understand is how ".Net" or "VB" enables this scrapping functionality and why RPA companies decide to develop their tools in ".Net" vs another langauge. Im also trying to understand how the recorder works. It seems like it needs to be object orient to record a workflow however I don't understand what technology allows the recorder function to exist. I am also trying to understand what technology allows for unattended robots. What tech creates the ability to tigger the workflow. Lastely in regards to the market place it seems like UiPath is using "NuGet". Why would this be the right approach?

I understand this is a bit of an odd request. I am just trying to learn as much as possible. I am also open to a call if anyone is open to it.

Thank you in advance.

Ryan

PC Detects Pendrive but hidden and unableto use

Posted: 25 Apr 2021 07:37 AM PDT

Just bought a pendrive and used it as a bootable windows 10 drive and then it went hidden and when i try to format it says pls. insert median into disk even tried ChipBanks UMPTools but the process wont start.Pls helpChipBank UmpTool Unable to start

C# how do I tell when all threads or tasks have completed

Posted: 25 Apr 2021 07:37 AM PDT

This app processes image files that meet certain criteria, namely that the resolution is larger than 1600X1600. There can be upwards of 8000 files in a source directory tree but not all of them meet the resolution criteria. The tree can be 4 or 5 levels deep, at least.

I've "tasked" the actual conversion process. However, I can't tell when the last task has finished.

I really don't want to create a task array because it would contains thousands of files that don't meet the resolution criteria. And it seems a waste to open the image file, check the resolution, add or not to the task array, and then reopen it again when it's time to process the file.

Here's the code.

using System;  using System.Data;  using System.Drawing;  using System.Drawing.Imaging;  using System.IO;  using System.Linq;  using System.Threading.Tasks;  using System.Windows.Forms;    namespace ResizeImages2  {      public partial class Form1 : Form      {          private string _destDir;          private string _sourceDir;          private StreamWriter _logfile;          private int _numThreads;            private void button1_Click(object sender, EventArgs e)          {              _numThreads = 0;              if (_logfile is null)                  _logfile = new StreamWriter("c:\\temp\\imagesLog.txt", append: true);                _destDir = "c:\\inetpub\\wwwroot\\mywebsite\\";              _soureDir = "c:\\images\\"              Directory.CreateDirectory(_destDir);              var root = new DirectoryInfo(sourceDir);              WalkDirectoryTree(root); // <--async so it's going to return before all the threads are complete. Can't close the logfile here              //_logfile.Close();          }            private async void WalkDirectoryTree(System.IO.DirectoryInfo root)          {              System.IO.FileInfo[] files = null;              System.IO.DirectoryInfo[] subDirs = null;              files = root.GetFiles("*-*-*.jpg"); //looks like a sku and is a jpg.              if (files == null) return;              foreach (System.IO.FileInfo fi in files)              {                  _numThreads++;                  await Task.Run(() =>                  {                      CreateImage(fi);                      _numThreads--;                      return true;                  });              }                // Now find all the subdirectories under this directory.              subDirs = root.GetDirectories();                foreach (System.IO.DirectoryInfo dirInfo in subDirs)              {                  WalkDirectoryTree(dirInfo);              }          }            private void CreateImage(FileSystemInfo f)          {              var originalBitmap = new Bitmap(f.FullName);              if (originalBitmap.Width <= 1600 || originalBitmap.Height <= 1600) return;              using (var bm = new Bitmap(1600, 1600))              {                  Point[] points =                  {                      new Point(0, 0),                      new Point(new_wid, 0),                      new Point(0, new_hgt),                  };                  using (var gr = Graphics.FromImage(bm))                  {                      gr.DrawImage(originalBitmap, points);                  }                    bm.SetResolution(96, 96);                  bm.Save($"{_destDir}{f.Name}", ImageFormat.Jpeg);                  bm.Dispose();                  originalBitmap.Dispose();              }              _logfile.WriteLine(f.Name);          }      }  }  

How can I infer types for recursive functions?

Posted: 25 Apr 2021 07:37 AM PDT

I try to implement language with type inference based on Hindley-Milner algorithm. But I don`t know how to infer types for recursive functions:

f = g  g = f  

Here I must generate and solve constraints for f and g together because if I will do it for one function earlier it will not know the type of the other function. But I can't do it for all functions in module at the same time:

f = h 0  g = h "str"  h _ = 0  

Here in f I have h :: Int -> Int and in g I have h :: String -> Int, that will produce error if I will solve it at the same time but will not if I will infer the type of h before types for f and g (h :: forall a. a -> Int and can be used in f and g with different subsitution for a).

How can I infer this types?

Inconsistent SSL Certificates // Linux Server

Posted: 25 Apr 2021 07:37 AM PDT

I'm running a linux Ubuntu 20.x server for my site www.mbaglue.com

certbot certificate shows the following:

> Found the following certs:    Certificate Name: mbaglue.com      Domains: mbaglue.com www.mbaglue.com      Expiry Date: 2021-06-25 02:59:14+00:00 (VALID: 60 days)      Certificate Path: /etc/letsencrypt/live/mbaglue.com/fullchain.pem      Private Key Path: /etc/letsencrypt/live/mbaglue.com/privkey.pem  

However, chrome and digicert.com/help

TLS Certificate is revoked The certificate has been revoked. You should replace it with a new certificate as soon as possible.

OCSP Staple: Not Enabled OCSP Origin: Unauthorized CRL Status: Not Enabled TLS Certificate is expired. The certificate was valid from 25/Jan/2021 through 25/Apr/2021.

I'm not sure what's going on. Can someone shed some light

How to use firebase in normal java? [duplicate]

Posted: 25 Apr 2021 07:39 AM PDT

I'm creating a mod for minecraft which needs a database. But I can't find a way to use firebase with normal java, not android. how can I do it?

Can't download previous version of JDK from Oracle [closed]

Posted: 25 Apr 2021 07:37 AM PDT

I am gonna learn java 8. BUT I can't download it. Because Oracle web is saying I have to log in before it.

But I have no account. So I have to create one. But they are saying I have to tell my jobs ... I am 14. I have no jobs or what!!! What to DO now!!!!

Logical AND operation with integers in C#

Posted: 25 Apr 2021 07:37 AM PDT

When I do the following logical AND operation with numbers in C# I'm getting the following results:

 -3 & 3 = 1   -1 & 1 = 1    0 & 0 =0  

but when I do 8 & -8 =8 Can someone please explain how we are getting the result as 8?

$exception Unable to evaluate the expression. Operation not supported. Unknown error: 0x80040914

Posted: 25 Apr 2021 07:37 AM PDT

Here's my code and the error is with cmd. Please help. whats wrong with the code?

Imports MySql.Data.MySqlClient      Module Module1      Public conn As MySqlConnection = New MySqlConnection      Public ds As New DataSet      Public cmd As MySqlCommand = New MySqlCommand      Public dr As MySqlDataReader      Public sql As String        Public Sub connect()            cmd.CommandText = sql          cmd.CommandType = CommandType.Text          cmd.Connection = conn            conn.Open()          dr = cmd.ExecuteReader      End Sub    End Module  

How long is validity of app signing key when I 'Let Google create and manage my app signing key'?

Posted: 25 Apr 2021 07:38 AM PDT

When we create an app signing key for Android app, we set Validity (years) which should be valid for at least 25 years. For example, I can set it for 100 years.

But past few years, we were introduced Play App Signing. If I create just the upload key (and not create the app signing key by myself), Google creates and manages the app signing key.

Then, I wonder how long validity of app signing key created by Google is? I want it at least for 100 years. Isn't it for 25 years? What will Google do when app signing key expires?

What purpose is libSDL2main.a for?

Posted: 25 Apr 2021 07:38 AM PDT

Some sources say to have -lSDL2main.a as one of the files to link against while building SDL2 programs but some don't. The program works fine in either cases. What is it for?

Why is this a* algorithm is slower than Djikstra's?

Posted: 25 Apr 2021 07:39 AM PDT

I need to show how a* is quicker than Djikstra's using the graph below. I wrote the a* search function and then called it using a set of heuristics and then with all heuristics set to 0 (which is equivalent to Djikstra's). While the actual search with a* is more efficient, five steps to Djikstras seven, the recorded time it takes it to run is always higher, even averaged across numerous runs. The a* run with actual heuristic values is doing less so shouldnt it be faster? (Maybe my code is wonky?)

Edit: Used the timeit function as suggested in the comments which returned the expected results, updated the code to reflect that

#Create graph    graph =    {      'A': {'B':5},      'B': {'C':8,'D':9,'E':3},      'C': {'B':8,'G':2},      'D': {'B':9,'F':2},      'E': {'B':3,'I':4},      'F': {'D':2,'I':3},      'G': {'C':2,'H':3,'I':6},      'H': {'G':3,'J':4},      'I': {'E':4,'F':3,'G':6,'J':2},      'J': {'H':4,'I':2},      }    hcost =    {      'A': 875.008571,      'B': 717.54094,      'C': 720.151373,      'D': 685.286801,      'E': 596.030201,      'F': 434.165867,      'G': 420.107129,      'H': 190.779978,      'I': 179.744263,      'J': 0,      }    hcost1 =    {      'A': 0,      'B': 0,      'C': 0,      'D': 0,      'E': 0,      'F': 0,      'G': 0,      'H': 0,      'I': 0,      'J': 0,      }    def astar_algo(graph, start, target, hc):        #We set the cost for all nodes from the source      cost =  {vertex: float('infinity') for vertex in graph}      #The distance from the source to itself is 0      cost[start]=0            #We create       fcost={vertex: float('infinity') for vertex in graph}      fcost[start]=hc[start]            #We create a list of nodes to record the path i.e. the solution to the problem      path=set()            #We create a set to hold visited nodes      visited=set()        #We create a priority queue which contains distance to node,node,path and add our start node      priorityq = [(fcost[start], start, [])]        #While our priority queue isn't empty      while priorityq:                    pq0 =  [priorityq[idx][0] for idx in range(0, len(priorityq), 1)]           pq1 =  [priorityq[idx][1] for idx in range(0, len(priorityq), 1)]          print(f"Priority Queue: {list(zip(pq0,pq1))}\n")          #We pop out the highest priority element of the queue i.e. the shortest distance entry          (dist,current_node,path) = heap.heappop(priorityq)                    #print(f"dist {dist} current node {current_node} \tpath {path}\n")            #Add it to the path list and record it as being visisted          path = path+[current_node]          visited.add(current_node)            #We check if its our target, if it is we break the while loop with a return value          if current_node==target:              #We return a tuple with the target node and the cost to it as well as the path to it              return (current_node,cost[current_node]), path                        #If it isnt our target node then we check all its adjacent nodes          for adj_node, weight in graph[current_node].items():                            #If we've visited the node we move on to the nest              if adj_node in visited:                  continue                            #If the node is new we calculate the cost to it by adding the weight to it to              #the cost for the current node              new_cost = cost[current_node]+weight                            #calculate fcost = graph cost + heuristic cost              new_fcost = new_cost+hc[adj_node]                            #If the cost to the adjacent node is shorter than its recorded cost              if cost[adj_node] > new_cost:                  #We update its recorded cost                  cost[adj_node]=new_cost                            #If the fcost to the adjacent node is shorter than its recorded fcost              if fcost[adj_node] > new_fcost:                  #We update its recorded cost                  fcost[adj_node]=new_fcost                  #And it to the priority queue                  heap.heappush(priorityq, (new_fcost,adj_node,path))        return (0,0),'none'                                  start='A'  target='J'    t = timeit.Timer(lambda: astar_algo(graph,start,target,hcost))   print (f"Time taken to run A* 1 million times: {t.timeit(1000000)}")    t = timeit.Timer(lambda: astar_algo(graph,start,target,hcost1))   print (f"Time taken to run Djikstra's 1 million times: {t.timeit(1000000)}")    st =  perf_counter_ns()  cost,path = astar_algo(graph,start,target,hcost)  print('Time elapsed in nanoseconds {}\n'.format(perf_counter_ns() - st))    st =  perf_counter_ns()  cost,path = astar_algo(graph,start,target,hcost1)  print('Time elapsed in nanoseconds {}\n'.format(perf_counter_ns() - st))      if path=='none':      print("There is no solution available.")  else:      print(f"The distance to {cost[0]} is {cost[1]}.")      print (f"The shortest path from {start} to {target} is",end=" ")      print(*path, sep="->")  

NestJS - Avoid returning user's password

Posted: 25 Apr 2021 07:38 AM PDT

I have a little problem with my project using GraphQL and Mongoose (code-first approach). I have a findCurrentUser query in my user's resolver that returns the information about the currently authenticated user, but I don't want to return the user's password, how I can avoid this?

User's Resolver:

@Query(() => User)  @UseGuards(GqlAuthGuard)  async findCurrentUser(@CurrentUser() user: JwtPayload): Promise<User> {    return await this.usersService.findCurrent(user.id);  }  

User's Service:

async findCurrent(id: string): Promise<User> {      try {        // find the user        const user = await this.userModel.findOne({ _id: id });          // if the user does not exists throw an error        if (!user) {          throw new BadRequestException('User not found');        }          // we should not return the user's password        // TODO: this is a temporary solution, needs to be improved        user.password = '';          return user;      } catch (error) {        throw new InternalServerErrorException(error.message);      }    }  

User's Entity:

import { ObjectType, Field, ID } from '@nestjs/graphql';  import { Schema, Prop, SchemaFactory } from '@nestjs/mongoose';  import { Document, Schema as MongooseSchema } from 'mongoose';  import { nanoid } from 'nanoid';    @Schema()  @ObjectType()  export class User {    @Field(() => ID)    _id: MongooseSchema.Types.ObjectId;      @Field(() => String, { nullable: false })    @Prop({ type: String, required: true, trim: true })    firstName: string;      @Field(() => String, { nullable: true })    @Prop({ type: String, required: false, trim: true })    lastName?: string;      @Field(() => String, { nullable: true })    @Prop({ type: String, required: false, default: nanoid(10) })    username: string;      @Field(() => String, { nullable: false })    @Prop({      type: String,      unique: true,      required: true,      lowercase: true,      trim: true    })    email: string;      @Field(() => String, { nullable: false })    @Prop({ type: String, required: true, trim: true, minlength: 6 })    password: string;      @Field(() => Boolean, { defaultValue: true })    @Prop({ type: Boolean, default: true })    isActive: boolean;      @Field(() => Date, { defaultValue: Date.now() })    @Prop({ type: Date, default: Date.now() })    createdAt: Date;  }    export type UserDocument = User & Document;    export const UserSchema = SchemaFactory.createForClass(User);    

In the documentation, the NestJS team mentions "Serialization, " but I already tried and didn't work. I get the following error on my GraphQL Playground:

"message": "Cannot return null for non-nullable field User._id."

odr-use of `static const int` data member succeeds WITHOUT definition in call taking `const int &`

Posted: 25 Apr 2021 07:39 AM PDT

This is a frustratingly difficult question to ask. I'm asking you to guess what code or conditions in my build system might allow the following to build and run correctly, when the obvious expectation is that it should result in a linker undefined reference error.

class Logger  {  public:    template <typename T>    Logger & operator<<(const T& r)  // odr-use of static const data member here.    { return *this;    }    //...  };  class SomeClass  {    static const int a_constant = 42; // used as enum, not defined elsewhere.    static Logger & logOutput()    {  static Logger log;       return log;    }      void do_something()    {  logOutput()         << a_constant     //<--- EXPECT undefined reference error here.        << '\n';          // works fine also.    }  };  

(Dev is g++ 9.xx, -std=c++17. CI builds are g++ 4.6.x.)

Code similar to the above builds without error, against expectations, in our development environment. It had also built in the past without issue in our Jenkins CI environment, most recently 3 years ago. The reason to ask is that it now no longer builds in CI, but continues to build fine in dev. That it now fails to build in CI brings it to our attention.

My expectation is template<> Logger::operator<<(const int &) will always be preferred, given that the offending value is a const int. I don't expect that a free function can ever be a better overload match. (Is this a safe presumption?)

What mechanisms could allow this white magic? Compiler flags? versions? Other helper function signatures?

Thanks.

How to format SQL subquery to produce new and old data

Posted: 25 Apr 2021 07:38 AM PDT

I have a database where I am trying to figure out this problem. I want to write a SQL query to list all patients whose information has changed during their future visits. A future visit is defined as dbo.patientvisit.encounter_id < dbo.visitvitalstat.encounter_id The outputs I want in the table are the columns patient number, old and new race values, old and new gender values, and both encounter ids from the both tables. The new race and gender values are from future visits.

enter image description here enter image description here

This is the code I have so far but I can't figure out how to get the new gender and new race values.

  SELECT pv.patient_nbr,pv.encounter_id, vvs.race, vvs.gender, vvs.encounter_id  FROM PatientVisit pv  LEFT JOIN VisitVitalStat vvs  ON pv.encounter_id = vvs.encounter_id  WHERE pv.encounter_id < vvs.encounter_id;  

This is the result I should get back: enter image description here

SELECT  fpv.patient_nbr(??)                  vvs.race as "Old race",                  fv.newrace as "New Race",                  vvs.gender as "Old Gender",                  fv.newgender as " New Gender",                  vvs.encounter_id as "Old Encounter ID" ,                  fv.newencounter as "New Encounter ID"  FROM  VisitVitalStat vvs  INNER JOIN                      ( SELECT fpv.patient_nbr as newnbr,                                        fvvs.race as newrace,                                        fvvs.gender as newgender,                                        fvvs.encounter_id as newencounter  FROM PatientVisit fpv, VisitVitalStat fvvs                        WHERE  fpv.encounter_id = fvvs.encounter_id                                AND                                        fpv.encounter_id < fvvs.encounter_id) fv  ON   fv.newencounter = vvs.encounter_id;  

So I was able to write a query but I feel like it is still off, I'm not sure how to get patient number into all of this.

Cypress: Getting the text from an input field returns object values instead of text value

Posted: 25 Apr 2021 07:37 AM PDT

I'm having problems doing the simplest of the simple things: Verify a value in an field.

The markup:

<input class="hb-inputfelt data-e2e-selector="boligbetegnelse" ng-reflect-form="[object Object]" id="finansieringsobjekt-boligbetegnelse-211-H01-0">  

Cypress:

.should('have.text', 'value');  

or

.should('have.value', '123'):  

returns

expected '<div>' to have value '123', but the value was ''  

and

.should('have.text', '123');  

returns

expected '<div>' to have text '123', but the text was     'a bunch of text - probably values from the object in ng-reflect-from=[object Object]  

I'm guessing the problem is the object in the field, since the data it returns consists of a long list of object values from the object "behind" the frontend.

But the value I'm checking for - "123" - IS the visible text in the field. How do I get it when the above doesn't work?

Asynchronous mail receiving with Spring Boot and Spring integration

Posted: 25 Apr 2021 07:37 AM PDT

I'm trying to receive emails from gmail server and then process them somehow. So every time when new email arrives to the mail server, my application should download it and process it, it means call other services asynchronously which will be registered as listeners.

I'm quite new in spring integration and I don't fully understand how does it work or if it is correct.

1) So far, I have this code -- I'm able to read all emails but I'm not sure if they are processed asynchronously or not or if it is a correct way?

ListeningExample class

@Configuration  public class ListeningExample {        @Bean      public HeaderMapper<MimeMessage> mailHeaderMapper() {          return new DefaultMailHeaderMapper();      }        @Bean      public IntegrationFlow imapMailFlow() {              IntegrationFlow flow =  IntegrationFlows                  .from(Mail.imapInboundAdapter("imap://user:pwd@imap.gmail.com/INBOX")                                  .userFlag("testSIUserFlag")                                  .javaMailProperties(javaMailProperties()),                          e -> e.autoStartup(true)                                  .poller(p -> p.fixedDelay(5000)))dostane to detailni zpravy                  .transform(Mail.toStringTransformer())                  .channel(MessageChannels.queue("imapChannel"))                  .get();          return flow;       }        @Bean(name = PollerMetadata.DEFAULT_POLLER)      public PollerMetadata defaultPoller() {            PollerMetadata pollerMetadata = new PollerMetadata();          pollerMetadata.setTrigger(new PeriodicTrigger(1000));          return pollerMetadata;      }  }  

MailRecieverService class

@Service  public class MailRecieverService {        private List<EmailAction> services;        @Bean      @ServiceActivator(inputChannel = "imapChannel")      public MessageHandler processNewEmail() {          MessageHandler messageHandler = new MessageHandler() {                @Override              public void handleMessage(org.springframework.messaging.Message<?> message) throws MessagingException {                  System.out.println("New email:" + message.toString());                    //Processing emails do with them something..                  for (EmailAction emailAction : services) {                      emailAction.performAction(null);                  }                }          };          return messageHandler;      }    }    

Main class

@SpringBootApplication  @EnableIntegration  public class Main extends SpringBootServletInitializer {        @Override      protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {          return application.sources(Main.class);      }          public static void main(String[] args) throws Exception {          SpringApplicationBuilder builder = new SpringApplicationBuilder(Main.class);          builder.headless(false).run(args);      }    }  

2) Is there also a possibility in spring boot to move/delete emails, create folders, and do other actions with an email account or do I have to use javax.mail library on my own? If yes, could you provide some examples?

How to append values to the PATH environment variable in NodeJS?

Posted: 25 Apr 2021 07:38 AM PDT

Following the answer suggested in the question -

Is it possible to permanently set environment variables?

I was able to set new environment variables permanently with the command -

spawnSync('setx', ['-m', 'MyDownloads', 'H:\\temp\\downloads'])  

But now my goal is to append new values to the PATH environment variable.

Is it possible?

Android - Get current position from recyclerview with listener when position changed

Posted: 25 Apr 2021 07:39 AM PDT

I'm working with recyclerview with snaphelper. this is my recyclerview:

    final LinearLayoutManager lm = new LinearLayoutManager(getContext(),       LinearLayoutManager.HORIZONTAL, false);        recyclerview.setLayoutManager(lm);        final PagerSnapHelper snapHelper = new PagerSnapHelper();      snapHelper.attachToRecyclerView(recyclerview);  

when user scroll to another cell i need to do something with the new cell position.

this is what i do to get the position:

        recyclerview.addOnScrollListener(new RecyclerView.OnScrollListener() {          @Override          public void onScrollStateChanged(RecyclerView recyclerView, int newState) {              if (newState != RecyclerView.SCROLL_STATE_IDLE) {                  return;              }              if recyclerview == null) {                  return;              }               //recyclerview.clearOnChildAttachStateChangeListeners();              int firstVisible = ((LinearLayoutManager) viewerRv.getLayoutManager()).findFirstCompletelyVisibleItemPosition();              if (firstVisible == RecyclerView.NO_POSITION) {                  return;              }              doSomething(firstVisible);         }  

the problem is the firstVisible var not always give me the right position for example when i scroll from position 0 to 9 this can be the output: 0,1,2,3,4,4,5,9

there is another way to get the right current position?

what are the best practices for that?

How do I run a terminal inside of Vim?

Posted: 25 Apr 2021 07:39 AM PDT

I am used to Emacs, but I am trying out Vim to see which one I like better.

One thing that I like about Emacs is the ability to run a terminal inside Emacs. Is this possible inside of Vim? I know that you can execute commands from Vim, but I would like to be able to run a terminal inside of a tab.

No comments:

Post a Comment