Friday, November 5, 2021

Recent Questions - Stack Overflow

Recent Questions - Stack Overflow


Microsoft Teams Apps: Issue using media permissions for tabs

Posted: 05 Nov 2021 09:14 AM PDT

I'm trying to develop a tab for Microsoft Teams which needs to access the microphone. According to the documentation

https://docs.microsoft.com/en-us/microsoftteams/platform/concepts/device-capabilities/mobile-camera-image-permissions?view=msteams-client-js-latest

I need to add this property to the manifest.json:

"devicePermissions": [       "media",   ],  

When i open my tab, i can see this message:

enter image description here

The problem is I also need to use my application in a different window

enter image description here

But, when i select that option and have my app running in a different window, i can't see the message to allow that permission and my tab can't use the microphone

I also try to grant that permission before open my app in a different window, but it doesn't work neither.

What could i do in this case?

change bar color by interactivity of matplotlib

Posted: 05 Nov 2021 09:14 AM PDT

I'm practicing the interactivity of matplotlib now, I want to change color by the value I press on the picture. But after I execute my codes, nothing happened, I have tested it using print to see if it successfully interact or not, and it did. It just doesn't change color. Here are my codes.

def onclick(event):     yclick=event.ydata     paint=probability_cal(yclick, interval)     color=np.array(paint)     color1=cm.coolwarm(color)     for i in range(len(df)):         bars[i].set_color(color1[i])    cid=fig.canvas.mpl_connect('button_press_event', onclick)  

'bars' is the bar chart I created beforehand. and 'color1' is an np.array looks like [0.9396231304298562,1.0,1.0,1.0]

Why my if statement at line 14 and 77 dosen't work?

Posted: 05 Nov 2021 09:14 AM PDT

class IA(object):    def __init__(self, choice):      self.choice = choice    def __str__ (self):        template = '{0.choice}'      return template.format(self)    def IAs(choice):          if choice == 1 :          bool = IA.Tricheur()            return bool              def Tricheur():      bool = False          return bool        def Enfant():      bool = True      return bool    def Coequipier(boolean):        if boolean == True :          confiance = confiance + 2        elif boolean ==  False :            confiance = confiance - (-5)        if confiance < 0 :            bool = False          return bool        elif confiance >= 0 :            bool = True          return bool    def copieur(bool):        if bool == True :          booléun = True      elif bool == False :          booléun = False    def game(turn,choice1,choice2) :      count1= 0      count2= 0      tour = turn        while tour != 0 :          IA1 = IA.IAs(choice1)          IA2 = IA.IAs(choice2)          print(tour)          print(IA1)          print(IA2)              if IA1 == False and IA2 == False :              count1= count1 + 0              count2 = count2 + 0              turn = turn - 1            elif IA1 == False and IA2 == True :                count1= count1 + 3              count2 = count2 - 1              turn = turn - 1            elif IA1 == True and IA2 == False :                count1= count1 - 1              count2 = count2 + 3              turn = turn - 1            elif IA1 == True and IA2 == True :                count1= count1 + 1              count2 = count2 + 1              turn = turn - 1            elif IA1 == None and IA2 == None :              turn = 0        return print(f"score 1 : {count1} | score 2 : {count2}")        def main():      print("""          ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~                       Jeux de la confiance          ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~          """)        print("""          ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~                              règles          ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~          """)        print("""          1 - Choisissez qu'elle IA vous voulez faire jouer            2 - Si les 2 IA mette une pièce chacun gagne 1 points            3 - Si une IA met une piece et l'autre non, L'IA qui a mis une pièce perd 1           point et l'autre gagne 3 points            4 - si les deux IA ne mette pas de pièce alors aucun ne gagne de point            5 - vous choisissez le nombre de tour que on fait jouer les IA            """)                                            if __name__ == "__main__":      main()    print("Choisissez le nombre de tour")  tour=int(input())  print("Choisissez une des IA")  choix1=int(input())  IA1= IA(choix1)  print("Choisissez une autre IA")  choix2=int(input())  IA2= IA(choix2)    game(tour,IA1,IA2)  

My if statement when i did the function IAs didn't go in same for the while with the function game

when I enter 1 in the variable choice for the function IAs, the function launch but doesn't go in the if statement. I don't know why. I respect all the indent (I think) Please help me (sorry for my english)

Store difference between two date fields as new column in oracle

Posted: 05 Nov 2021 09:13 AM PDT

I have two different DATE fields in the same table. Change_date and End_date, I need to get the difference between two (in days) and store as a new column in that same table.

I've attempted a datediff function but that seems to only work in Ms sql and not oracle.

JSON.loads gives a string output when invoked in tornado handler

