Skip to main content

Posts

Showing posts from May, 2022

How can i use firebase cloud storage to handle static files

I am building a a Practice blog with django, after hosting it on heroku, i discovered that any images i upload using image field or fetch disappear after a while. Now i started using firebase cloud storage via django-storage gloud backend and it is working fine since then , but when i tried hosting my staticfiles storage from there is get this error cross origin request blocked the same-origin policy disallows reading the remote resource at? how do i fix this? source https://stackoverflow.com/questions/72453697/how-can-i-use-firebase-cloud-storage-to-handle-static-files

(Odin Project Rock paper scissors) How do I make results appear only once and not show up each time you play a round?

So everytime you press on a button, a round of rps play and displays computer and player points. But instead of points just adding, they add and appear again below, I tried moving brackets on the eventListener so that it doesn't include append results every time you press a button, but then I get playerSelection is not defined. function computerPlay() { let choice = ["rock", "paper", "scissors"]; let random = choice[Math.floor(Math.random() * choice.length)]; return random; } let computerPoints = 0; let playerPoints = 0; function playRound(playerSelection, computerSelection) { if (playerSelection === computerSelection) { return ("It's a draw!"); } else if ((playerSelection === "rock") && (computerSelection === "scissors")) { ++playerPoints return ("You win! Rock beats scissors"); } else if (playerSelection === "rock" && computerSelection === "paper&quo

Flask: index() returns render_template(...) . Why does return index() not work?

