Saturday, May 1, 2021

Recent Questions - Stack Overflow

Recent Questions - Stack Overflow


Cycles in a graph

Posted: 01 May 2021 08:09 AM PDT

I have to find an algorithm that prints the number of cycles in a graph. the following example should print that the case only 1 cycle.

enter image description here

how to open a python project from anotther project

Posted: 01 May 2021 08:09 AM PDT

I am trying to make a python3 project which is a personal assistant and when computer asks the user to choose what they would like: a calculator, email sender or the weather. i made separate projects for each of the functions the user could use and in my main project I want to open them up so the computer could run it. I tried using os.system because I read that somewhere but I don't really know how ,here is the code:

from random import choice  import os  import time      print(''' LOADING PERSONAL ASSISTANT...  ''')  time.sleep(1)    user_choice = input('Welcome to your personal assistant what would you like to use: Email Sender(E),    Weather(W), Calculator(C): ')    if user_choice == ("E"):      os.system("emailsender.py")  elif user_choice == ("W"):      os.system("weather.py")  elif user_choice == ("C"):      os.system("calculator.py")  

please answer fast I need the help as soon as possible

Change SVG attribute (width, height, viewBox, and transform) to remove padding from the inner drawing

Posted: 01 May 2021 08:09 AM PDT

I have an SVG (https://drive.google.com/open?id=1SBA2Xsi228agUO65FmtLwjg6Zuoq59-5) which is shifted. I have tried to change parameters such as width, height, viewBox, and transform attributes. I do not have a clear understanding of this area and it is not as simple as I estimated. I need to draw only the below part and remove the padding.

enter image description here

tesseract not found error occuring in IDLE but not in terminal...I am very confused as to why

Posted: 01 May 2021 08:09 AM PDT

I am working on some OCR and chose to use tesseract as the library. So, I installed it using the pip command in the terminal and when I tested the library with a sample image it seems to be working fine(in the terminal). I have no idea why it wouldn't work in IDLE and python versions of the idle and terminal are the same down to the exact detail. Can someone help me with this?

thanks!

Python String object does not support error

Posted: 01 May 2021 08:09 AM PDT

I am learning python and while i was working on this exercise...

student_scores = input("Input a list of student scores here ")

for n in range(0, len(student_scores)): student_scores[n] = int(student_scores[n]) print(student_scores)

highest_score = max(student_scores) print(highest_score)

i got the below error: line 5, in student_scores[n] = int(student_scores[n]) TypeError: 'str' object does not support item assignment

Printing a 2 bytes packet

Posted: 01 May 2021 08:09 AM PDT

There is a 2 bytes packet. And first 5 bits represent version, next 5 bits represent type and the last 6 bits represent value. And I am passing the packet as char* to a function(print_pak). And in that function I want to print the packet version, packet type and packet value. How can I do that?

void print_pak(char* pak) { }

How to run unit tests against a go web app?

Posted: 01 May 2021 08:09 AM PDT

What is the best way to run tests against a sizable web app? i.e. the app is web-based and the tests are command-line based.

The web app starts and has lots of handlers, background daemons, etc.

I'm trying to test the underlying code. Not the HTTP requests etc.

'<>' cannot be used with anonymous classes

Posted: 01 May 2021 08:09 AM PDT

I moved my project in a new project with different foldels named (root\Model, rood\View, root\Control) The source moved from the old project has been moved all in "Model" folder. The source code is identical, in first project works propertly and in second project an error happened: "'<>' cannot be used with anonymous classes".

The differences between first project and second project are just "subfolders" for classes and package on the top. Any suggest? Thanks

enter image description here

Problem with docker installation on 32 bit machine

Posted: 01 May 2021 08:09 AM PDT

I've successfully installed docker on my Debian i686 machine with command sudo apt-get install docker.io (source: https://stackoverflow.com/a/48881019/) . The installation was completed without errors but I can't use docker-compose. When I launch nano /usr/local/bin/docker-compose I see "Not found" and after many research I see that error is because docker-compose didn't find any compatible architecture. How can I fix it? Thanks

Label text out of frame in Tkinter

Posted: 01 May 2021 08:09 AM PDT

I have the following issue. I created a frame with a scrollbar in tkinter. The frame has a label which takes information from a json file and it loads it there. Here's the code:

    second_frame = Frame(canvas)            canvas.create_window((0,0), window=second_frame, anchor='nw')        label = Label(second_frame, text=str(info), anchor='e', justify=LEFT)      label.pack()  

The problem is that when a sentence is too long, it gets out of the frame, which is weird because I thought that these labels had an automatic system to detect when it gets out of the frame. Here's an example:

enter image description here

The program took this text from the json file:

"\nThis is Matt\nIf I press enter, everything is fine.\nBut if I don't enter and make this sentence too long, the text will get out of the frame.\n"  

What am I doing wrong? Thanks in advance!

What is the Time and space complexity of this Sorting Technique? Analyze it

Posted: 01 May 2021 08:09 AM PDT

def sort(arr): A = [] for i in range(len(arr)): mn = min(arr) arr.remove(mn) A.append(mn) del arr return A

Is it possible to use Policy-based authorization in a Hosted Service?

Posted: 01 May 2021 08:08 AM PDT

I have a ASP.Net Core 3.1 API that uses Policy-based authorization. The authorization is made in Authorization Handlers in a class library. I check authorization like this:

var azResult = await _authHandler.AuthorizeAsync(principal, userDto, Operations.Create);  

Above code works fine in ASP.NET Core. But if I use the same code from a console app (Generic Host/Hosted Service) the handler is never called. I have registered the handler:

services.AddScoped<IAuthorizationHandler, IUserAuthorizationHandler>();  

and in the serviceCollection and I have called:

services.AddAuthorizationCore();  

The AddAuthorizationCore extension is located in a ASP.NET Core assembly so I guess it only works when using ASP.NET, not a Console app.

Does anyone know if it is possible to use Authorization handlers in a console app?

Firebase database set objects in favorite list

Posted: 01 May 2021 08:08 AM PDT

I have a problem clearing list in fragment. I need to clear the list when happening update in fragment. I already put it in different places but it does not help me.

When update happens in fragment it show same list but that list also add elements from previous list. If I put list.clear(); in moment when it rakes arguments from firebase it did not give me needed effect, when I put it in onCreate() method then app give me error .

public class Favourite extends Fragment {    private RecyclerView recyclerView;  private ArrayList<TourReader1> artistList;  private ToursAdapter1 adapter1;  private DatabaseReference reference,reference2;  String uid;    public Favourite() {      // Required empty public constructor  }    @Override  public void onCreate(Bundle savedInstanceState) {      super.onCreate(savedInstanceState);      if (getArguments() != null) {          mParam1 = getArguments().getString(ARG_PARAM1);          mParam2 = getArguments().getString(ARG_PARAM2);      }      FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();      //Get current user id      uid = user.getUid();      //Connect to specific point in database Tours      reference = FirebaseDatabase.getInstance().getReference("Tours");      //Create add to method valuelistener or reference which is specific point in database      reference2 = FirebaseDatabase.getInstance().getReference("user").child(uid);      reference.addValueEventListener(valueEventListener);      reference.keepSynced(true);    }  ValueEventListener valueEventListener = (new ValueEventListener() {      @Override      public void onDataChange(@NonNull DataSnapshot snapshot1) {              //get all information from specific point of database              for (DataSnapshot datasnapshot : snapshot1.getChildren()) {                  //get current name of starting point from where we recive information from database                  String firstname = datasnapshot.getKey();                  //valuelistener for another point from database                  reference2.addValueEventListener(new ValueEventListener() {                      @Override                      public void onDataChange(@NonNull DataSnapshot snapshot) {                              for (DataSnapshot dSnapshot2:snapshot.getChildren()){                                  String seconame = dSnapshot2.getKey();                                  Boolean control = dSnapshot2.child("like").getValue(Boolean.class);                                  if(control != null&&firstname.equals(seconame) &&control.equals(true)) {                                      TourReader1 artist = datasnapshot.getValue(TourReader1.class);                                      artistList.add(artist);                                  }                              }                          adapter1.notifyDataSetChanged();                      }                        @Override                      public void onCancelled(@NonNull DatabaseError error) {                        }                  });              }      }      @Override      public void onCancelled(@NonNull DatabaseError databaseError) {        }  });    @Override  public View onCreateView(LayoutInflater inflater, ViewGroup container,                           Bundle savedInstanceState) {      // Inflate the layout for this fragment      artistList = new ArrayList<>();      View rootview = inflater.inflate(R.layout.favourite, container, false);      recyclerView = rootview.findViewById(R.id.list);      recyclerView.setHasFixedSize(true);      recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));      adapter1 = new ToursAdapter1(getContext(), artistList);      recyclerView.setAdapter(adapter1);      GridLayoutManager mGridLayoutManager = new GridLayoutManager(getContext(), 2);      recyclerView.setLayoutManager(mGridLayoutManager);      return rootview;  }  

}

Sum of all nodes in a binary tree giving incorrect output in JavaScript

Posted: 01 May 2021 08:08 AM PDT

I am trying to solve the following problem. Problem statement: Given a binary tree, return the sum of the depth of all the nodes. For example, this is a binary tree.

          1         /     \        2       3      /   \   /   \     4     5 6     7   /   \  8     9  

The depth of the node with value 2 is 1. Similarly, the Depth of node with value 4 is 2 etc... The total depth of all nodes is 16. I have written the following recursive solution which is giving me the incorrect output. My pseudocode is as follows :

If the current node has no left and right child, then return;  Check if the current node has any left child. If it has, then:     Add 1 to depthSoFar variable     Add the depthSoFar value to totalDepth variable     Then, recursively call the function with the left child as the current node  If the current node has the right child, then:         Add 1 to depthSoFar variable        Add the depthSoFar value to totalDepth variable        Then, recursively call the function with the right child as the current node  

The code is as follows;

var nodeDepths = function(root) {        var totalDepth = 0;      function depth(root, depthSoFar) {          if (root.left === null && root.right === null) {              return;          }          // checking if it has left child          if(root.left) {              depthSoFar = depthSoFar + 1;              // Add it to total              totalDepth = totalDepth + depthSoFar;              depth(root.left, depthSoFar);          }          if(root.right) {              depthSoFar = depthSoFar + 1;              totalDepth = totalDepth + depthSoFar;              depth(root.right, depthSoFar);          }      }      depth(root, 0);      return totalDepth;  };  

My output is 22 but the correct output is 16. I am not understanding where I am getting wrong. Any help in understanding the problem, would be appreciated. Thanks in advance.

Transform this HTML/CSS/JS CODE to a React Component

Posted: 01 May 2021 08:08 AM PDT

Can anybody help me convert this to a React component, I've been on it for hours with no hope of success. I'm relatively new to react and this has been particularly difficult for me. Sorry, and Thanks in advance. Can anybody help me convert this to a React component, I've been on it for hours with no hope of success. I'm relatively new to react and this has been particularly difficult for me. Sorry, and Thanks in advance. Can anybody help me convert this to a React component, I've been on it for hours with no hope of success. I'm relatively new to react and this has been particularly difficult for me. Sorry, and Thanks in advance.

// ——————————————————————————————————————————————————  // TextScramble  // ——————————————————————————————————————————————————    class TextScramble {    constructor(el) {      this.el = el      this.chars = '!<>-_\\/[]{∫∆₳₴Ω∏∑≤≠₰₩}—=+*^?#_____'      this.update = this.update.bind(this)    }    setText(newText) {      const oldText = this.el.innerText      const length = Math.max(oldText.length, newText.length)      const promise = new Promise((resolve) => this.resolve = resolve)      this.queue = []      for (let i = 0; i < length; i++) {        const from = oldText[i] || ''        const to = newText[i] || ''        const start = Math.floor(Math.random() * 40)        const end = start + Math.floor(Math.random() * 40)        this.queue.push({ from, to, start, end })      }      cancelAnimationFrame(this.frameRequest)      this.frame = 0      this.update()      return promise    }    update() {      let output = ''      let complete = 0      for (let i = 0, n = this.queue.length; i < n; i++) {        let { from, to, start, end, char } = this.queue[i]        if (this.frame >= end) {          complete++          output += to        } else if (this.frame >= start) {          if (!char || Math.random() < 0.28) {            char = this.randomChar()            this.queue[i].char = char          }          output += `<span class="dud">${char}</span>`        } else {          output += from        }      }      this.el.innerHTML = output      if (complete === this.queue.length) {        this.resolve()      } else {        this.frameRequest = requestAnimationFrame(this.update)        this.frame++      }    }    randomChar() {      return this.chars[Math.floor(Math.random() * this.chars.length)]    }  }    // ——————————————————————————————————————————————————  // Example  // ——————————————————————————————————————————————————    const phrases = [    'Neo,',    'later',    'realize',    'just',    'difference',    'between',    'path'  ]    const el = document.querySelector('.text')  const fx = new TextScramble(el)    let counter = 0  const next = () => {    fx.setText(phrases[counter]).then(() => {      setTimeout(next, 800)    })    counter = (counter + 1) % phrases.length  }    next()
@import 'https://fonts.googleapis.com/css?family=Roboto+Mono:100'  html, body    font-family 'Roboto Mono', monospace    background #212121    height 100%  .container    height 100%    width 100%    justify-content center    align-items center    display flex  .text    font-weight 100    font-size 28px    color #FAFAFA  .dud    color #757575
<div class="container">    <div class="text">s</div>  </div>

How is the result of the query using both filters in MongoDB even though only one is ever passed due to the if else statement?

Posted: 01 May 2021 08:07 AM PDT

So here's the code in question. I thought since it has if statements for each filter, it will only filter by one parameter, that being the one it finds first and skips the rest but when it actually makes the query later in the code somehow both filters are applied in the response. Am I missing something?

Even console logging while calling it with two parameters results in only one property in the query object.

 static async getRestaurants({          filters = null,          page = 0,          restaurantsPerPage = 20,      } = {}) {  let query            if (filters) {              if ("name" in filters) {                  query = { $text: { $search: filters["name"] } }              } else if ("cuisine" in filters) {                  query = { "cuisine": { $eq: filters["cuisine"] } }              } else if ("zipcode" in filters) {                  query = { "address.zipcode": { $eq: filters["zipcode"] } }              }          }          console.log(filters)          let cursor            try {              cursor = await restaurants                  .find(query)          } catch (e) {              console.error(`Unable to issue find command, ${e}`)              return { restaurantsList: [], totalNumRestaurants: 0 }          }          const displayCursor = cursor.limit(restaurantsPerPage).skip(restaurantsPerPage * page)            try {              const restaurantsList = await displayCursor.toArray()              const totalNumRestaurants = await restaurants.countDocuments(query)                return { restaurantsList, totalNumRestaurants }          } catch (e) {              console.error(                  `Unable to convert cursor to array or problem counting documents, ${e}`              )              return { restaurantsList: [], totalNumRestaurants: 0 }          }  

Cannot read json file downloaded from s3 bucket

Posted: 01 May 2021 08:09 AM PDT

For context, I have a json file that I am reading in with the following code:

with open("file.json", "w") as jsonFile:      data = json.load(jsonFile)  

Then, I modify this list based on some other information:

for key in data:      if key == label_file[-len(key):]:          print(data)          del data[key]          print(data)  

I know that this del call is actually working properly because I can see the actual json file being modified. Then, I update this file in the bucket through these lines

with open('file.json', 'w', encoding='utf-8') as updatedFile:      json.dump(data, updatedFile, ensure_ascii=False, indent=4)      s3.Bucket('bucket-name').upload_file(os.path.abspath('file.json'), 'file.json', ExtraArgs={'ContentType': "application/json"})  

Reading the json file before updating the file works completely fine. Additionally, I can read from the json file if it is stored locally. However, in the case that I download the json file immediately from the bucket, the program crashes on data = json.load(file).

Additionally, I've tried replacing the text in the downloaded json file with exactly what's in the local one, and it still crashes so I believe it is some file type issue with the S3 bucket.

Can't put a space between output and input on the same line

Posted: 01 May 2021 08:08 AM PDT

After printing, if I write the name I get:

Insert a name :John

There is no space before John, even if I put the space in the output. How can I add a space before writing the name?

#include <stdio.h>    int main() {      int string[8];      printf("\nInsert a name : ");      printf(" ");      scanf("%s", string);      printf("\nThe name is : %s", string);      return 0;  }  

GET request gives 404 error express js even though I have a well defined route in my express server

Posted: 01 May 2021 08:08 AM PDT

I am using Jquery's ajax request to get a JSON object from the server however when the request is invoked it gives a 404 error that looks like this:

Failed to load resource: the server responded with a status of 404 (Not Found) profile_data?uid=HW3gAHeiuJbQLMFQMbHA6nNlFUT2&_=1619880251360:1

As far as I am concerned all is done according to standard which is CRUD = Create:POST, Read:GET,Update:PUT and delete: DELETE. Please let me no of anything in my execution is wrong Here is the get request:

$(document).ready(()=>{              $.ajax({                url: '/profile_data',                type: 'GET',                cache: false,                data: { "uid": uid},                success: function(data){                  //Instantiate Variables of User Data                                    }                , error: function(jqXHR, textStatus, err){                  alert('text status '+textStatus+', err '+err)                }              });              });            } else {            Window.locate.assign("/login");          }    });  

This is the server side code:

app.get("/profile_data",   function (req, res){      const current_user = req.body;      const uid = current_user.uid;      console.log(uid)      db.ref("user_file_ref").on("value", snapshot=>{          snapshot.forEach( dataSnapshot=>{              if(uid === dataSnapshot.val().user_id){                  getFileFromNet(dataSnapshot.val().ipfs_ref).then( result =>{                      const hash = JSON.parse(result);                      let decrypted_string = decrypt(hash);                      let return_data = JSON.parse(decrypted_string);                      //console.log("Here!!")                      res.send(return_data);                  }).catch(err =>{                      console.log(err);                  });                  }          })      })  });  

How to properly return null/empty object in C++?

Posted: 01 May 2021 08:09 AM PDT

I am Java developer and trying to solve a simple C++ task. In Java, if I want to return an empty/null object, to indicate that object is not found I just return null. Example:

Person getGetByName(String name) {      for(int i = 0 ;i<10 ;i++) {      if(people[i].name == name){    return people[i];     }    }  return null;   }    // later in code I can do   P p = getByName("Sam");         if(p == null) { ... }   

In C++ I have the following method

It seems that if I declare a method like the above, returning NULL is not an option since the method doesn't return a pointer but rather a class. So what do I return to indicate that no person is found ?

How to filter out number and . from text using Excel formula in excel

Posted: 01 May 2021 08:09 AM PDT

I have the following text cell values:

31.55c/kWh  49.66c/kWh  12.84 cents/kWh  19.24 cents/kWh  15.30 cents/day  15.30 cents/day  12 cents/kWh data  7 cents/kWh data  

I have written the below formula, but not able to filter the required data (starting cell no.: B2):

{=IF(".",(LEFT(B2, MATCH(TRUE,ISERROR(VALUE(MID(B2,ROW(INDIRECT("1:"&LEN(B2))),1))),0))+2),(LEFT(B2, MATCH(TRUE,ISERROR(VALUE(MID(B2,ROW(INDIRECT("1:"&LEN(B2))),1))),0))))}  

Can anyone help me out with this!

Expected Result:

31.55  49.66  12.84  19.24  15.3  15.3  12  7  

Combine: rowwise(), mutate(), across(), for multiple functions

Posted: 01 May 2021 08:09 AM PDT

This is somehow related to this question: In principle I try to understand how rowwise operations with mutate across multiple columns applying more then 1 functions like (mean(), sum(), min() etc..) work.

I have learned that across does this job and not c_across. I have learned that the function mean() is different to the function min() in that way that mean() doesn't work on dataframes and we need to change it to vector which can be done with unlist or as.matrix -> learned from Ronak Shah hereUnderstanding rowwise() and c_across()

Now with my actual case: I was able to do this task but I loose one column d. How can I avoid the loose of the column d in this setting.

My df:

df <- structure(list(a = 1:5, b = 6:10, c = 11:15, d = c("a", "b",   "c", "d", "e"), e = 1:5), row.names = c(NA, -5L), class = c("tbl_df",   "tbl", "data.frame"))  

Works not:

df %>%     rowwise() %>%     mutate(across(a:e),            avg = mean(unlist(cur_data()), na.rm = TRUE),           min = min(unlist(cur_data()), na.rm = TRUE),            max = max(unlist(cur_data()), na.rm = TRUE)    )    # Output:        a     b     c d         e   avg min   max      <int> <int> <int> <chr> <int> <dbl> <chr> <chr>  1     1     6    11 a         1    NA 1     a      2     2     7    12 b         2    NA 12    b      3     3     8    13 c         3    NA 13    c      4     4     9    14 d         4    NA 14    d      5     5    10    15 e         5    NA 10    e   

Works, but I loose column d:

df %>%     select(-d) %>%     rowwise() %>%     mutate(across(a:e),            avg = mean(unlist(cur_data()), na.rm = TRUE),           min = min(unlist(cur_data()), na.rm = TRUE),            max = max(unlist(cur_data()), na.rm = TRUE)    )          a     b     c     e   avg   min   max    <int> <int> <int> <int> <dbl> <dbl> <dbl>  1     1     6    11     1  4.75     1    11  2     2     7    12     2  5.75     2    12  3     3     8    13     3  6.75     3    13  4     4     9    14     4  7.75     4    14  5     5    10    15     5  8.75     5    15  

How do I handle an error ''list index out of range" as an exception?

Posted: 01 May 2021 08:07 AM PDT

The thing is , that I am given some code and it is structured this way that we expect some accesses to not - initialised elements in the list. (I don't want to change the logic behind it, because it deals with some math concepts ). But I've been given the code in some other language and I want to do the same with python (handling this exception and let the program run).

a = []  for i in range(1,10,2): a.append(i)  for j in range(10):      try:          a[i] +=1      finally:          a.append(1)    ---------------------------------------------------------------------------  IndexError                                Traceback (most recent call last)  <ipython-input-2-edc940b2697a> in <module>        3 for j in range(10):        4     try:  ----> 5         a[i] +=1        6     finally:        7         a.append(1)    IndexError: list index out of range  

I then tried something else (after reading a similar stack overflow post)

a = []  for i in range(1,10,2): a.append(i)  for j in range(10):            if(a[j]): a[j] +=1      else:          a.append(1)  ndexError                                Traceback (most recent call last)  <ipython-input-4-324628aa850d> in <module>        3 for j in range(10):        4   ----> 5     if(a[j]): a[j] +=1        6     else:        7         a.append(1)    IndexError: list index out of range              

As you can see the error , persisted.

Find intersection between a mask and a texture picture in python

Posted: 01 May 2021 08:09 AM PDT

I would like to find the intersection between my mask that it's like this:

enter image description here

And the textured image:

enter image description here

I wanted something like this, but without the blue line (it's just to see more the difference) and without the info in the borders: enter image description here

Thanks!!!!

EDIT: That's my code by now:

from PIL import Image  import os  from PIL import Image, ImageFont, ImageDraw  import numpy as np  import cv2  import cv  import matplotlib.pyplot as plt  from scipy.misc import derivative  import copy  import skimage.feature.texture  from PIL import Image        class TextureWavelets:      def access_to_images(self, directory_segmentation: str, directory_originals: str, n_displays: int,                           color_plaque: str):            count = 0          for image_name in os.listdir(directory_originals):              if count < n_displays:                  segmented_image = cv2.imread(directory_segmentation + "/" + image_name)                  segmented = Image.open(directory_segmentation + "/" + image_name)                  original = Image.open(directory_originals + "/" + image_name)                    masked = self.create_mask_plaque(segmented_image, color_plaque)                  intersection = self.find_intersection(segmented_image, masked)                  haralick = self.haralick(segmented_image, 'contrast')          def find_intersection(self, mask, image):          mask = cv2.cvtColor(mask, cv2.COLOR_BGR2GRAY)          masked_image = image * mask          Image.fromarray(masked_image).show()          def create_mask_plaque(self, image, color_plaque):          COLOR1_RANGE = [(30, 0, 0), (255, 50, 50)]  # Blue in BGR, [(low), (high)].            if color_plaque == 'green':              COLOR1_RANGE = [(0, 30, 0), (50, 255, 50)]          elif color_plaque == 'red':              COLOR1_RANGE = [(0, 0, 30), (50, 50, 255)]          elif color_plaque == 'blue':              COLOR1_RANGE = [(30, 0, 0), (255, 50, 50)]          elif color_plaque == 'b&w':              COLOR1_RANGE = [(0, 0, 255), (255, 255, 255)]            mask = cv2.inRange(image, COLOR1_RANGE[0], COLOR1_RANGE[1])          only_plaque = cv2.bitwise_and(image, image, mask=mask)          gray = cv2.cvtColor(only_plaque, cv2.COLOR_BGR2GRAY)          blur = cv2.GaussianBlur(gray, (3, 3), 0)          thresh = cv2.threshold(blur, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)[1]          thresh = 255 - thresh            # Morph open with a elliptical shaped kernel          kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5, 5))          opening = cv2.morphologyEx(thresh, cv2.MORPH_OPEN, kernel, iterations=2)          Image.fromarray(opening).show()            return opening        def haralick(self, image, function):          image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)          P = skimage.feature.texture.greycomatrix(image, [1], [0], levels=256, symmetric=False, normed=False)          result = skimage.feature.texture.greycoprops(P, prop=function)            return result[0][0]      if __name__ == "__main__":      texture_wavelets = TextureWavelets()      directory_segmentation = 'D:/CTU/new_segmentation_data/references/trans'      directory_originals = 'D:/CTU/new_segmentation_data/data/trans'      n_displays = 2      # options for lumen and plaque colors: green, red, blue, b&w      texture_wavelets.access_to_images(directory_segmentation, directory_originals, n_displays, 'b&w')  

The problem is that the find_intersection function returns me this:

enter image description here

It's gray with no texture, and what I need is the texture...

Firebase Realtime Rules: Allowing multiple Users Access to Data

Posted: 01 May 2021 08:08 AM PDT

So I have my Database structured like this, the owner gets set when the group is created and the owner the should have the permission to add other Users to allowed so they can access and edit the data too.

-Groups     |-Groupname        |- Owner: string        |- Allowed: List<string>        |- Data: all the data  

So my attempt were these rules but they dont work when I use the playground feature with a saved uid under owner or allowed:

"Groups" : {        "$group": {          ".read": "auth != null && (data.child('Owner').val() === auth.uid || data.child('Allowed').val() === auth.uid)",          ".write": "auth != null && (data.child('Owner').val() === auth.uid || data.child('Allowed').val() === auth.uid)"                  }             }  

And would a User still be able to create a new group when these rules would work? Pictures of the Database and Errors: 1 2 3

Is a good practice having a virtual environment in a different folder with python? [closed]

Posted: 01 May 2021 08:08 AM PDT

Is it any good having venv folder in a separated folder outside our project ??

I have google drive and always when I create new virtual environments I think it is a waste of storage when syncing it there. I'm thinking of creating virtual enviroments in a different folder which won't sync.

Fast algorithm for sum of steps taken by the Euclidean algorithm over pairs of numbers under an upper bound

Posted: 01 May 2021 08:08 AM PDT

Note: This may involve a good deal of number theory, but the formula I found online is only an approximation, so I believe an exact solution requires some sort of iterative calculation by a computer.

My goal is to find an efficient algorithm (in terms of time complexity) to solve the following problem for large values of n:

Let R(a,b) be the amount of steps that the Euclidean algorithm takes to find the GCD of nonnegative integers a and b. That is, R(a,b) = 1 + R(b,a%b), and R(a,0) = 0. Given a natural number n, find the sum of R(a,b) for all 1 <= a,b <= n.

For example, if n = 2, then the solution is R(1,1) + R(1,2) + R(2,1) + R(2,2) = 1 + 2 + 1 + 1 = 5.

Since there are n^2 pairs corresponding to the numbers to be added together, simply computing R(a,b) for every pair can do no better than O(n^2), regardless of the efficiency of R. Thus, to improve the efficiency of the algorithm, a faster method must somehow calculate the sum of R(a,b) over many values at once. There are a few properties that I suspect might be useful:

  1. If a = b, then R(a,b) = 1
  2. If a < b, then R(a,b) = 1 + R(b,a)
  3. R(a,b) = R(ka,kb) where k is some natural number
  4. If b <= a, then R(a,b) = R(a+b,b)
  5. If b <= a < 2b, then R(a,b) = R(2a-b,a)

Because of the first two properties, it is only necessary to find the sum of R(a,b) over pairs where a > b. I tried using this in addition to the third property in a method that computes R(a,b) only for pairs where a and b are also coprime in addition to a being greater than b. The total sum is then n plus the sum of (n / a) * ((2 * R(a,b)) + 1) over all such pairs (using integer division for n / a). This algorithm still had time complexity O(n^2), I discovered, due to Euler's totient function being roughly linear.

I don't need any specific code solution, I just need to figure out the procedure for a more efficient algorithm. But if the programming language matters, my attempts to solve this problem have used C++.

Side note: I have found that a formula has been discovered that nearly solves this problem, but it is only an approximation. Note that the formula calculates the average rather than the sum, so it would just need to be multiplied by n^2. If the formula could be expanded to reduce the error, it might work, but from what I can tell, I'm not sure if this is possible.

C++ Display Character with Ansi Color Code

Posted: 01 May 2021 08:09 AM PDT

I can use ANSI color codes for strings like this:

cout << "\033[35m" << "hello" << "\033[0m" << endl;  

but not for individual characters that I have assigned as part of my 2D array of characters. My goal is to display:

myArr[6][5] = 'H'  

in a specific color. I have tried:

myArr[6][5] = "\033[35mH\033[0m"  

and also

myArr[6][5] = '\033[35mH\033[0m'  

The first gives an error because my array is of character data type, so I can't assign it to a string element. The second doesn't work because the ' ' is meant for single characters, and the ANSI code has more than one character. Any suggestions? This needs to transfer onto Linux by the way (on Terminal on my mac).

ionic 5 (capacitor) gives NullInjectorError empty object Magnetometer can not access ionic-native functionality,

Posted: 01 May 2021 08:07 AM PDT

NullInjectorError: No provider for Magnetometer My goal is to read sensordata, like magnetometer. Using Ionic 5, Angular, capacitor android.

You can find my project at https://github.com/kpproce/ionicMagnoMeter

I can't get access to the magnetometer, because the object is empty. I did manage to access the camera, but this is standard available in the web version also...

I understand that the magnetometer probably doesn't exist in the web app version. There are many instructions about plugins, but could not get them working

followed instructions: https://ionicframework.com/docs/native/magnetometer

To prepare: In the terminal VScode:
--- npm install --save @ionic-native/core
--- npm install cordova-plugin-magnetometer

--- npm install @ionic-native/magnetometer
--- npx cap add android

Code used:
import { Component } from '@angular/core';
import { Plugins } from '@capacitor/core';
import { Magnetometer, MagnetometerReading } from '@ionic-native/Magnetometer/ngx';

...

export class HomePage {
constructor(private magnetometer: Magnetometer) {} // this seems to be the problem, empty object

see error NullInjectorError: No provider for Magnetometer!

How to use Amazon SNS api with c

Posted: 01 May 2021 08:08 AM PDT

I have not been able to find documentation on how to use Amazon SNS API from just c. Can someone point me in the right direction? Is there a c build of the API or do I build from source? If so, how?

I intend to use it with borland c++ compiler from command line.

No comments:

Post a Comment