Saturday, May 28, 2022

Recent Questions - Stack Overflow

Recent Questions - Stack Overflow


approximating Euler’s number e to within 0.001 in python

Posted: 28 May 2022 04:25 PM PDT

I need to write an algorithm that approximates e using a while loop and returns the number of terms needed to approximate the number. It seems to me like the loop stops after the first iteration but I cannot figure out why.

Here's my code:

import math    def factorial(n):      f = 1      for i in range(1, n+1):          f = f * i      return f    def e_to_x_series():      sum_acc = 0      e = math.e      i = 1      print(e)      while abs(e - sum_acc) < 0.001:          sum_acc = sum_acc + 1 ** i / factorial(i)          print(sum_acc)          i += 1      return sum_acc    print(e_to_x_series())  

How to use 2 text files at once in python

Posted: 28 May 2022 04:26 PM PDT

I have made a Spanish verb conjugation function which has 2 parameters for the pronoun and verb as shown below:

def doConjugate(pronoun,verb):      if unidecode(verb).endswith("ar"):          arDict = {"yo": "o", "tú": "as", "usted": "a", "él": "a", "ella": "a", "nosotros": "amos", "vosotros": "áis", "ustedes": "an", "ellos": "an", "ellas": "an"}          verb = verb[:-2] + arDict[pronoun]          print(verb)      if unidecode(verb).endswith("er") or unidecode(verb).endswith("ir"):          erDict = {"yo": "o", "tú": "es", "usted": "e", "él": "e", "ella": "e", "nosotros": "emos", "vosotros": "éis", "ustedes": "en", "ellos": "en", "ellas": "en"}          irDict = {"nosotros": "imos", "vosotros": "ís"}          if (pronoun == "nosotros" or pronoun == "vosotros") and verb.endswith("ir"):              verb = verb[:-2] + irDict[pronoun]          else:              verb = verb[:-2] + erDict[pronoun]          print(verb)  

Addionally, I have two text files. One with all of the verbs, and a second one with all of the pronouns. I want to make a for loop which takes the pronoun from one file and the verb from the another and conjugate it. However, I do not know how to do so.

Below is what it tried to do:

with open("words.txt") as file:      with open("pronouns.txt") as f:          for word in file:              for conjugates in f:                  conjugated = doConjugate(conjugates,word)                  print(conjugated)  

However, in the terminal, instead of the conjugations, I just get the word "None" over and over. I am new to python and am requesting someone to show how to do this properly.

Thanks in advance.

Checking For Duplicates While Decoding JSON (SWIFT)

Posted: 28 May 2022 04:23 PM PDT

I am writing swiftUI code in xcode, i need to decode some json. im using the decoder i see online, and I understand how it works and it is working perfectly. What i am doing is parsing a json full of data about a list of photo albums. however i want to check for DUPLICATE photo albums and do soemthing when i find one. here is the decoding code im using:

var albums: [PhotoAlbum] = load("albums.json")  func load<T: Decodable>(_ filename: String) -> T {      let data: Data      guard let file = Bundle.main.url(forResource: filename, withExtension: nil)      else {          fatalError("Couldn't find \(filename) in main bundle.")      }        do {          data = try Data(contentsOf: file)      } catch {          fatalError("Couldn't load \(filename) from main bundle:\n\(error)")      }        do {          let decoder = JSONDecoder()          return try decoder.decode(T.self, from: data)      } catch {          fatalError("Couldn't parse \(filename) as \(T.self):\n\(error)")      }  }  

Thanks in advance :)

inserting brokenly formatted text into PostgreSQL table despite encoding errors with \copy

Posted: 28 May 2022 04:23 PM PDT

I have a text field (utf8) that misbehaves a little. originally fetched it includes the character sequence \u00e2\u0080\u0099 which is basically an apostrophe in another encoding. I have decided to maintain this corrupted state and not solve it despite the fact I have found a few solutions online on how to reinterpret these kinds of errors in my text field.

So I just want to insert the raw data as is. I have tried 2 ways to insert this row.

  1. Using python with peewee (an orm library). with everything configured correctly this method actually works, the data is inserted and there is a row in the database.
    selecting the column yield: donâ\u0080\u0099t which I am ok with keeping.

So far so good.

  1. Writing a python script that prints tab delimited text and using \copy
    Annoyingly this method does not work and returns the following error:
ERROR:  invalid byte sequence for encoding "UTF8": 0x80  CONTEXT:  COPY comment, line 1: "'donâ\x80\x99t'"  

(when printing the data from the python script to console it shows up as donâ\x80\x99t)

Thus clearly there is a difference between what peewee does and my naive printing of the string from python (peewee and print receive the same string as input).

How do I encode this string correctly so I can use \copy to populate the row?

max weight on code and current weight not changing and staying equal on a hx711 load cell attached to an lcd

Posted: 28 May 2022 04:22 PM PDT