Posted: 05 Nov 2021 09:13 AM PDT

I am passing some data to a tornado server handler which calls json.loads(request.body) This is how request.body looks like:

b'"{\\"inputs\\": {\\"key1\\": \\"/9j/4QxgRXhpZgAATU0AKgAAAAgA....... sVf/2Q==\\"}}"'  

When I call json.loads on this request.body this is what the output looks like

payload = json.loads(request.body)  print(payload)  {"inputs": {"key1": "/9j/4QxgRXhpZgAATU.....rsVf/2Q=="}}  print(type(payload)) # <class 'str'>  

I am not sure why the output of json.loads is str

This is the request body I am passing

with open("ee", "rb") as image_file:      encoded_string = base64.b64encode(image_file.read())    x = {"inputs": {"key1": encoded_string.decode("utf-8")}}  <request_session>.post(<HOST>, json=json.dumps(x))  

How can I change my request body such that when json.loads is called on my request.body, I recieve a dictionary

The handler is built in tornado

Web-Scraping an iframe with Beautiful Soup

Posted: 05 Nov 2021 09:13 AM PDT

I'm trying really hard to get the data from this webpage in python https://coronavirus.health.ny.gov/zip-code-vaccination-data and am just so lost...

I think I need to scrape it using beautiful soup, but it's really difficult because the data is in an iframe and I don't know what to do.

Any guidance would really help.

-Vanessa

what can i do for my mouse to work properly?

Posted: 05 Nov 2021 09:13 AM PDT

Good afternoon for all. Well, i've acquired a new mouse and i want to use it in my games to do what i want it to do! I'm brasilian and i don't have that much money, i know a litte bit of programming, but i'm trying to do this for two days with just knowledge learning but not the expected result, i've already tryed to use x-mouse button control, but the mouse i bough has some additional buttons with additional functions like opening the web browser and opening the my computer folder, i want to disable this two functions and put another command for it to do, the buttons my mouse has are 5 in the left side, the 2 regular ones, the scroll whell with button press and the 2 for increasing or decreasing the speed of the pointer. I've also tryed to open the driver .sys files but i don't have an editor for it and it has that permission of microsoft that don't allow us to change the stuff, i've also looked at the machine registry, and i don't know how to use that Autohotkey and i don't think it will prevent the mouse button of opening the browser or the my computer folder, i think i must have a new driver for it, i'm not lazy and i don't care spending a week in learning this thing, just point me some directions. thank you so much guys for this amazing website!

I need to import a .txt file into a psql database table

Posted: 05 Nov 2021 09:13 AM PDT

I need to import data from .txt file into a psql database table. I created a loop that opens the file and iterates through it but it doesnt append anything into the database table here is my code:

with open(Dataaa,'r') as file:      file_content = file.readlines()      values = [line.split(';') for line in file_content]      db_cursor.executemany(query, values)      count = db_cursor.rowcount    count = db_cursor.rowcount  print(count, "Records inserted succesfully into table")  print(file_content)  conn.commit()    except (Exception, psycopg2.DatabaseError) as error:     print(error)    finally:  if conn:      db_cursor.close()      conn.close()      print("PSQL conn is closed")  

Dataaa is the file path mentioned above the code. The data in the txt file is in 1;xxxx;xxxx;23543452346; format.

Proper way to handle node_modules in docker compose?

Posted: 05 Nov 2021 09:13 AM PDT

Docker is great while developing the app locally because it matches the production environment.

How I've seen it done:

Mount the code

Mounting the host code folder inside the container allows editing the code and to instantly see the result inside the running docker container.

Normally node_modules are in .gitignore, meaning that npm install is required after building or if the package.json dependencies are changed.

For production it makes more sense to do npm ci --production in the Dockerfile using a multi-stage build, no node_modules folder on production.

Mounting the volume will replace all the code and add node_modules on the production ready image for development.

Pros:

  • node_modules is not part of the Docker image (Smaller image)
  • Rebuilding the dev container doesn't require re-downloading node_modules (npm install is faster)
  • npm install is faster after the first time
  • One Dockerfile for dev and production

Cons:

  • node_modules on the host will be built for the docker OS (Not an issue if the container OS matches the host)
  • May accidentally overwrite node_modules by doing npm install on the host (Not an issue if the OS matches the host)
  • Need to npm install manually or automatically each time when rebuilding the dev container (For example docker-compose could run npm install) or possibly manually when changing branches.
  • Need to connect the IDE interpreter to the container (might be ok to use the host node_modules).

Work remotely

git clone main and npm ci --production inside the Dockerfile and do remote development using vscode (or any other IDE that supports that)