Using Flask. This must be a basic gotcha I just don't know about. I have two templates, index.html and index8.html index() sets url to one of these two strings, based on a session parameter, and returns render_template(url, data={...}) Then I've got a toggleMode() which sets the session parameter (from a POST), and then calls return index() It does seem to run the index() code... it prints out index.html or index8.html correctly, which is passed to render_template, and returned, and returned... but it never uses index8.html . If you change html template files, do you need a redirect? Is that it? Why does Flask not change templates, in this situation? I'm printing the template name, and it is 'index8.html' passed in to render_template . But it still renders as though I had passed in 'index.html' . (Or, rather, it doesn't do a new render, at all, despite Flask returning a 200 reply to toggleMode() ) EDIT: Ok minimal example... @app.route(

Data not put into Paragraph JS/AJAX/PHP

My php script echoes Connection successful{"name":"James","dateOfBirth":"2002-10-10","companyname":"Apple"} using echo json_encode(array('name'=>$row['Name'], 'dateOfBirth'=>$row['dateOfBirth'], 'companyname'=>$row['companyname'])); In Javascript the different values should then be displayed in a Label, but the Labels return undefined $(function() { $.ajax({ type: "post", url: 'url', data: {usermail: 42}, success: function(response){ nameLabel.innerHTML = response.name; dateLabel.innerHTML = response.dateOfBirth; companyLabel.innerHTML = response.companyname; console.log(response); } }); }); Via Active questions tagged javascript - Stack Overflow https://ift.tt/yfEC4AD

How to redirect to not found page if slug doesn't exist using React Router Dom?

Let's say I have these routes: <Switch> <Route exact path="/myflix/:slug" component={Home} /> <Route exact path="/myflix/:slug/register" component={Signup} /> <Route exact path="/myflix/:slug/event" component={Event} /> <Route exact path="/myflix/:slug/contact" component={Contact} /> <Route exact path="/myflix/:slug/login" component={Login} /> <Route exact path="/myflix/:slug/show-details" component={ShowList} /> <Route exact path="/myflix/:slug/*" component={NotFound} /> <Route path="*" exact={true} component={NotFound} /> <Redirect to="/not-found" /> {/* <Route path="*" element={<NotFound />} /> */} </Switch> We have certain slugs from an API, in this form: [ { id: 1, title: "_flix", slug: "_flix", status: true, viewTime: null, langue:

How to mutate state in react?

I'm trying the change the value of an object field that is nested in an array. I keep getting this error, "Cannot assign to read only property '0' of object '[object Array]'" Here is what the state looks like { "school stuffs": [ { "_id": "629332e33f0e48af3d626645", "completed": false, }, { "_id": "629425fc9c50b142dff947a9", "completed": true, } ], "household and furniture": [ { "_id": "629334424709234a344c0189", "completed": false, }, { "_id": "629334f12da7859af0828c9a", "completed": false, } ] } Here is the code I'm using to mutate the state and change the value of "completed"

Displaying Eigenfaces but the image is always black

I am using the following code in python to calculate and display my eigenfaces, however, it always returns 6 black images. My problem here is not the calculation of the eigenfaces, but how to display the images in color and not in black. How can I fix this? # Read in original image of old person and store it old = cv2.cvtColor(cv2.imread('images/old.jpg'), cv2.COLOR_BGR2RGB) # Read in altered images of old person and store them oldBeard = cv2.cvtColor(cv2.imread('images/oldBeard.jpg'), cv2.COLOR_BGR2RGB) oldHair = cv2.cvtColor(cv2.imread('images/oldHair.png'), cv2.COLOR_BGR2RGB) oldSmile = cv2.cvtColor(cv2.imread('images/oldSmile.jpg'), cv2.COLOR_BGR2RGB) oldNoise = cv2.cvtColor(cv2.imread('images/oldNoise.jpeg'), cv2.COLOR_BGR2RGB) oldBright = cv2.cvtColor(cv2.imread('images/oldBright.jpg'), cv2.COLOR_BGR2RGB) oldSet = (old, oldBeard, oldHair, oldSmile, oldNoise, oldBright) def createDataMatrix(images): numImages = len(images)

Select option presets messing up after manual select

I have a list of permissions in a <select> element, and three radio buttons to select presets, instead of seelcting permissions manually. I use the same trigger function for all four elements, and the radio buttons work beautifully until you select something manually, and then they scre up completely. I assume that it is my XOR if(selectItems.includes(option.value) ^ invert) ... that is clogging up the works, but when I do step-through debugging, it looks correct, but the result is not the expected one... document.getElementById('userTypeAdminInhouse').addEventListener('change', selectScope); document.getElementById('userTypeAdminClient').addEventListener('change', selectScope); document.getElementById('userTypeUser').addEventListener('change', selectScope); document.getElementById('scope').addEventListener('change', selectScope); function selectScope(e) { let scopeSelect = document.getElementById('sc

Protractor-cucumber-framework: how to run only one test?

FYI, none of the other Stackoverflow questions/answers have resolved this for me. In an Angular project, we're using Protractor Cucumber Framework for our E2E tests. I can't figure out how to run only one single test via tags . You're supposed to be able to edit the tags inside of the cucumberOpts property of the protractor.conf.js file. But when I add a tag @testOnlyThis there, then add that tag to a test in a .feature file, then run npm run e2e:ci (which, according to package.json, runs "protractor ./e2e/protractor.conf.js" ), Protractor still runs every single E2E test in our suite. Other changes made in the protractor.conf.js file take effect, but editing the tags seems to have zero effect. What gives? protractor.conf.js // @ts-check // Protractor configuration file, see link for more information // https://github.com/angular/protractor/blob/master/lib/config.ts const path = require('path'); const fs = require('fs'); const cucumb

Google App Engine Error: Server Error but can't find error in logs

My deployed Flask web app keeps throwing “Error: Server Error The server encountered an error and could not complete your request. Please try again in 30 seconds”. However, I can’t find any error in the logs: 2022-05-30 00:35:40 default[20220529t172208] [2022-05-30 00:35:40 +0000] [10] [INFO] Starting gunicorn 20.1.0 2022-05-30 00:35:40 default[20220529t172208] [2022-05-30 00:35:40 +0000] [10] [INFO] Listening at: http://0.0.0.0:8081 (10) 2022-05-30 00:35:40 default[20220529t172208] [2022-05-30 00:35:40 +0000] [10] [INFO] Using worker: sync 2022-05-30 00:35:40 default[20220529t172208] [2022-05-30 00:35:40 +0000] [15] [INFO] Booting worker with pid: 15 2022-05-30 00:35:42 default[20220529t172208] 2022-05-30 00:35:42.693664: W tensorflow/stream_executor/platform/default/dso_loader.cc:64] Could not load dynamic library 'libcudart.so.11.0'; dlerror: libcudart.so.11.0: cannot open shared object file: No such file or directory; LD_LIBRARY_PATH: /layers/google.python.pip/pip/lib

(ursina) Prevent partially transparent model

I'm using Ursina with Python3.8 to do some 3D world stuff. I wanted to load in a 3D model of the portal gun, just to see if I could do it. I've done that sucessfully, but it looks weird . I've attached some screenshots so you can see what I mean. As far as I can tell, it looks like the surface i'm looking at on the model is transparent... and i'm seeing the inside of the model. I want the portal gun to look the way it does in the real Portal games Does anyone know how I can prevent the weird transparency so it doesn't show the inside of the model? The line of code I used to add the entity in-game: Entity(model='portal_gun.fbx', position=(.5,3,.25), scale=.08, origin_z=-.5, rotation_z=0, color=pcolor, on_cooldown=False, name="gun", texture=("/models/tex/w_portalgun.png"), shader=unlit_shader) For context, it does this with both 'unlit_shader' and 'lit_with_shadows_shader' I'm using this 3D model: https://ske

How do I set up my react-hot-loader to react to changes instantly?

I am building a very simple, 'Hello World' style server using MongoDB, React, Babel, Node.js, Webpack, Express, and a couple other software modules. I am able to build, compile, and run said server, but hot-loader never updates the DOM. I get no errors in my terminal and my server otherwise runs fine, but in my browser console I get the following: Uncaught EvalError: Refused to evaluate a string as JavaScript because 'unsafe-eval' is not an allowed source of script in the following Content Security Policy directive: "script-src 'self'". at Object../node_modules/webpack-hot-middleware/client.js?reload=true (bundle.js:1197:1) at __webpack_require__ (bundle.js:726:30) at fn (bundle.js:101:20) at Object.0 (bundle.js:1287:1) at __webpack_require__ (bundle.js:726:30) at bundle.js:793:37 at bundle.js:796:10 My non-dev dependencies associated with hot-loader and listed in my package.json are the following (Outdated versions were required for the server I&#

Web scraping with BeautifulSoup .find() always returns None

Relevant part of the DOM: Screenshot of the DOM This is the code I wrote: from bs4 import BeautifulSoup import requests URL = 'https://www.cheapflights.com.sg/flight-search/SIN-KUL/2022-06-04?sort=bestflight_a&attempt=3&lastms=1653844067064' page = requests.get(URL) soup = BeautifulSoup(page.content, 'html.parser') flight = soup.find('div', class_= 'resultWrapper') print(flight) The result that I get whenever print(flight) is executed is always None. I have tried changing to div tags with different class names but it still always returns None. The soup seems to be fine though because when I execute print(soup) it returns a text version of the DOM so the problem seems to be with the next line Any suggestions on how I can get something other than None? Thank you! source https://stackoverflow.com/questions/72425884/web-scraping-with-beautifulsoup-find-always-returns-none

How to save data to a Django model in views.py?

I am trying to create an e-commerce site (CS50 Project 2) that allows the user to add a listing, created through the Listings Model, to their WatchList. I am using a Django form with a Boolean field. I need help saving the listing to the WatchList Model. Also, since there will be more than one WatchList because of the multiple users, should I implement Sessions, and if so, how do I do that? views.py def listing(request, id): #gets listing listing = Listings.objects.get(id=id) watchlist_form = WatchListForm() watchlist_form = WatchListForm(request.POST) if watchlist_form.is_valid(): watchlist = watchlist_form.save(commit=False) watchlist.user = request.user watchlist.save() return render(request, "auctions/listing.html",{ "auction_listing": listing, "watchlistForm": watchlist_form }) else: return render(request, "auctions/listing.html",{

request body is not good formatted

I'm sending a post request in x-www-form-urlencoded form but as is it shown in the pictures i don't know why the body of the request doesn't appear as it must, can anyone help me with that please ? when i remove the stringify method i receive the same request body See the screenshot bellow to understand the problem. code received body Via Active questions tagged javascript - Stack Overflow https://ift.tt/A1CPclZ

pandas timedelta with float argument

pandas Timedelta documentation states that the value input parameter should be of the following types: valueTimedelta, timedelta, np.timedelta64, str, or int However, when I use a floating point number for value , it seems to work fine. For example: pd.Timedelta(1.234234, "h") yields Timedelta('0 days 01:14:03.242400') This functionality is said to be based on numpy's timedelta64 which indeed raises an error when passed a floating point argument. So, is it always safe to use a floating point number for value with pandas Timedelta ? Is the docstring simply wrong? source https://stackoverflow.com/questions/72418372/pandas-timedelta-with-float-argument

How to format object points for cv2.calibrateCamera()? OpenCV

I am trying to pass custom object points and image points into cv2.calibrateCamera() . By custom points I mean points I have calculated without finding chessboard patterns. I'm trying to only warp the image horizontally (x direction) and I'm using the image points as a "map from" and object points as a "map to". My object points look like this: [[[ 254.1 0. 0. ]] [[ 268.40825 0. 0. ]] [[ 282.7165 0. 0. ]] ... [[1541.8425 1080. 0. ]] [[1556.15075 1080. 0. ]] [[1570.459 1080. 0. ]]] code: object_points = np.empty((0, 1, 3)) for p in range(0, 1081, 5): for q in range(0, 93): t = 0.1075 * q object_points = np.append(object_points, [[[get_undistorted_value(t), float(p), 0.0]]], axis=0) But I get an error when passing them to calibrateCamera() . objectPoints should contain vector of vectors of points of type Point3f in function 'cv::coll

rsa encryption with flask and javascript

I'm trying to encrypt the data twice with rsa public keys, I'm getting a false value in javascript when I try to encrypt the data. What I'm trying to do is generate the public and private keys in flask, generate the client public and private keys to use unique to each call, encrypt the data client side using jsencrypt, decrypt the data server side using pycryptodome here's my code in app.py from flask import Flask from flask import render_template from flask import request import Crypto from Crypto.PublicKey import RSA from Crypto import Random from base64 import b64decode application = Flask(__name__, static_url_path='/static') random_generator = Random.new().read key = RSA.generate(2048, random_generator) #generate public and private keys @application.route("/") def hello(): return "<h1 style='color:blue'>Hello There!</h1>" @application.route("/register") def register(): crypto_key = key.publi

JavaScript: Fetch text from php and alert

quite a noob question, but I tried to use php for the first time and can't get it to work... I have the most basic php file <?php echo 'Hello World!'; ?> and I try to fetch the output and alert that. Just for learning how to do that... My JS code (more or less like here ): fetch('./test.php').then(function(response) { return response.text().then(function(text) { alert(text); }); }); Both file (test.php and the js file are in the same folder). Could someone tell me what is wrong here? Thanks, celdri Via Active questions tagged javascript - Stack Overflow https://ift.tt/IfxcoWk

How I can make ICMP Pinger code work using python?

I have a problem with running a python code in pox controller... I have a code that use ping3 to ping between a pox controller and two servers. However, every time the ping returns (None) as a result and I can't figure out why. I have tried to go through the code of the icmp pinger and I find out that this line: whatReady = select.select([mySocket], [], [], timeLeft) always return this result: [],[],[] and because of this ping always return (None) instead of numerical number. The icmp pinger code: from socket import * import socket import os import sys import struct import time import select import binascii ICMP_ECHO_REQUEST = 8 def checksum(str): csum = 0 countTo = (len(str) / 2) * 2 count = 0 while count < countTo: thisVal = ord(str[count+1]) * 256 + ord(str[count]) csum = csum + thisVal csum = csum & 0xffffffffL count = count + 2 if countTo < len(str): csum = csum + ord(str[len(str) - 1])

PDI--- Delete Object in a json file sourced from a column if conditions meet

In PDI, I am trying to compare data from a query(STG_FULFILLMENT_QTY_AGG) with data in Json array being sourced from a column json in Sales Queues table input. When the order_number and extid is same we compare the count(fullfilments.line_items) and quantity(which is the sum of fullfilments.line_items.quantity) . If the order_number and ext_if combination match along with count and sum above, we leave the json struct as it is. If not, we remove the refund. the code works fine in Visual Studio. I am new to pentaho and I think the code needs to be changed as only core js works with this tool. In the Orders file are sample json structure, for example Order_number (66 in this case) need to calculate and compare the count of line items(6 in this case) along with the Quantity of items(7 in this case), if it doesn't match need to remove Object Refund along with its elements, else No Changes. ``````Sample File```````` [ { "app_id": 111, "fulfillments&q

Google Auth OAuth 2.0 SvelteKit wierd behavior

I am using Google Auth OAuth 2.0 One Tap Sign and Sveltekit, and I got some really weird behavior, I followed this doc https://developers.google.com/identity/gsi/web/guides/overview with javascript onMount(async () => { const handleCredentialResponse = async (response) => { console.log('Encoded JWT ID token: ' + response.credential); }; google.accounts.id.initialize({ client_id: clientId, callback: handleCredentialResponse, }); google.accounts.id.renderButton( document.getElementById('buttonDiv'), { theme: 'outline', size: 'large' } // customization attributes ); google.accounts.id.prompt(); }); the code from the doc. Sometimes it works everything goes well, Sometimes I got Uncaught (in promise) ReferenceError: google is not defined And some mobile / mobile browsers I get [GSI_LOGGER]: The given origin is not allowed for the given client ID. but works on laptop Hop

Problem with Open Cv installation on conda

I copied the link conda install -c conda-forge opencv from the homepage https://anaconda.org/conda-forge/opencv and pasted it into Anaconda Prompt to be able to use Open Cv on Spyder. Unfortunately I am getting this error from Anaconda Prompt as shown in the picture. What can I do about this problem? I would be very grateful for help source https://stackoverflow.com/questions/72408810/problem-with-open-cv-installation-on-conda

download the pdf of component in react

I have a page that consist of a component that has a chart.js component. I use html2canvas and then jspdf for create a pdf of component but there is problem with chart.js on responsive mode .i want to chart in pdf be same as desktop chart but when screen resize the chart resize to based on width is there a way to fix this issue? Via Active questions tagged javascript - Stack Overflow https://ift.tt/BNnrH6g

Need help implementing ZILN custom loss function in lightGBM

Im trying to implement this zero-inflated log normal loss function based on this paper in lightGBM ( https://arxiv.org/pdf/1912.07753.pdf ) (page 5). But, admittedly, I just don’t know how. I don’t understand how to get the gradient and hessian of this function in order to implement it in LGBM and I’ve never needed to implement a custom loss function in the past. The authors of this paper have open sourced their code, and the function is available in tensorflow ( https://github.com/google/lifetime_value/blob/master/lifetime_value/zero_inflated_lognormal.py ), but I’m unable to translate this to fit the parameters required for a custom loss function in LightGBM. An example of how LGBM accepts custom loss functions— loglikelihood loss would be written as: def loglikelihood(preds, train_data): labels = train_data.get_label() preds = 1. / (1. + np.exp(-preds)) grad = preds - labels hess = preds * (1. - preds) return grad, hess Similarly, I would need to define a cust

Can't run react-native app on iOS 5 error: duplicate symbols for architecture x86_64

Log output: duplicate symbol '_bridgeRef' in: /Users/sistemas/Library/Developer/Xcode/DerivedData/AppRino-dpmstbwiuaxsmaaznuvxrkhqxixf/Build/Products/Debug-iphonesimulator/react-native-blob-util/libreact-native-blob-util.a(ReactNativeBlobUtil.o) /Users/sistemas/Library/Developer/Xcode/DerivedData/AppRino-dpmstbwiuaxsmaaznuvxrkhqxixf/Build/Products/Debug-iphonesimulator/rn-fetch-blob/librn-fetch-blob.a(RNFetchBlob.o) duplicate symbol '_fsQueue' in: /Users/sistemas/Library/Developer/Xcode/DerivedData/AppRino-dpmstbwiuaxsmaaznuvxrkhqxixf/Build/Products/Debug-iphonesimulator/react-native-blob-util/libreact-native-blob-util.a(ReactNativeBlobUtil.o) /Users/sistemas/Library/Developer/Xcode/DerivedData/AppRino-dpmstbwiuaxsmaaznuvxrkhqxixf/Build/Products/Debug-iphonesimulator/rn-fetch-blob/librn-fetch-blob.a(RNFetchBlob.o) duplicate symbol '_commonTaskQueue' in: /Users/sistemas/Library/Developer/Xcode/DerivedData/AppRino-dpmstbwiuaxsmaaznuvxrkhqxixf/Build/Products/Debug

How to check if an object key is in another object of objects

I have the following objects: const allMembers = { "-Lz8YxHiwp8QZW3TqAFn": { "first": "foo", "last": "bar", "uid": "-Lz8YxHiwp8QZW3TqAFn" }, "-Lz8YxHqQXWoaGOFRLrO": { "first": "foo", "last": "bar", "uid": "-Lz8YxHqQXWoaGOFRLrO" }, "-Lz8YxHsMItaaTVNyQRE": { "first": "foo", "last": "bar", "uid": "-Lz8YxHsMItaaTVNyQRE" }, "-Lz8YxHwuVBMWl0Go6C5": { "first": "foo", "last": "bar", "uid": "-Lz8YxHwuVBMWl0Go6C5" }, "-Lz8YxHy0S-QkDaE1PkX": { "first": "foo", "last": "bar", "uid": "-Lz8YxHy0S-QkDaE1PkX&q

How come the difference between 'View page source' and document.querySelector("html").innerHTML?

I want to extract subtitles from this YouTube page ( link ). I found timedtext , when looking via 'View page source'. But not when I search via javascript console. It won't find it: document.querySelector("html").innerHTML.match("timedtext") But for this other YouTube page, it does actually work both. How come the difference and how to fix it? Via Active questions tagged javascript - Stack Overflow https://ift.tt/ajEu7kn

Cant access children in component used as element in Route (react-router-dom 6.3.0)

Im using react: 17.0.2 and react-router-dom: 6.3.0 . My current App.js snippet looks like this: class App extends React.Component { render() { return ( <div className="App"> <Routes> <Route element={<Layout/>}> <Route path="/home" element={<Home/>} /> <Route path="/login" element={<Login/>} /> <Route path="/signup" element={<Signup/>} /> </Route> <Route exact path='/' element={<Intro/>}/> </Routes> </div> ); } } The route to '/' should not use the Layout component, so I need to exclude it from the context. Within Layout.js I need to access the children like so: const Layout = ({ children }) => { console.log(childr

How to dynamically import_module from a relative path with python importlib

My folder structure looks like: __init__.py core/ fields.py managers.py models.py __init__.py models/ products.py suppliers.py __init__.py From class A in fields.py I'm trying to load class Supplier using importlib.load_module from which is defined in products.py or suppliers.py. This is needed to populate some configurations in order to generate some sql. The approach below generates TypeError: the 'package' argument is required to perform a relative import for '..models.suppliers.Supplier'' . I'm not sure how to define the package, as this isn't an installed package. import importlib model_name = "Supplier" path = f"...models.{model_name.lower()}s.{model_name}" model = importlib.import_module(path) To try and resolve this I've tried out various combination of something like below to no avail. Error ModuleNotFoundError: No module named '.core' or ModuleNotFoundError: No module named &#

How to write xml.etree._Element to a file in python?

I have an element of a tree that I want to write to a file, but you can only write strings to a file and I can't seem to convert it to a string. I tried the following: elem = tree.find('Element', {}) file = open(filepath, "w+") file.write(prod.text) file.close() Which gives the following error: TypeError: write() argument must be str, not None even though elem is not None My other approach was: elem = tree.find('Element', {}) prod.write(filepath, pretty_print=True) file.close() Which gave: AttributeError: 'lxml.etree._Element' object has no attribute 'write' Any ideas how to get it to work? source https://stackoverflow.com/questions/72396880/how-to-write-xml-etree-element-to-a-file-in-python

error ajax laravel 405 method not allowed

I try to insert data in database with Ajax, but it doesn't work Error: POST http://127.0.0.1:8000/%7B%7Broute('achats.store')%7D%7D 405 (Method Not Allowed) Controller: $achat = new achat(); $achat->libellé=$request->input('libll'); $achat->date_achat=$request->input('achatDate'); $achat->montant_total=$request->input('montant'); $achat->Agent=Auth::user()->id; $achat->fournisseur=$request->get('frn'); if($request->file('bon')){ $bon=$request->file('bon'); $achat->bon=$bon->getClientOriginalName(); $bon->move('bon',$bon->getClientOriginalName()); } $achat->save(); return response()->json([ 'status'=>true, 'msg'=>'Sauvegardé avec succès' ]); return response()->json([ 'statu

JS remove class Name dynamically

I have a requirement to remove a class name dynamically via js. The reason to do so is that I'm trying to remove the icon of sorting a specific column from a table. When I inspect the element - I see I have ng-class with the same class name as the class attribute. I don't have any access to the angular file - since it's a third-party app, but I can write some JS in it. <th title="" ng-repeat="$column in $columns" ng-class="{ 'sortable': $column.sortable(this), 'sort-asc': params.sorting()[$column.sortable(this)]=='asc', 'sort-desc': params.sorting()[$column.sortable(this)]=='desc' }" class="col_poi_Id_356 sortable"> </th> When I'm removing the "sortable" from the class manually from the developer console - It works great. But when I'm trying to do: element.remove("sortable"); it removes the "sortable" both from the class and fr

How to use OpenCV convertPointsToHomogeneous() method

I thought that if you read in an image and then passed it into this method as a float matrix that it would work... but it gives an error. import cv2 import numpy as np img = cv2.imread('image.jpg') hom_img = cv2.convertPointsToHomogeneous(img.astype(np.float32)) Error: hom_img = cv2.convertPointsToHomogeneous(img.astype(np.float32)) cv2.error: OpenCV(4.5.5) D:\a\opencv-python\opencv-python\opencv\modules\calib3d \src\fundam.cpp:1125: error: (-215:Assertion failed) npoints >= 0 in function 'cv::convertPointsToHomogeneous' source https://stackoverflow.com/questions/72369236/how-to-use-opencv-convertpointstohomogeneous-method

AWS API Gateway IAM Authorization - Generating signature using crypto.js

I am working on an app for Jira Cloud platform using forge framework. I created an HTTP endpoint using AWS API Gateway. This endpoint triggers a lambda function that does some operation on DynamoDB. I employed IAM authorization for the endpoint. After failing trials to use aws4 library with forge, I used the following function that is taken from AWS documentation to create signing key. However, while sending the request using javascript, I always get "{message: Forbidden}".: export function getAWSHeaders(){ const accessKey = "" const secretKey = "" const regionName = "us-east-1" const serviceName = "execute-api" var date = new Date().toISOString().split('.')[0] + 'Z'; date = date.split("-").join("").split(":").join("") var dateWithoutTime = date.split("T")[0] var myHeaders = {} myHeaders["X-Amz-Date"] = date; var crypto = require("

I am working on airport data and I am new to python. I have a code in STATA and I need help to convert it into python [closed]

I am working on airport data and I am new to python. I have a code in STATA and I need help to convert it into python. The code is as follows: gen FlightID= origin+ dest+ op_unique_carrier+ string(op_carrier_fl_num) egen N_Flights = count( FlightID ), by ( FlightID ) keep fl_date op_unique_carrier tail_num origin dest crs_dep_time dep_time dep_delay taxi_out wheels_off wheels_on taxi_in crs_arr_time arr_time FlightID N_Flights drop taxi_in crs_arr_time //crs_dep_time drop if dep_time==. drop if wheels_off==. keep if origin=="EWR" drop if wheels_off<dep_time //revisit to bring back those flights around midnight sort fl_date dep_time gen fl_id=_n //gen Departed = 1 //replace Departed= Departed[_n-1]+1 if _n>1 sort fl_date wheels_off //gen Tookoff = 0 //replace Tookoff= Tookoff[_n-1]+1 if _n>1 //gen DepartedQ=Departed-Tookoff gen date=date(fl_date, "YMD") format date %td gen dow=dow( date)+1 gen QuJump=0 replace QuJump=1 if dep_time>

How to find a variable that is causing scope colision?

i just started a new html project as any other day, but totay i was suprised with scope colision in javascript. The point is i'm trying to declare a variable called top, but i think that i had already declared it in another file and i would like to know if there is a fast way to find this file and fix it. This is my html: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>day one</title> </head> <body> <h1>hiii</h1> <script src="script.js"></script> </body> </html> This is my javascript: let top = [0, 0, 0] When i open the devtools and look at the console there is an error message there: script.js:1 Uncaught SyntaxError: Identifier 

Implementing Machine learning model into flutter app

i have created a machine learning model that can predict laptop prices with python using GridSearchCV algorithm, i want to implement it into my flutter app, so that the user when he chooses his laptop specifications and hit "tap to predict" button, the estimated price will be shown. i don't know backend very well. My model with GridSearchCV my flutter app source https://stackoverflow.com/questions/72347420/implementing-machine-learning-model-into-flutter-app

Airflow Dag won't move past "queued" state

This code was working just fine a couple hours ago, but suddenly my dags started getting stuck in "queued" state. Here's what I'm trying to run: from airflow import DAG from airflow.operators.python_operator import PythonOperator from datetime import datetime as dt def test_function(): print('Hello there') default_args = { 'owner': 'airflow', 'depends_on_past': False, 'email_on_failure': False, 'email_on_retry': False, 'retries': 0 } with DAG( 'test', default_args=default_args, description='A dag used for testing...', start_date=dt(2017, 1, 1), tags=['example'] ) as dag: start = PythonOperator( task_id='test', python_callable=test_function, dag=dag ) start Here's what it looks like when it gets stuck. If I replace the PythonOperator with a PostgresOperator it gets stuck as well. The Dum

Finding multiple non-zero value in an image

I have this kind of image, and I want to draw rectangle on each of non zero value of them. I am trying to use this code from other thread import cv2 import numpy as np img = cv2.imread('blob_in_the_middle.png', cv2.IMREAD_GRAYSCALE) positions = np.nonzero(img) top = positions[0].min() bottom = positions[0].max() left = positions[1].min() right = positions[1].max() output = cv2.rectangle(cv2.cvtColor(img, cv2.COLOR_GRAY2BGR) , (left, top), (right, bottom), (0,255,0), 1) cv2.imwrite('blob_with_bounds.png', output) But what I get is this: What I expect to get is something like this: source https://stackoverflow.com/questions/72366224/finding-multiple-non-zero-value-in-an-image

can anyone help me Convert this typescript script to php, new to typescript

Basically i am creating a trading script in php , i have done almost 80% work , i need to convert this typescript or javascript code to php , iam a native php user and not so familier with javascript, i tried it multiple errors but i failed , please help me Exchange class- export type Balance = Record<string, number>; export enum OrderSide { BUY = "BUY", SELL = "SELL", } export interface OrderConfig { side: OrderSide; pair: string; amount: number; price: number; } export class Exchange { public async getBalance(): Promise<Balance>; public async createOrder(config: OrderConfig); public async getAllPrices(): Promise<Record<string, number>>; } main code- import { Exchange, OrderSide } from "./Exchange"; export interface BotConfig { pair: string; } export interface GridLine { active: boolean; price: number; side: OrderSide; } export default class GridBot { private MAX_QUOTE_ASSET_AMOUNT = 200;

Catch error and put inside a component ReactJS

I have an issue, this issue is to take an error from my try catch and pass this message error to my custom alert component. Below is my code: export const Register = () => { const dispatch = useDispatch(); const [openError, setOpenError] = useState(false); const AlertError = openError ? ( <Dialog open={openError}> <AlertCard open={openError} handleClose={handleCloseError} borderTop="1vh solid red" color="black" severity="error" title="Cadastro falhou" description='message' //put here message error /> </Dialog> ) : ( "" ); const formik = useFormik({ initialValues: { email: "", password: "", first_name: "", last_name: "", confirmPassword: "", newsletter: "", }, validationSchema: validationSchema,

Pandas - concatenating selected rows from several groups with additional condition

I have an example +─────────────+────────+────────+────────+ | main_group | COL_A | COL_B | COL_C | +─────────────+────────+────────+────────+ | 0 | TXT1 | | None | | 0 | TXT2 | | None | | 0 | 5 | | None | | 0 | 1.93 | 1.93 | 0 | | 0 | 7.60 | 7.60 | 1 | | 0 | 2.46 | 2.46 | 1 | | 1 | TXT11 | | None | | 1 | TXT12 | | None | | 1 | 0.50 | | None | | 1 | 0.45 | 0.45 | 0 | | 1 | 0.31 | 0.31 | 1 | | 1 | 0.35 | 0.35 | 1 | | 1 | 0.73 | 0.73 | 1 | | 2 | 0.5 | | None | | 2 | 4.15 | 4.15 | 0 | | 2 | 2.98 | 2.98 | 0 | | 2 | 1.53 | 1.53 | 0 | | 3 | 4.46 | | None | | 3 | 4.00 | 4.00 | 0 | | 3 | 0.95 | 0.95 | 1