I am building a hx711-based weight scale that displays the measured weight on an LCD, along with the weight the LCD shows a "max weight" If weight>max weight the buzzer will buzz. I have written code to perform these functions but, the weight always goes to zero no matter what and I cant set the max weight. I will include a schematic and the code here:

https://imgur.com/wMFoVMB

#include "HX711.h     #include <Wire.h>`      #include <LiquidCrystal_I2C.h>    LiquidCrystal_I2C lcd(0x27, 16, 2);    int IN1 = A0;  /  int IN2 = A1;    int over_val;  int data;  int g_weight;  int Weight;    const int buzzer = 13;      void setup()  {    pinMode(buzzer, OUTPUT);    lcd.init();    lcd.clear();    lcd.backlight();    pinMode(IN1, INPUT);    pinMode(IN2, INPUT);    Init_Hx711();    Serial.begin(9600);    Serial.print("Ready!\n");    Get_Maopi();    lcd.begin(16, 2);    lcd.clear();    lcd.setCursor(0, 0);    lcd.print(" Harry Brass ");    lcd.setCursor(0, 1);    lcd.print("  Gus Creech  ");    delay(1000);    lcd.clear();  }    void loop()  {      Weight = Get_Weight();    g_weight = Weight - data;      lcd.setCursor(0, 0);    lcd.print("Weight:");    lcd.print(g_weight);    lcd.print("g    ");      if (digitalRead(IN2) == LOW) {data = Weight;}    if (digitalRead(IN1) == LOW) {over_val = g_weight;    }      if (g_weight <= over_val)    {      lcd.setCursor ( 0, 1 );      lcd.print("Max Weight:");      lcd.print(over_val);      lcd.print("g    ");      digitalWrite(buzzer, LOW);    }      else if (g_weight > over_val)    {      Serial.println("overload");      lcd.setCursor ( 0, 1 );      lcd.print("...OverLoad!!...");      digitalWrite(buzzer, HIGH);    }      delay(50);  }  

Is there a way to make my aside be aligned to the right?

Posted: 28 May 2022 04:22 PM PDT

So, I'm working on a project for my web design class and a sidebar is required to get to other pages. The teacher recommended I use the aside tag, so I have, however I've run into a rather annoying issue that I cant find an answer to. Whenever I try to align the aside to the center right, it clips into the footer, or does the complete opposite, I'm not sure what to do, as w3 schools and other sources have been little to no help. I'm not sure if its just my lack of understanding, or if there's code I'm missing. Either way its rather frustrating. I've included a picture of all my code, just incase some code may be interfering.

HTML:

CSS 1:

CSS 2:

Best practices for managing modules in a Node project

Posted: 28 May 2022 04:22 PM PDT

So I am building a project in node and for better separation and management of different concerns, I am trying to divide into different modules pieces of code that are not directly associated with my business logic (definitions, extended errors, etc).

For improved readability I am using internal packages exploiting this package.json syntax:

{        "dependencies": {          "@my-lib/module": "file:./path/to/file"      }    }  

I am aware of different more evolved tools for managing these kinds of situations or the possibility to create private npm packages but I would like to keep things simple and not deal with the overhead of learning new tools for now. Could this be considered good practice or something to totally avoid? I couldn't find a really satisfying answer searching around so thanks to anyone who can give me some insight or even a suggestion.

What is the current status of the Oauth 2.0 Assited Token Flow draft?

Posted: 28 May 2022 04:21 PM PDT

Does anyone know the current status of this draft http://www.watersprings.org/pub/id/draft-ideskog-assisted-token-00.html#:~:text=The%20OAuth%202.0%20authorization%20flow,the%20implicit%20grant%20type%20flow. regaring the Oauth Assisted Token Flow.

I tried to search on the internet, but was not able to find this auth flow as a widely adopted method.

I wonder what is the current status on this. I might as well contact the author of the draft.

Thanks

Spyder won't start in any environment or standalone

Posted: 28 May 2022 04:21 PM PDT

Spyder won't start in any environment or standalone.

  • In the command window (both conda terminal and cmd ) it doesn't throw any error just silently doesn't work.
  • When I try to start it by anaconda navigator it throws "Exit code: 3221225477".

I've tried,

  • Deleting the Anaconda and doing the clean installation several times.
  • Setting the Anaconda preferences as default.
  • python spyder --reset
  • checking hard disk health
  • diagnose memory problems

Why XOR value is empty in BitSet in java?

Posted: 28 May 2022 04:22 PM PDT

I just entered into Advance Java. I don't know why xor() function returning empty set. As i know, XOR return zero for two same bits and 1 for two different bits. So, if I XOR first two bit from Bits One and Bits two that is, 0 and 1 respectively, why does it return empty set. Please explain in detail, if possible and/or necessary.

Code