Then while developing inside the container do npm install manually to get the devDependencies

Pros:

  • Developing inside an environment that matches production
  • node_modules is not part of the Docker image (Smaller image)
  • One Dockerfile for dev and production

Cons:

  • Everyone on the team has to use an IDE that supports remote development
  • Changes are lost each time after rebuilding the container. (git commit makes this ok)
  • Need to npm install manually or automatically each time when rebuilding the dev container (For example docker-compose could run npm install) or possibly manually when changing branches.

Mount the code without node_modules

Same as "Mount the code" above, but using a hack with an additional mount volume to avoid having node_modules on the OS

docker volume create node_modules  

in docker-compose.yml

myapp:      volumes:          - /me/code:/app          - node_modules:/app/node_modules    volumes:      node_modules:          external: true  

Or move node_modules to be outside of /app

Pros:

  • node_modules is not part of the Docker image (Smaller image)
  • Rebuilding the dev container doesn't require re-downloading node_modules (npm install is faster), only required after the node_modules volume is removed.
  • One Dockerfile for dev and production

Cons:

  • Need to npm install manually or automatically each time you rebuild the dev container (For example docker-compose could run npm install) or possibly manually when changing branches.
  • Need to connect the IDE interpreter to the container (or do npm install on the host, which won't necessarily match the one on the container and cause bugs).

Or some other way that I haven't mentioned.

Each way assumes that we boot a dummy app during, so that it won't crash and stop the container if dependencies become missing during development.

Is there an automated way to handle the change in package.json during development?
And which way is considered the standard proper way and why?

Search function for a value in an array of objects

Posted: 05 Nov 2021 09:14 AM PDT

I have tried to create a function which searches for the title in an array of book-objects. For some reason my code doesn't work, I have tried going through each step logically and in my mind it should be working.

let book = {    title: "The 48 Laws of Power",    author: "Robert Greene",    numOfPages: 452,    publisher: "Penguin Books",    rating: "4.5 stars"  }    let book2 = {    title: "How to Catch a Turkey",    author: "Adam Wallace",    numOfPages: 40,    publisher: "",    rating: "5 stars"  }    let book3 = {    title: "Glitter Every Day: 365 Quotes from Women I Love",    author: "Andy Cohen",    numOfPages: 384,    publisher: "Henry Holt and Co.",    rating: "3 stars"  }    let bookArr = [book, book2, book3];  let searchBtn = document.getElementById('search-button');  let found = false;    let bookSearch = function() {    found = false;    let input = document.getElementById('book-search');    for (i = 0; i < bookArr.length; i++) {      if (input.value.toLowerCase == bookArr[i].title.toLowerCase) {        found = true;        break;      }      }    if (found) {      console.log(bookArr[i]);    } else {      console.log("The book was not found.");    }  }  searchBtn.addEventListener('click', bookSearch);
<input type="text" id="book-search" placeholder="Search books...">  <button id="search-button">Search</button>  <script src="object.js"></script>

And lastly I'm new to this forum and also new to programming so I apologize if this is the wrong way of asking questions but I would really appreciate some criticism on my code and what I should do better. Thank you!

Is there a way to automatically submit a form after text is populated via $_GET?

Posted: 05 Nov 2021 09:13 AM PDT

I am bringing a value to a page via $_GET and inserting it into my search textbox. The box is an auto complete using ajax. The problem is that when it is dropped into the search box it doesn't auto search. It needs me to press a key to fire off. Is there an easy way to get it to submit after the value is inserted? Or maybe a different method for accomplishing this?

<div class="form-group">      <input type="text" name="search_box" id="search_box" class="form-control input-lg" placeholder="Type your search here" '.(isset($_GET['search']) ? 'value="'.$_GET['search'].'"' : "").' />  </div>  
<script>    $(document).ready(function(){        load_data(1);        function load_data(page, query = '')      {        $.ajax({          url:"fetch.php",          method:"POST",          data:{page:page, query:query},          success:function(data)          {            $('#dynamic_content').html(data);          }        });      }        $(document).on('click', '.page-link', function(){        var page = $(this).data('page_number');        var query = $('#search_box').val();        load_data(page, query);      });        $('#search_box').keyup(function(){        var query = $('#search_box').val();        load_data(1, query);      });      });  </script>  

Pandas read csv with columns name spread over multiple rows

Posted: 05 Nov 2021 09:13 AM PDT

While reading a csv file into pandas dataframe, I came into following situation: The column names were spread into multiple rows. I have attached a picture below. The problem is that now I have some columns to have duplicated name, but they are not. Is there a way to combine the columns from multiple row in single columns, without doing manual hack?

data = pd.read_csv("CO2.csv", header=54)

enter image description here

Thanks in advance

pip package gets error at installing aiohttp

Posted: 05 Nov 2021 09:14 AM PDT

I have made an own pip package and I get this error when I'm installing it.

urllib3 works fine, but aiohttp raises this error

ERROR: Could not find a version that satisfies the requirement aiohttp (from web-math) (from versions: none)  ERROR: No matching distribution found for aiohttp  

this i my setup.py file:

from setuptools import setup, find_packages    requirements = ["aiohttp", "urllib3"]    classifiers = [      "Development Status :: 5 - Production/Stable",      "Intended Audience :: Education",      "Operating System :: OS Independent",      "License :: OSI Approved :: MIT License",      "Programming Language :: Python :: 3",  ]    setup(      name="web_math",      version="1.0.11",      description="For online math api",      long_description=open("README.md").read(),      long_description_content_type='text/markdown',      url="https://github.com/mcbabo/webmath",      author="Moritz",      license="MIT",      classifiers=classifiers,      keywords="discord discord-calc calculator easy-calc simple-calculator discord.py pycord python math",      packages=find_packages(),      install_requires=requirements,      include_package_data=True  )  

Can't change this to pandas datetime

Posted: 05 Nov 2021 09:14 AM PDT

dfff = pd.DataFrame({'date': ['01-01-2016 0.55', '01-01-2016 1.26', '01-01-2016 4.51',                       '01-01-2016 7.43']})   print(dfff)    s1 = dfff.apply(pd.to_datetime)    *Error* : **ParserError: Unknown string format: 01-01-2016 0.55  

**

when I try to apply the DateTime the error is showing I even tried to do formating but no use

This.props.t with SweetAlert2

Posted: 05 Nov 2021 09:14 AM PDT

I am using Sweetalet2 in order to show a popup, and it works perfectly, but i now have to use i18n Library in order to translate the error messages, i tried using this.props.t but it doesn't seem to be working, and i really don't know why

Here is the error message i am getting.

this.props.t is not a function

Here is the sweetAlert part i am using

componentDidMount() {  let condition =    !this.props.urlMagasin ||    !this.props.amountValue ||    !this.props.edmMagasin ||    !this.props.edmCommande;    let error_message = this.props.urlMagasin    ? this.props.t("Please try again")    : this.props.t("Return to the magasin and re-do the oprder");    if (this.props.edm && !this.props.wafacare && condition) {    Swal.fire({      html:        "<div>" +        this.props.t("There has been an unexpected error") +        "<br/>" +        this.props.t(error_message) +        "</div>",      showConfirmButton: this.props.urlMagasin ? true : false,      confirmButtonText: "Retourner au magasin",      allowOutsideClick: false,      buttonsStyling: false,      didOpen: () => {        Swal.clickConfirm();      },    }).then(() => {      if (this.props.urlMagasin)        return window.location.assign(this.props.urlMagasin);    });  }  

}

I wrote the same code as 'developer.apple.com/tutorials/swiftu' but why is it different view

Posted: 05 Nov 2021 09:13 AM PDT

I'm learning swiftUi and I was writing the project on apple site but I can't get the same view. I copied and pasted but the screen borders are different

my project

developer.apple project

import SwiftUI      struct CategoryHome: View {  @EnvironmentObject var modelData: ModelData    var body: some View {      NavigationView {          List {              modelData.features[0].image                  .resizable()                  .scaledToFill()                  .frame(height: 200)                  .clipped()                  .listRowInsets(EdgeInsets())                ForEach(modelData.categories.keys.sorted(), id: \.self) { key in                  CategoryRow(categoryName: key, items: modelData.categories[key]!)              }              .listRowInsets(EdgeInsets())          }          .navigationTitle("Featured")      }   }  }  

retry with python requests when status_code = 200

Posted: 05 Nov 2021 09:13 AM PDT

The API I'm sending requests to has a bit of an unusual format for its responses

  1. It always returns status_code = 200

  2. There's an additional error key inside the returned json that details the actual status of the response:

    2.1. error = 0 means it successfully completes

    2.2. error != 0 means something went wrong

I'm trying use the Retry class in urlib3, but so far I understand it only uses the status_code from the response, not its actual content.

Are there any other options?

Decoding a weird json file with Dart

Posted: 05 Nov 2021 09:14 AM PDT

This needs to be decode into readable JSON with Dart the problem is. I don't what it is and I don't know how to do it.

{  mifare: {  identifier: [4, 119, 66, 185, 196, 77, 112],   mifareFamily: 2,   historicalBytes: []  },   ndef: {  isWritable: true,   maxSize: 492,   cachedMessage:   {records:   [{identifier: [],   typeNameFormat: 1,   type: [84],   payload: [2, 101, 110, 123, 39, 99, 109, 100, 39, 58, 39, 110, 101, 119, 95, 102, 114, 105, 101, 110, 100, 39, 44, 39, 117, 115, 101, 114, 39, 58, 39, 116, 101, 115, 116, 39, 125]}]}}}  

Someone any idea how to do that? PS: the 'payload' should be text like this:

{'cmd':'new_friend','user':'test'}  

firebaseAdmin.auth().getUser(uid) being extremely slow recently

Posted: 05 Nov 2021 09:14 AM PDT

Starting around October firebaseAdmin.auth().getUser(uid) is having an extremely slow response time - often reaching more than 60 secs and even more - and then it returns back to normal.

My first suspicion was it's related to the throughput of the API but it doesn't correlate as it happens almost randomly.

Is anyone else facing this issue? It has been a real problem and can't know if there is something wrong with the service or if it's on our end.

import firebaseAdmin from 'firebase-admin';  const uid = "uid-goes-here";  const data = await firebaseAdmin.auth().getUser(uid);  

New relic Performance Graph

scipy matrix conversion documentation is unclear

Posted: 05 Nov 2021 09:13 AM PDT

Im converting a dok to a coo matrix in scipy and the documentation seems unclear to me. My goal is to not destroy the original matrix! The documentation states:

Convert this matrix to Compressed Sparse Row format. With copy=False, the data/indices may be shared between this matrix and the resultant csr_matrix.

However it seems to output the matrix rather than convert the original one. I thought "copy" might change the behaviour from converting to creating a copy but testing shows that can't be true. My programm has a long runtime so i don't want to destroy the matrix accidentially right before exporting it :)

mat = scipy.sparse.dok_matrix((10,10),dtype=np.int16)  type(mat)  

<class 'scipy.sparse.dok.dok_matrix'>

coo = mat.tocoo(copy=True)  print(type(mat))  

<class 'scipy.sparse.dok.dok_matrix'>

print(type(coo))  

<class 'scipy.sparse.coo.coo_matrix'>

coo = mat.tocoo(copy=False)  print(type(mat))  

<class 'scipy.sparse.dok.dok_matrix'>

print(type(coo))  

<class 'scipy.sparse.coo.coo_matrix'>

Thanks!

Only most recent task ExecutorService in Java

Posted: 05 Nov 2021 09:14 AM PDT

I want to create an ExecutorService in Java which, when given a task will stop and discard it's current task (if there is a current task) and execute the given task. When a new task is given to this ExecutorService it is always because the previous tasks became irrelevant an not worth executing anymore.

Is there a builtin way in Java to do this or should I resort to implementing this behavior myself? Or is there another approach which works better in this case?

Pine Script V4 - Resolve_error "Fund" for Marketcap label

Posted: 05 Nov 2021 09:14 AM PDT

I'm stucked with an issue with on Pine Script v4 (Tried with v5 but it's same) I don't succeed to fix it. That's why I need your help.

I just want to add a label with the marketcap of the coin currently in use :