public class LearnBitSet {  public static void main(String[] args) {  BitSet bits1 = new BitSet(32);  BitSet bits2 = new BitSet(32);  for (int bitCount = 0; bitCount < 32; bitCount++) {          if (bitCount % 2 == 0){              bits1.set(bitCount);          }          if (bitCount % 5 != 0){              bits2.set(bitCount);          }      }  System.out.println("Bits One = " + bits1);  System.out.println("Bits Two = " + bits2);  // AND  bits1.and(bits2);  System.out.println("ADD = " +bits1);    // OR  bits1.or(bits2);  System.out.println("OR = "+bits1);  // XOR    bits1.xor(bits2);  System.out.println("XOR = "+bits1);  }  

}

OUTPUT

Bits One = {0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30}  Bits Two = {1, 2, 3, 4, 6, 7, 8, 9, 11, 12, 13, 14, 16, 17, 18, 19, 21, 22, 23, 24, 26, 27, 28, 29, 31}  ADD = {2, 4, 6, 8, 12, 14, 16, 18, 22, 24, 26, 28}  OR = {1, 2, 3, 4, 6, 7, 8, 9, 11, 12, 13, 14, 16, 17, 18, 19, 21, 22, 23, 24, 26, 27, 28, 29, 31}  XOR = {}  

Unknown Error Cause While Debugging WPF - 'System.AccessViolationException' occurred in SkiaSharp.dll

Posted: 28 May 2022 04:20 PM PDT

I am incredibly new to C# (my knowledge comes exclusively from YouTube tutorials), so please keep this in mind when viewing my novice code! I apologize in advance. I am trying to develop a WPF desktop application using VS2022. Without going into extensive detail, the application needs to be capable of loading and displaying SVG files, as well as storing the path data. For this, I am using the SkiaSharp and Skia.Svg nuget packages. As in the title, when the program tries to run the 'draw' function, it gives the following error:

An unhandled exception of type 'System.AccessViolationException' occurred in SkiaSharp.dll  Attempted to read or write protected memory. This is often an indication that other memory is corrupt.  

The following are how I initialized the canvas, as well as the 'draw' function itself:

canvas:

SKCanvas canvas;            public void CreateCanvas()          {                SKImageInfo info = new SKImageInfo(1920, 1080);              SKSurface surface = SKSurface.Create(info);              canvas = surface.Canvas;              canvas.Clear(SKColors.Empty);            }                    //not actually sure if this is an initializer oop...          public MainWindow()          {                InitializeComponent();              CreateCanvas();            }  

draw function:

        private void draw(string path, SKCanvas canvas)          {                var svg = new SKSvg();                svg.Load(path);                canvas.DrawPicture(svg.Picture);            }  

The "path" string is simply the filepath for the desired svg. The one I've been feeding it for debug purposes is on my desktop, and I am running VS as admin. Again, I'm new to this, so I'm not sure where the error lies or what really causes it. Seeking help in determining the root cause! Please let me know if you need more info, and thank you in advance.

Where should I addTarget() for UIButton in a custom UICollectionViewCell view or model?

Posted: 28 May 2022 04:20 PM PDT

I'm struggling with a UICollectionView list wherein I've defined a custom cell that has a custom UIControl subclass (checkbox button). I can addTarget() for that in the view or configuration data model, but not sure where to put the selector's callback function such that I can associate the callback it with cell itself (rather than the content view), or get indexpath, or whatever reasonably causes the data model/content/cell to refresh state based on the clicking of it, from within the UIContentView where the custom checkbox control is added as a subview.

The problem is that the UIContentView is not really integral to the cell where content view instance will be displayed in the collection, i.e. in terms of an API call inside the UIContenView that I can get a reference to the UICollectionViewCell when it's in the UICollectionView list.

I've added custom state as well to track the checkbox's state, and I can now set the custom state flag in the data model, but I'm not sure therefore how to trigger the refresh of content when the checkbox is clicked.

It's a lot of code and if I have to try to figure out a way to bring it in as an example, I will, but I'm hoping this scenario makes sense to people with more experience with it and they can just steer me in the right direction.

Besides the problem I'm having with that, everything works. I have a checkbox, label with SFsymbol, chevron disclosure ...

POST Status Code: 404 Not Found ERROR: Cannot POST /api/users/signup

Posted: 28 May 2022 04:23 PM PDT

I'm working on a project using react.js in the frontend and node.js in the backend. I keep getting a POST Status Code: 404 Not Found error in my code for my signup page. Specifically, I'm getting: Cannot POST /api/users/signup. I've gone over my code a number of times, and I can't figure out what could be causing this error. I would really appreciate any help or advice on why this could be occurring. Thank you!

Frontend:

SignInScreen:

import React, { useEffect, useState } from 'react';  import { useDispatch, useSelector } from 'react-redux';  import {signup} from "../actions/userActions";  import { useNavigate } from 'react-router-dom'      export default function SignupScreen(props) {        const [email, setEmail] = useState('');        const [password, setPassword] = useState('');        const [confirmPassword, setConfirmPassword] = useState('');         console.log(email, password, confirmPassword)          const userSignUp = useSelector((state) => state.userSignUp);        const { userInfo, loading, error } = userSignUp;              let navigate = useNavigate()          const dispatch = useDispatch();        const submitHandler = (e) => {          e.preventDefault();          if (password !== confirmPassword) {            alert('Password and confirm password do not match');          } else {            dispatch(signup( email, password));            navigate ('/onboarding')          }            }                return (          <div className="auth">              <h2>CREATE ACCOUNT</h2>              <form onSubmit={submitHandler}>                  <input                      type="email"                      id="email"                      name="email"                      placeholder="email"                      required={true}                      onChange={(e) => setEmail(e.target.value)}                  />                  <input                      type="password"                      id="password"                      name="password"                      placeholder="password"                      required={true}                      onChange={(e) => setPassword(e.target.value)}                  />                   <input                      type="password"                      id="password-check"                      name="password-check"                      placeholder="confirm password"                      required={true}                      onChange={(e) => setConfirmPassword(e.target.value)}                  />                  <input className="secondary-button" type="submit"/>              </form>          </div>        );      }  

userActions.js

import Axios from 'axios';  import {    USER_SIGNUP_FAIL,    USER_SIGNUP_REQUEST,    USER_SIGNUP_SUCCESS,  } from '../constants/userConstants';      export const signup = (email, password) => async (dispatch) => {      dispatch({ type: USER_SIGNUP_REQUEST, payload: { email, password } });      try {        const { data } = await Axios.post('/api/users/signup', {          email,          password,        });        dispatch({ type: USER_SIGNUP_SUCCESS, payload: data });        dispatch({ type: USER_LOGIN_SUCCESS, payload: data });        localStorage.setItem('userInfo', JSON.stringify(data));      } catch (error) {        dispatch({          type: USER_SIGNUP_FAIL,          payload:            error.response && error.response.data.message              ? error.response.data.message              : error.message,        });      }    };    

backend:

server.js

import express from 'express';  import cors from 'cors';  import mongoose from 'mongoose';  import dotenv from 'dotenv';  import {v4} from 'uuid';  import bcrypt from 'bcrypt';  import userRouter from './routers/userRouter.js';    dotenv.config();    const app = express()  app.use(cors())  app.use(express.json())    mongoose.connect(process.env.MONGODB_URL || 'mongodb://localhost/TC', {      useNewUrlParser: true,      useUnifiedTopology: true,      /*useCreateIndex: true,*/  });    app.use('/api/users', userRouter);  app.get('/', (req, res) => {      res.send('Server is ready');  })        app.use((err, req, res, next) => {      res.status(500).send({ message: err.message });  });    const port = process.env.PORT || 5000;  app.listen(port, () => {      console.log(`Serve at http://localhost:${port}`);  });    

userRouter.js

import express from 'express';  import expressAsyncHandler from 'express-async-handler';  import bcrypt from 'bcrypt';  import User from '../models/userModel.js';  import { generateToken, isAdmin, isAuth } from '../utils.js';    const userRouter = express.Router();    userRouter.post(      '/signup',      expressAsyncHandler(async (req, res) => {          const user = new User({              email: req.body.email,              password: bcrypt.hashSync(req.body.password, 8),          });          const createdUser = await user.save();          res.send({              _id: createdUser._id,              email: createdUser.email,              isAdmin: createdUser.isAdmin,              token: generateToken(createdUser),          });      }),  );    export default userRouter;  

Is there a way around SyntaxError: unexpected EOF while parsing? [closed]

Posted: 28 May 2022 04:22 PM PDT

I've tried everything, including changing input to raw_input. I'm just looking to see what I'm doing wrong?

Error

'Traceback (most recent call last): File "/Users/haydenbradford/Desktop/Python projects/Hospital Patient System/main.py", line 8, in selection = input("Enter 1 or 2 to Select an Option: ") File "", line 0

^  

SyntaxError: unexpected EOF while parsing

print("1: Find a Patient")  print("2: Add a Patient")    stage1 = 0    while stage1 == 0:        selection = input("Enter 1 or 2 to Select an Option: ")        if int(selection) < 3 and int(selection) > 0:          print("Entered " + str(selection))          break      elif len(selection) == 0:          print("Enter a number")      else:          print("Enter either 1 or 2")    print(selection)  

Compiler says to add type parameters, but I don't think I can in this context

Posted: 28 May 2022 04:22 PM PDT

The compiler complains that type annotations are needed. I was able to fix it by creating an unused variable with type parameters, commented out in the code snippet below. This feels like a weird workaround though, is there some way to add type parameters without needing to do this? It just seems like rust should know the type of key because Map is a defined type.

type Map = Arc<DashMap<[u8; 32], Session>>;    pub struct SessionManager {      map: Map,      db_wtx: WriteTx,      db_rtx: ReadTx,  }    impl SessionManager{      pub fn logout(&self, token: &str) {          if let Ok(decoded_vec) = base64::decode(token) {              if let Ok(key) = decoded_vec.try_into() {                  //let _typed_key: [u8; 32] = key;                  self.map.remove(&key);              }          }      }  }  

Error msg:

error[E0282]: type annotations needed     --> src/login_handler.rs:244:14      |  244 |             if let Ok(key) = decoded_vec.try_into() {      |                       ^^^    ---------------------- this method call resolves to `Result<T, <Self as TryInto<T>>::Error>`      |                       |      |                       cannot infer type  

edit: for clarity I'm using the dashmap crate, which tries to mimic the api of std::hashmap closely, but allows multithreaded access.

C++ program with no error goes into a never end input cycle

Posted: 28 May 2022 04:20 PM PDT

This is a simple binary search program, but for some reason, the program just doesn't move on after asking for the value of the key from the user. At first, I thought it is an issue with my compiler, but happens wherever I paste the code, and I don't know why.

#include <iostream>  using namespace std;    int binary(int arr[], int n, int k){      int s = 0;       int e = n;       int mid = (s+e)/2;       while(s<=e){          if(k==arr[mid]){              return mid;           }          else if(k>arr[mid]){              s = mid+1;           }          else if(k<arr[mid]){              e = mid-1;           }      }      return -1;  }    int main(){      int i, n, key = 4;      cin>>n;       int a[n];        for(i=0;i<n;i++){          cin>>a[i];      }      cout<<"Enter key:"<<endl;      cin>>key;        cout<< binary(a, n, key);     }  

instead of moving on after k, the code just does nothing.

Making a search form display inline with Bootstrap 5

Posted: 28 May 2022 04:24 PM PDT

I am trying to create a search form within a page using Bootstrap 5 and the following code:

        <div class="row mb-5">              <div class="col-lg-10 offset-lg-1">                  <form class="form-inline" role="form">                      <label for="field">Find all where...</label>                      <select id="field" class="form-select">                          <option value="company_name" selected>Company Name</option>                          <option value="federal_ein" selected>EIN</option>                          <option value="state">State</option>                          <option value="city">City</option>                      </select>                      <label for="term">includes...</label>                      <input type="text" class="form-control" id="term" placeholder="Enter full/partial term" name="term">                      <button type="submit" class="btn btn-primary btn-lg">Search</button>                  </form>              </div>          </div>  

I want the form to be inline, with the text box stretched to fill unused space in the row. I can't figure out how to achieve this. Any help on it? Thanks!

Flutter : best way to store maps locally?

Posted: 28 May 2022 04:23 PM PDT

what is the best way to store data locally. Assuming that I'm creating an app that stores transaction and I need to save id(because they may be many transactions with the same name), title, amount and time. Can I do it with shared preferences or is there another way to do it ? Thank you for answering.

How to create sorted linked list using array of structure in c

Posted: 28 May 2022 04:24 PM PDT

Here is student.txt file with some information and I took them to the array and I created a sorted linked list using the array, but it is not listing any information. I could not find why it is happening! Here is the onlineGDB session.

Who can find my mistake in the code and explain it?

Here is the code:

#include <stdio.h>  #include <stdlib.h>  #include <string.h>    struct studInfo {      int studNr;      char studName[12];      int grade;  };    struct node {      struct studInfo info;      struct node *link;  };    typedef struct node *NODEPTR;    NODEPTR getnode(void);  void fileIntoArray(struct studInfo allStudent[],int *num);  void sortByNum(struct studInfo allstudent[], NODEPTR *, int num);  void list(NODEPTR);    int main() {      struct studInfo allStudent[150];      NODEPTR headNum, headName;      int choice;      int num;            fileIntoArray(allStudent, &num);      sortByNum(allStudent, &headNum, num);      list(headNum);            return 0;  }    void fileIntoArray(struct studInfo allStudent[], int *num) {      FILE *ptr = fopen("student.txt", "r");      int i = 0;      while (!feof(ptr)) {          fscanf(ptr, "%d%s%d", &allStudent[i].studNr,                 allStudent[i].studName, &allStudent[i].grade);          i++;      }      *num = i;      fclose(ptr);  }    void sortByNum(struct studInfo allStudent[], NODEPTR *headNum, int num) {      NODEPTR head, p, save, prev;      head = NULL;      for (int i = 0; i <= num; ++i)  {          p = getnode();          p->info = allStudent[i];          if (head = NULL) {              head = p;              p->link = NULL;          } else {              if (p->info.studNr < head->info.studNr) {                  p->link = head;                  head = p;              } else {                  save = head;                  while ((save->info.studNr < p->info.studNr) &&(save != NULL)) {                      prev = save;                      save = save->link;                      if (save == NULL) {                          prev->link = p;                          p->link = NULL;                      } else {                          p->link = prev->link;                          prev->link = p;                      }                  }              }          }      }      *headNum = head;  }    void list(NODEPTR headNum) {      NODEPTR p = headNum;      int line = 0;      while (p->link != NULL) {          line++;          if (line > 25) {              printf("Tab a button\n");              getchar();              line = 1;          }          printf("%d %d  %s  %d\n", line, p->info.studNr,                 p->info.studName, p->info.grade);          p = p->link;      }  }    NODEPTR getnode() {      NODEPTR q;      q = (NODEPTR)malloc(sizeof(struct node));      return(q);  }  

Where is located the “needs-validation” class in Bootstrap 5?

Posted: 28 May 2022 04:20 PM PDT

It's a class used in the form component. One extract here: <form class="row g-3 needs-validation" novalidate> I don't put more because that snippet is enough to say that "needs validation" is a class that should be defined in the "bootstrap.css" file, which is the most complete, but nothing.

I used the cmd+F to search ".needs-validation" (withor without the prepend dot), in the open files of: bootstrap.css, bootstrap.js and bootstrap.bundle.js, but nothing. Or is it on the server somehow? From where is called that "needs-validation" class

Why Bi-LSTM Performed poorly?

Posted: 28 May 2022 04:24 PM PDT

I performed 8 machine learning algorithms on a transliterated English text there bi-lstm accuracy was very poor only 43% can anyone explain the reason behind it?

C/C++ Compilation terminated in VS Code [closed]

Posted: 28 May 2022 04:21 PM PDT

#include<iostream>  using namespace std;    int main()  {      int a=45;      float b=45.46;      int c = int (b);      cout<<"value of c is :"<<c<<endl;      cout<<"the sum is :"<<a + b<<endl;      cout<<"the sum is :"<<a + (int)b<<endl;      cout<<"the sum is :"<<a + int(b)<<endl;      return 0;  }  

Whenever I tried to compile it produce error.

g++.exe: error: use: No such file or directory  g++.exe: error: of: No such file or directory  g++.exe: error: setw: No such file or directory  g++.exe: error: function.cpp: No such file or directory  g++.exe: error: of: No such file or directory  g++.exe: error: setw: No such file or directory  g++.exe: error: function: No such file or directory  g++.exe: fatal error: no input files  compilation terminated.  
typecasting.cpp: In function 'int main()':  typecasting.cpp:9:11: error: unable to find string literal operator 'operator""a' with 'const char [13]', 'unsigned int' arguments       cout<<"the sum is :"a+b;             ^~~~~~~~~~~~~~~  typecasting.cpp:10:11: error: unable to find string literal operator 'operator""a' with 'const char [13]', 'unsigned int' arguments       cout<<"the sum is :"a+(int)b;             ^~~~~~~~~~~~~~~  typecasting.cpp:11:11: error: unable to find string literal operator 'operator""a' with 'const char [13]', 'unsigned int' arguments       cout<<"the sum is :"a+int(b);             ^~~~~~~~~~~~~~~  

How to apply Interface segregation principle?

Posted: 28 May 2022 04:23 PM PDT

I have a public interface that creates a bunch of different specific objects by client, and the only thing in common is that they all need to be serialized as xmls.

Something like this:

public interface IBuildXmlService  {      XmlObject1 BuildClient1Xml(CustomObjectWithClient1Data data);      XmlObject2 BuildClient2Xml(CustomObjectWithClient2Data data);      XmlObject3 BuildClient3Xml(string string1, int int1);      XmlObject4 BuildClient4Xml(CustomObjectWithClient4Data data);  }  

Now this interface started to get big, and I'm definitely sure this is not a good sign. Also every time I inject the interface into a client specific class, that client specific class has access to all the other object creation methods for other clients.

Now the first thing I thought about was to just move the object creation method as a private method in client specific class, but this results in quite some big files.

Then I thought to use the factory method pattern to create a IXmlFactory with a BuildXml method for the object creation part, but this doesn't seem to work since I have different objects to return.

Can anyone give me some advice about what design pattern should I look for?

A .db file won't open from the server, but will open when copied to hard drive

Posted: 28 May 2022 04:21 PM PDT

I have a strange issue where I can not open a .db file from my server using RSQLite package in R, but when I copy the file onto my HD I can open it. Other .db files on the server open fine without this error.

It's not a permissions issue for the folder, as I can copy a .db file from another folder into this folder and open it fine. The ls -l command on the NAS shows that I have rwx access and all of the other .db files in other folders have the same permissions anyway.

Finally, if I move the offending .db file into another folder on the server, I still can not open it.

enter image description here

Issue with merge task for CDC snowflake using stream and task

Posted: 28 May 2022 04:22 PM PDT

I have a basic task which merges data from the source table into the target table using a stream.

Creating the tables and stream

create or replace table source_json_table_trial(  v variant  );    create or replace table target_json_table_trial like source_json_table_trial;    create stream if not exists source_to_target_stream_trial on table source_json_table_trial  SHOW_INITIAL_ROWS = TRUE;  

Merge Task

create or replace task stage_task_json_trial  warehouse = COMPUTE_WH  schedule = '1 minute'  when  SYSTEM$STREAM_HAS_DATA('source_to_target_stream_trial')  AS  merge into target_json_table_trial a1 using source_to_target_stream_trial b1   on a1.v:pd:product_id = b1.v:pd:product_id   WHEN MATCHED AND METADATA$ACTION = 'INSERT' AND METADATA$ISUPDATE = 'TRUE'  then update set a1.v = b1.v, a1.lastUpdatedTimestamp= current_timestamp  WHEN NOT MATCHED AND METADATA$ACTION = 'INSERT' AND METADATA$ISUPDATE = 'FALSE'  then insert values (b1.v, current_timestamp)  WHEN MATCHED AND METADATA$ACTION = 'INSERT' AND METADATA$ISUPDATE = 'FALSE'  then update set a1.v = b1.v, a1.lastUpdatedTimestamp=current_timestamp  ;   

If the target has a row of id 1

INSERT INTO target_json_table_trial SELECT parse_json('{    "pd": {      "extraction_date": "1652787650",      "product_id": "1",      "product_name": "Product 1",      "retailerName": "Retailer 1"    }  }');      

And I insert multiple rows of same id to source at the same time

INSERT INTO source_json_table_trial SELECT parse_json('{    "pd": {      "extraction_date": "1652787660",      "product_id": "1",      "product_name": "Product 2",      "retailerName": "Retailer 2"    }  }');     INSERT INTO source_json_table_trial SELECT parse_json('{    "pd": {      "extraction_date": "1652787670",      "product_id": "1",      "product_name": "Product 3",      "retailerName": "Retailer 3"    }  }');   

The new data doesn't update and is stuck in the stream.

Any ideas on what's causing this issue and how to fix it?

Force User to Select Slicer/Parameter Before Executing SQL

Posted: 28 May 2022 04:23 PM PDT

My Power Query expression is mostly a SQL query, taking advantage of query folding with a Snowflake SQL database. My where clause references two parameters that an end user sets in slicers:

WHERE Time BETWEEN '" & Date.ToText(DateTime.Date(StartTimeParameter)) & "' AND '" & Date.ToText(DateTime.Date(EndTimeParameter)) & "'  

How can I require that the user selects the slicer/parameter value before the SQL is executed? Currently the SQL executes when the report is opened, and again when the parameter is changed. Perhaps I can make better default values, but most users will still need to adjust the slicers/parameters. The full SQL is complex and has a noticeable load time. I have tried making the two parameters optional, but the Power Query expression becomes invalid:

Expression.Error: We cannot convert the value null to type Text.

How do I add job posting schema in my wordpress posts using pandas

Posted: 28 May 2022 04:24 PM PDT

I have this code for adding schema:

schm="<script type="application/ld+json">{      "@context": "http://schema.org/",      "@type": "JobPosting","title" : "",      "description" : "",      "datePosted" : "",      "hiringOrganization": {          "@type": "Organization",          "name": ""},      "employmentType": [],      "jobLocation": {          "@type": "Place",          "address": {              "streetAddress": "",              "addressLocality": "","addressRegion": "",              "addressCountry": "United States"          }      }  }  </script>",  

Then I use this variation for job schema:

def schema(variable):              job='<!-- wp:html -->'+variable<!-- /wp:html -->'              return job  

I combine these two variations like this:

content=wpp(s1p1+s2p2)+schema(schm)  wpp(s1p1+s2p2)   

this is my content part (which doesn't have problems, this part is working)

schema(schm) is the variation that is not working. schema does not add in my WordPress post How do I solve it https://prnt.sc/vDJS4SaADP1a

String matching in CUDA shows different result when increase blocks

Posted: 28 May 2022 04:21 PM PDT

I'm trying to implement string matching program with CUDA in C and I have th following issue.

When I set 1 block and 1 thread per block the result for pattern dfh is 2. That's correct, but when I increase the blocks the result is 4.

The text file is:

ffskdfhksdjhfksdfksjdfhksdhfksjdhfkjer654yrkhjkfgjhdsrtrhkjchgkjthyoirthygfnbkjgkjdhykhkjchgkjfdhsfykhkbhkjfghkfgjy

This is my code:

#include <stdio.h>  #include <stdlib.h>  #include <string.h>  #include <cuda.h>    __global__ void string_matching(char *buffer, char *pattern, int match_size, int pattern_size, int *result){      int tid, i;      __shared__ int local_matches;        if(threadIdx.x == 0) local_matches = 0;        __syncthreads();        for(tid=blockIdx.x*blockDim.x+threadIdx.x; tid<match_size; tid+=blockDim.x){          for (i = 0; i < pattern_size && pattern[i] == buffer[i + tid]; ++i);          if(i >= pattern_size){              atomicAdd(&local_matches, 1);          }      }        __syncthreads();        if(threadIdx.x == 0)           atomicAdd(result, local_matches);    }      int main(int argc, char *argv[]){      FILE *pFile;      long file_size, match_size, pattern_size;      char * buffer;      char * filename, *pattern;      size_t result;      int *match, total_matches;        //CUDA variables      int blocks, threads_per_block;      int *result_dev;      char *buffer_dev, *pattern_dev;        float total_time, comp_time;      cudaEvent_t total_start, total_stop, comp_start, comp_stop;      cudaEventCreate(&total_start);      cudaEventCreate(&total_stop);      cudaEventCreate(&comp_start);      cudaEventCreate(&comp_stop);        if (argc != 5) {          printf ("Usage : %s <file_name> <string> <blocks> <threads_per_block>\n", argv[0]);          return 1;      }      filename = argv[1];      pattern = argv[2];      blocks = strtol(argv[3], NULL, 10);      threads_per_block = strtol(argv[4], NULL, 10);            pFile = fopen ( filename , "rb" );      if (pFile==NULL) {printf ("File error\n"); return 2;}        // obtain file size:      fseek (pFile , 0 , SEEK_END);      file_size = ftell (pFile);      rewind (pFile);      printf("file size is %ld\n", file_size);            // allocate memory to contain the file:      buffer = (char*) malloc (sizeof(char)*file_size);      if (buffer == NULL) {printf ("Memory error\n"); return 3;}        // copy the file into the buffer:      result = fread (buffer,1,file_size,pFile);      if (result != file_size) {printf ("Reading error\n"); return 4;}             pattern_size = strlen(pattern);      match_size = file_size - pattern_size + 1;            match = (int *) malloc (sizeof(int)*match_size);      if (match == NULL) {printf ("Malloc error\n"); return 5;}        cudaMalloc((void **)&result_dev, sizeof(int));      cudaMalloc((void **)&buffer_dev, file_size*sizeof(char));      cudaMalloc((void **)&pattern_dev, pattern_size*sizeof(char));        cudaEventRecord(total_start);        cudaEventRecord(comp_start);        cudaMemcpy(buffer_dev, buffer, file_size*sizeof(char), cudaMemcpyHostToDevice);      cudaMemcpy(pattern_dev, pattern, pattern_size*sizeof(char), cudaMemcpyHostToDevice);        string_matching<<<blocks, threads_per_block>>>(buffer_dev, pattern_dev, match_size, pattern_size, result_dev);      cudaThreadSynchronize();        cudaEventRecord(comp_stop);      cudaEventSynchronize(comp_stop);      cudaEventElapsedTime(&comp_time, comp_start, comp_stop);        cudaMemcpy(&total_matches, result_dev, sizeof(int), cudaMemcpyDeviceToHost);        cudaEventRecord(total_stop);      cudaEventSynchronize(total_stop);      cudaEventElapsedTime(&total_time, total_start, total_stop);        cudaFree(result_dev);      cudaFree(buffer_dev);      cudaFree(pattern_dev);        fclose (pFile);      free (buffer);        //Print result      printf("Total matches: %d\n", total_matches);        printf("\n\n\nN: %d, Blocks: %d, Threads: %d\n", file_size, blocks, blocks*threads_per_block);      printf("Total time (ms): %.3f\n", total_time);      printf("Kernel time (ms): %.3f\n", comp_time);      printf("Data transfer time(ms): %.3f\n\n\n", total_time-comp_time);    }  

How to load extension within chrome driver in selenium with python

Posted: 28 May 2022 04:23 PM PDT

All my efforts to open chrome browser with Browsec extension enabled are failing. Here is what i tried in last -

# Configure the necessary command-line option.  options = webdriver.ChromeOptions()  options.add_argument(r'--load-   extension=C:\Users\lap0042\AppData\Local\Google\Chrome\User   Data\Default\Extensions\omghfjlpggmjjaagoclmmobgdodcjboh')    # Initalize the driver with the appropriate options.  driver = webdriver.Chrome(chrome_options=options)    driver.get("http://stackoverflow.com")  

This results in error "Failed to load extension from . Manifest files is missing or unreadable"

After search for this error I get that Manifest.json file should be renamed to manifest.json.txt but doing this resulted in same error.

Any help will be highly appreciated

enter image description here

How to request administrator privileges?

Posted: 28 May 2022 04:21 PM PDT

Applications must be run with administrator privileges. How to ask the user is? How to verify that he agreed to? How do I know whether already running application as an administrator?

Made as described here by the user ChrisW67. The result is not received. If possible, give an example of "Hello world" project.

P.S Windows 7. Am writing in Qt Creator. Qt5.2

No comments:

Post a Comment