//@version=4  study("My Script", overlay=true)      //Marketcap    TSO = financial(syminfo.tickerid, "TOTAL_SHARES_OUTSTANDING", "FQ")  MarketCap = TSO*close      label MarketCapL = label.new(time, close, text="  MarketCap | " + tostring(MarketCap, "##.###"),color=color.new(color.white,90), xloc= xloc.bar_time, style=label.style_none, textcolor= color.new(color.white,0), textalign=text.align_left), label.set_x(MarketCapL, label.get_x(MarketCapL)+ round(change(time)* 8)), label.set_y(MarketCapL, (label.get_y(MarketCapL) * 1.100)), label.delete(MarketCapL[1])  

But it returns a

"Resolve_error "FUND""

Could someone help me ?

Prewitt edge detector implemented with Matlab gives thick edges than the in-built function

Posted: 05 Nov 2021 09:13 AM PDT

I implemented the Prewitt edge detector and compared my output with Matlab's in-built Prewitt edge detector and I noticed that my output gave thicker edges. What could be the reason?

input = imread('pic.png');  input = double(rgb2gray(input));  kernel_x = [-1, 0, 1; -1, 0, 1; -1, 0, 1];  kernel_y = [1, 1, 1; 0, 0, 0; -1, -1, -1];    [length, width] = size(input);  new = input;  for i = 1:length - 2    for j = 1:width - 2      Gx = sum(sum(kernel_x.*input(i:i+2, j:j+2)));      Gy = sum(sum(kernel_y.*input(i:i+2, j:j+2)));      new(i+1, j+1) = sqrt(Gx.^2 + Gy.^2);    end  end  new = uint8(new);    % binarizing image and setting threshold  edge = imbinarize(edge, 100); % final output from implementation  

The in-built function I used is edge(input, 'Prewitt') Output from my implementation vs the in-built operator:

comparison of two results

What could be the reason for this?

I tried changing the Threshold value also but still no luck.

How to get week number based on Two dates based Conditions in Excel

Posted: 05 Nov 2021 09:13 AM PDT

I have a DateTime column in Excel in which data is sorted in ascending order based on DateTime conditions from 15th June to say 1st November ; I want to print Week Number from 1st to Nth Week based on date condition; Week criteria are like first seven days i.e 15th June to 21st June is Week1, 22nd Jun-28th Jun is Week2, 29th June - 5th June is Week3 and so on.

How Can I do this?

Column1    06/15/2021 8:00  06/15/2021 10:00  :  :    11/01/2021 20:44  11/01/2021 20:46        

Visual Studio Code unable to compile cpp and Cuda (cu) files together

Posted: 05 Nov 2021 09:13 AM PDT

I have c++ program with multiple cpp files in VS code. Recently I learned some CUDA programming and tried to add a cuda functionality to this program. However, the nvcc compiler fails. If I try renaming the cu file to cpp I get an error:

expected primary-expression before ')' token      cuda_hello<<<1, 1>>>();  

I understand this is because the nvcc then ignores that the file has cuda codes. So is there a way I can compile the cpp and cu files separately and then combine them or some other solution in VS code itself, maybe by changing the tasks.json file.

SQLite numColumns > 0 but fetchArray returns false

Posted: 05 Nov 2021 09:13 AM PDT

I have this code

$res = $db->query("query...");  $res->numColumns(); // outputs: 14  $res->fetchArray(1); // outputs: false  $db->lastErrorMsg(); // outputs: unknown error  $db->lastErrorCode(); // outputs: 101 (SQLITE_DONE)   

as you can see numColumns tells me there should be a result to my query, but then fetchArray returns false, and the error message and code are not really helpful.

What could be happening that makes numColumns return a result > 0, but fetchArray return false?

Taming Lifetime Contagion with Rust Structs

Posted: 05 Nov 2021 09:13 AM PDT

I am attempting to define a struct, in Rust, that contains a member of type async_executor::LocalExecutor, a type that, itself, is generic over a lifetime, 'a:

pub struct LocalExecutor<'a> {      inner: ......<Executor<'a>>,      ...      ...  }  

My own struct must now, apparently, also be generic over a lifetime, 'a, which means nothing to it, itself -- that lifetime is a detail of async_executor::LocalExecutor.

#[cfg(all(test, not(target = "wasm32")))]  struct MockThing<'a> {      executor: async_executor::LocalExecutor<'a>,  }  

My struct exists only when building unit-tests, where I need a mock, single-threaded executor for running async code. Herein lies the problem: the only consumer of my struct uses #[cfg(...)] conditional compilation, internally, to

  1. use my mock when compiling for unit-tests (and not WebAssembly)
  2. or one real implementation when compiling for WebAssembly
  3. or another real implementation, otherwise.

This is done with conditional compilation to ensure that the consumer, itself, is not unnecessarily generic, which would polute its public API and just push the problem of contagious generics to everything that consumes it -- a large number of things. Conditional compilation provides compile-time duck-typing, of a sort, and because that conditional compilation only exists in one place, knowledge of the implementation details is unnecessary for everyone else -- as it should be.

Neither implementation 2 nor 3 requires generic lifetimes but, because the mock one (1) must be generic over 'a, I now have to make everything, throughout my code-base, generic over some lifetime, 'a'! (and faff about with PhantomData to stop the compiler from complaining that 'a is meaningless, which it is, most of the time.)

Is there some way that I could define my mock struct in a way that does not strike this problem? It would be really convenient if I could use '_ in the member definition, like...

#[cfg(test)]  struct MockThing {      executor: async_executor::LocalExecutor<'_>,  }  

... to indicate that the lifetime of executor should be deduced from the lifetime of the MockThing. (Of course, this does not work.)

I suppose I could also just use another async runtime, with ambient executor, for my unit tests, and bypass the problem but that would not help me to understand what is going on, here, and, in general, how one should encapsulate lifetimes as implementation details, in structs that have members that are generic over some lifetime.

There is something I am not understanding, though: why Executor (inside LocalExecutor) must be generic over 'a -- it does not contain a reference with lifetime 'a -- and why they use PhantomData to ensure that it is generic over an invariant lifetime, 'a, and, even, what lifetime invariance means in this case. I've been reading about it, in the nomicon and elsewhere, but it will be many days of learning before I can say I understand lifetime variance and all I want to do is "put one of those in my struct".

Surely there must be some way to tame lifetime contagion and prevent it polluting one's entire code-base just because one type is generic over a lifetime? Help, please!

Storing file in PostgreSQL database using NestJS

Posted: 05 Nov 2021 09:14 AM PDT

I have one form in React. It has many fields. once user click on the submit button all the field should be saved in database. It also contains one file attachment(pdf).

enter image description here

I dont know what the datatype of variable which will store file, I should take in entity class. Also what should be the database column type. I am using TypeORM for the same.

   @IsNotEmpty()      @IsDate()      endDate: Date;      @Column()      @IsNotEmpty()      @IsString()      personIncharge: string;        @Column()      @IsNotEmpty()      @IsString()      country: string;        @Column()      @IsNotEmpty()      @IsString()      comments: string;        attachFile: string;  // Should I take file or string?  

Angular SSR: Build Error TS6306: Referenced project must have setting "composite": true

Posted: 05 Nov 2021 09:14 AM PDT

I'm developing an Angular App with SSR, but I'm getting the following error when building with npm run build:ssr:

ERROR in [...]/tsconfig.json  [tsl] ERROR        TS6306: Referenced project '[...]/tsconfig.app.json' must have setting "composite": true.    ERROR in [...]/tsconfig.json  [tsl] ERROR        TS6306: Referenced project '[...]/tsconfig.server.json' must have setting "composite": true.  

I then tried to add this key to the tsconfig.app.json and tsconfig.server.json, but I'm not sure where to add this key:

tsconfig.app.json (and tsconfig.server.json accordingly)

{      "extends": "./tsconfig.base.json",      "compilerOptions": {          "outDir": "./out-tsc/app",          "types": [],          "composite": true   // <-- generates the next error (see below)      },      "files": [          "src/main.ts",          "src/polyfills.ts"      ],      "include": [          "src/**/*.d.ts"      ],      "exclude": [          "src/test.ts",          "src/**/*.spec.ts"      ],      "composite": true   // <-- no effect  }  

After adding the key as mentioned above, while building, the following error occurred for each typescript-file:

ERROR in error TS6304: Composite projects may not disable declaration emit.  

( So this cannot be the way... )

A few things to know:

  • Angular v 10.0.5
  • Added SSR-support via @nguniversal/express-engine
  • ng serve is working fine

package.json:

{    "name": "cg",    "version": "0.0.0",    "scripts": {      "ng": "ng",      "start": "ng serve",      "build": "ng build --prod --localize",      "test": "ng test",      "lint": "ng lint",      "e2e": "ng e2e",      "xi18n": "ng xi18n --outFile=de.xlf --outputPath=src/i18n",      "compile:server": "webpack --config webpack.server.config.js --progress --colors",      "serve:ssr": "node dist/server",      "build:ssr": "npm run build:client-and-server-bundles && npm run compile:server",      "build:client-and-server-bundles": "ng build --prod && ng run cg:server:production"    },    "private": true,    "dependencies": {      "@angular/animations": "~10.0.8",      "@angular/cdk": "^10.1.3",      "@angular/common": "~10.0.8",      "@angular/compiler": "~10.0.8",      "@angular/core": "~10.0.8",      "@angular/elements": "^10.0.8",      "@angular/forms": "~10.0.8",      "@angular/google-maps": "^9.2.4",      "@angular/localize": "^10.0.8",      "@angular/platform-browser": "~10.0.8",      "@angular/platform-browser-dynamic": "~10.0.8",      "@angular/platform-server": "^10.0.8",      "@angular/router": "~10.0.8",      "@angular/service-worker": "~10.0.8",      "@ngrx/effects": "^10.0.0",      "@ngrx/store": "^10.0.0",      "@nguniversal/builders": "^10.0.2",      "@nguniversal/express-engine": "^10.0.2",      "@nguniversal/module-map-ngfactory-loader": "^8.2.6",      "@types/express": "^4.17.7",      "@types/lodash": "^4.14.155",      "document-register-element": "^1.7.2",      "express": "^4.17.1",      "http-server": "^0.12.3",      "lodash.merge": "^4.6.2",      "lodash.pick": "^4.4.0",      "rxjs": "~6.6.2",      "smoothscroll-polyfill": "^0.4.4",      "tslib": "^2.0.0",      "zone.js": "~0.10.3"    },    "devDependencies": {      "@angular-devkit/build-angular": "^0.1000.5",      "@angular/cli": "~10.0.5",      "@angular/compiler-cli": "~10.0.8",      "@angular/language-service": "~10.0.8",      "@locl/cli": "0.0.1-beta.9",      "@types/node": "^14.0.13",      "fs-extra": "^9.0.1",      "git-describe": "^4.0.4",      "ts-loader": "^5.2.0",      "ts-node": "~8.10.2",      "tslint": "~6.1.0",      "typescript": "^3.9.7",      "webpack-cli": "^3.1.0"    }  }  

angular.json

{      "$schema": "./node_modules/@angular/cli/lib/config/schema.json",      "version": 1,      "newProjectRoot": "projects",      "projects": {          "cg": {              "i18n": {                  "sourceLocale": "de",                  "locales": {                      "fr": "src/i18n/fr.xlf"                  }              },              "projectType": "application",              "schematics": {                  "@schematics/angular:component": {                      "inlineStyle": true,                      "style": "scss",                      "skipTests": true                  },                  "@schematics/angular:class": {                      "skipTests": true                  },                  "@schematics/angular:directive": {                      "skipTests": true                  },                  "@schematics/angular:guard": {                      "skipTests": true                  },                  "@schematics/angular:module": {                      "skipTests": true                  },                  "@schematics/angular:pipe": {                      "skipTests": true                  },                  "@schematics/angular:service": {                      "skipTests": true                  }              },              "root": "",              "sourceRoot": "src",              "prefix": "cg",              "architect": {                  "build": {                      "builder": "@angular-devkit/build-angular:browser",                      "options": {                          "outputPath": "dist/browser",                          "index": "src/index.html",                          "main": "src/main.ts",                          "polyfills": "src/polyfills.ts",                          "tsConfig": "tsconfig.app.json",                          "localize": [                              "de"                          ],                          "aot": true,                          "assets": [                              {                                  "glob": "**/*",                                  "input": "src/assets/",                                  "output": "/assets/"                              },                              {                                  "glob": ".htaccess",                                  "input": "src/",                                  "output": "/../"                              },                              "src/manifest.webmanifest"                          ],                          "styles": [                              "src/sass/main.scss"                          ],                          "scripts": []                      },                      "configurations": {                          "production": {                              "fileReplacements": [                                  {                                      "replace": "src/environments/environment.ts",                                      "with": "src/environments/environment.prod.ts"                                  }                              ],                              "optimization": true,                              "outputHashing": "all",                              "sourceMap": false,                              "extractCss": true,                              "namedChunks": false,                              "extractLicenses": true,                              "vendorChunk": false,                              "buildOptimizer": true,                              "budgets": [                                  {                                      "type": "initial",                                      "maximumWarning": "2mb",                                      "maximumError": "5mb"                                  },                                  {                                      "type": "anyComponentStyle",                                      "maximumWarning": "6kb",                                      "maximumError": "10kb"                                  }                              ],                              "serviceWorker": true,                              "ngswConfigPath": "ngsw-config.json"                          },                          "fr": {                              "localize": [                                  "fr"                              ]                          },                          "it": {                              "localize": [                                  "it"                              ]                          },                          "en": {                              "localize": [                                  "en"                              ]                          }                      }                  },                  "serve": {                      "builder": "@angular-devkit/build-angular:dev-server",                      "options": {                          "browserTarget": "cg:build"                      },                      "configurations": {                          "production": {                              "browserTarget": "cg:build:production"                          },                          "fr": {                              "browserTarget": "cg:build:fr"                          },                          "it": {                              "browserTarget": "cg:build:it"                          },                          "en": {                              "browserTarget": "cg:build:en"                          }                      }                  },                  "extract-i18n": {                      "builder": "@angular-devkit/build-angular:extract-i18n",                      "options": {                          "browserTarget": "cg:build"                      }                  },                  "server": {                      "builder": "@angular-devkit/build-angular:server",                      "options": {                          "outputPath": "dist/server",                          "main": "src/main.server.ts",                          "tsConfig": "tsconfig.server.json"                      },                      "configurations": {                          "production": {                              "fileReplacements": [                                  {                                      "replace": "src/environments/environment.ts",                                      "with": "src/environments/environment.prod.ts"                                  }                              ]                          }                      }                  }              }          }      },      "defaultProject": "cg"  }  

Since I'm new to SSR, I'm a little bit lost. Does anybody have an idea? Thanks in advance!

View Both Assembly and C code

Posted: 05 Nov 2021 09:13 AM PDT

Do we have a way to view assembly and c code both using gdb.

disassemble function_name shows only assembly, I was trying to find a way to easliy map c code to assembly. Thanks

No comments:

Post a Comment