Inserting NaN in specific positions in an array in Python Posted: 16 Jul 2022 03:55 AM PDT I have two arrays P and J . I want to insert C1=nan in P according to positions in J . But I am getting an error. I present the expected output. import numpy as np from numpy import nan J=np.array([[1, 4, 5, 7]]) P=np.array([[1.35961580e+03, 1.35179719e+03, 1.30676673e+03, 1.17569069e+02, 5.19255443e+00, 5.19255443e+00, 5.19255443e+00, 1.00000000e-09]]) C1=nan P=np.insert(P,J,[C1],axis=1) print("Pnew =",[P]) The error is in <module> P=np.insert(P,J,[C1],axis=1) File "<__array_function__ internals>", line 5, in insert File "C:\Users\USER\anaconda3\lib\site-packages\numpy\lib\function_base.py", line 4626, in insert raise ValueError( ValueError: index array argument obj to insert must be one dimensional or scalar The expected output is array([[1.35961580e+03, nan, 1.35179719e+03, 1.30676673e+03, nan, nan, 1.17569069e+02, nan, 5.19255443e+00, 5.19255443e+00, 5.19255443e+00, 1.00000000e-09]]) |
How to get a value from an Html page? Posted: 16 Jul 2022 03:55 AM PDT In this portion of code of an Amazon scraper program that only checks the price of an item, i get an error saying TypeError: object of type 'Response' has no len() , how to solve this? I simply want to get the value from the id="corePriceDisplay_desktop_feature_div") , here is the portion of code: headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36'} url_the_last_of_us = "https://www.amazon.it/Last-Us-Parte-Remake-PS5/dp/B0B3X2N4PR/ref=sr_1_1?__mk_it_IT=%C3%85M%C3%85%C5%BD%C3%95%C3%91&crid=236V6E1BSSZMO&keywords=the+last+of+us+ps5&qid=1657964276&sprefix=the+last+of+us+ps5%2Caps%2C133&sr=8-1" apri_sito = requests.get(url_the_last_of_us, headers=headers) soup = bs4.BeautifulSoup(apri_sito, "html.parser") prezzo_tlou = soup.find(id="corePriceDisplay_desktop_feature_div").get_text() And i imported these libraries: import bs4 import urllib.request import requests |
Cannot resolve method 'getStackTrace' in 'ExceptionUtils' error Posted: 16 Jul 2022 03:55 AM PDT I am trying to build a global exception class and followed this example. @Slf4j(topic = "GLOBAL_EXCEPTION_HANDLER") @RestControllerAdvice public class GlobalExceptionHandler extends ResponseEntityExceptionHandler { // code omitted private ResponseEntity<Object> buildErrorResponse(Exception exception, String message, HttpStatus httpStatus, WebRequest request) { ErrorResponse errorResponse = new ErrorResponse(httpStatus.value(), message); if (printStackTrace && isTraceOn(request)) { errorResponse.setStackTrace(ExceptionUtils.getStackTrace(exception));//! } return ResponseEntity.status(httpStatus).body(errorResponse); } } However, the errorResponse.setStackTrace(ExceptionUtils.getStackTrace(exception)); line gives "Cannot resolve method 'getStackTrace' in 'ExceptionUtils'" error. I checked related maven references and there is nothing missed in my project. May it be related to the following library that is inferred when I mouse over ExceptionUtils ? org.apache.tomcat.util Maven: org.apache.tomcat.embed:tomcat-embed-core:9.0.64 (tomcat-embed-core-9.0.64.jar) |
How to solve "dbt: error unrecognised arguments: --schema"? Posted: 16 Jul 2022 03:55 AM PDT Here I am using windows laptop with python version 3.10.4 and dbt version 1.1.1 while running this command '''dbt test --schema --models'''in cmd I am getting error as '''dbt: error: unrecognized arguments: --schema''' |
Why npm run dev command is showing error cannot find module '. /dist/rx' Posted: 16 Jul 2022 03:55 AM PDT C:\Users\sharm\codeweb\eth-to-do-list>npm run dev npm WARN config global --global , --local are deprecated. Use --location=global instead. eth-to-do-list@1.0.0 dev lite-server node:internal/modules/cjs/loader:936 throw err; ^ Error: Cannot find module './dist/rx' Require stack: - C:\Users\sharm\codeweb\eth-to-do-list\node_modules\rx\index.js
- C:\Users\sharm\codeweb\eth-to-do-list\node_modules\browser-sync\dist\file-watcher.js
- C:\Users\sharm\codeweb\eth-to-do-list\node_modules\browser-sync\dist\browser-sync.js
- C:\Users\sharm\codeweb\eth-to-do-list\node_modules\browser-sync\dist\index.js
- C:\Users\sharm\codeweb\eth-to-do-list\node_modules\lite-server\lib\lite-server.js
- C:\Users\sharm\codeweb\eth-to-do-list\node_modules\lite-server\bin\lite-server at Function.Module._resolveFilename (node:internal/modules/cjs/loader:933:15) at Function.Module._load (node:internal/modules/cjs/loader:778:27) at Module.require (node:internal/modules/cjs/loader:1005:19) at require (node:internal/modules/cjs/helpers:102:18) at Object. (C:\Users\sharm\codeweb\eth-to-do-list\node_modules\rx\index.js:1:10) at Module._compile (node:internal/modules/cjs/loader:1105:14) at Object.Module._extensions..js (node:internal/modules/cjs/loader:1159:10) at Module.load (node:internal/modules/cjs/loader:981:32) at Function.Module._load (node:internal/modules/cjs/loader:822:12) at Module.require (node:internal/modules/cjs/loader:1005:19) { code: 'MODULE_NOT_FOUND', requireStack: [ 'C:\Users\sharm\codeweb\eth-to-do-list\node_modules\rx\index.js', 'C:\Users\sharm\codeweb\eth-to-do-list\node_modules\browser-sync\dist\file-watcher.js', 'C:\Users\sharm\codeweb\eth-to-do-list\node_modules\browser-sync\dist\browser-sync.js', 'C:\Users\sharm\codeweb\eth-to-do-list\node_modules\browser-sync\dist\index.js', 'C:\Users\sharm\codeweb\eth-to-do-list\node_modules\lite-server\lib\lite-server.js', 'C:\Users\sharm\codeweb\eth-to-do-list\node_modules\lite-server\bin\lite-server' ] }
|
Pass AWS authorizer policy context values to .net 6 minimal api Posted: 16 Jul 2022 03:54 AM PDT I have a scenerio that, I need to send custom headers from the api gateway after successfully authorised using lambda authorizer. From authorizer, i will be sending the json policy return with the context json key value pair as well. My question is, now i need to pass the context key value pair as custom headers to the minimal api from the api gateway. Can you please suggest me how to achieve this, since iam started learning AWS a month ago and working on the same. It will he helpful if I get some suggestions from the people who worked on these scenarios before. Note : Lambda function is deployed with .net 6 minimal api and api gate resources call the deployed lambda Api gateway resources are lambda proxy enabled in lamda integration part. |
wrapper emitted() not working in vue test utils composition api Posted: 16 Jul 2022 03:54 AM PDT I am trying to make a simple test to check that the button is emitting an event called "click" every time it is detected, the problem is that when I use wrapper.emitted('click') to validate that it is receiving it, it always arrives as an empty object... I don't know what I may be doing wrong. Current versions: Vue: 3.2.31 Vitest: 0.7.12 Vite: 2.8.6 Vue/test-utils: 2.0.0-rc.17 <template> <button class="eci-button" :disabled="props.disabled" @click="handleClick" > {{ props.label }} </button> </template> <script setup lang="ts"> /* Interfaces and types */ interface Props { label: string disabled?: boolean } /* Props */ const props = withDefaults(defineProps<Props>(), { disabled: false }) /* Events */ const emit = defineEmits<{ (e: 'click'): void }>() /* Methods */ const handleClick = () => { emit('click') } </script> <style lang="scss" src="./Button.scss"></style> Test test('should render and emit event at click', async () => { const label = 'Siguiente' const wrapper = mount(Button, { props: { label } }) wrapper.trigger('click') expect(wrapper.emitted()).toHaveProperty('click') }) Result |
What data model to use for Blazor tables Posted: 16 Jul 2022 03:54 AM PDT I am building a .Net 6 Blazor web app. I needs to display lots of html tables with data. For example I need tables that look like this: |Jul 17 | Jul 16 | Jul 15 --------------------------------- . . . Hour 1 | 11.213 | 123.23 | 123.54 Hour 2 | 12.234 | 234.45 | 54.34 . . . Code: I want to display a lot of tabular data and I would like to be able to compute new tabular data based on the ones I already have, like calculating averages of an existing "table" models rows. I considered having a data structure like this: public class DataTable { public DataTable(Dictionary<string, Dictionary<string, decimal?>>? values) { Values = values ?? new Dictionary<string, Dictionary<string, decimal?>>(); } public Dictionary<string, Dictionary<string, decimal?>>? Values { get; set; } } Questions: - Is this a good approach?
- How can I store optional row and column headers?
- What if I want to create a table with strings? I can't restrict extension methods for a generic class to "number" types, so it seems to no be good design.
|
PTB (PythonTelegramBot) v20: upload file to S3 Posted: 16 Jul 2022 03:54 AM PDT I need to upload the file that I receive from the user in the bot to the S3 remote storage. The bot works asynchronously, and aioboto3, as well as aioboto3, have a non-asynchronous method for uploading files. So I get the file, upload it, and create a process to upload to the server using Python Multiprocessing. However, I can't get the download status. If I wait for the download result using process.join(), it will block the execution flow. What are the options for downloading the file in this case? |
Javascript Canvas Viewport Camera for Top down RPG game Posted: 16 Jul 2022 03:53 AM PDT I've gone over most other posts about this subject. It seems that, everyone, has their own unique problem for their own unique implementation of the "Canvas topdown game". That makes it really hard finding a solution for your problem without refactoring your whole code. So hopefully you guys will be able to help me this time. Simple game (so far) - utilizing Vue3 btw but that's besides the point - most of the code is just Vanilla stuff. Simple topdown map. X and Y Axis What I'm doing in my implementation is taking a PNG I've created with the Tiled application Zoomed in by about 400% - drawing it with ctx.drawImage then I'm also setting boundaries and then drawing the player what I'm doing now is adding a "force" value to the x and y position on key pressed (WASD) Which means the character moves on the map and collision detection works what I want is the map to draw x amount of pixels based on where the character is positioned WITHOUT moving the map since I'm already implementing some SocketIO code to make this multiplayer I'm really really lost here, not sure what I should be doing to make the map draw a viewport.... I hope some of this makes sense Some code function create() { const canvas: HTMLCanvasElement = document.getElementById("game") as HTMLCanvasElement; if (!canvas) return console.error("canvas is undefined"); const ctx: CanvasRenderingContext2D = canvas.getContext("2d") as CanvasRenderingContext2D; ctx.imageSmoothingEnabled = false; initializeGameWindow(canvas, ctx); setEvents(canvas, ctx); const playerSpriteWidth = 192; const playerSpriteHeight = 68; const spriteFrames = 4; background = new Sprite(); player = new Sprite(); update(canvas, ctx); } function update(canvas: HTMLCanvasElement, ctx: CanvasRenderingContext2D) { window.requestAnimationFrame(() => update(canvas, ctx)); drawGame(canvas, ctx); } function drawGame(canvas: HTMLCanvasElement, ctx: CanvasRenderingContext2D) { background.draw(ctx); boundaries.forEach((boundary) => { boundary.draw(ctx); }); player.value.draw(ctx); let moving: boolean = true; player.value.moving = false; if (keys.w.pressed && lastKey.value === "w") { player.value.moving = true; player.value.image = player.value.sprites.up; for (let i = 0; i < boundaries.length; i++) { if ( rectengularCollision(player.value, { ...boundaries[i], position: { x: boundaries[i].position.x, y: boundaries[i].position.y + Sprite.force }, }) ) { moving = false; break; } } if (!moving) return; player.value.position.y -= Sprite.force; } else if (keys.a.pressed && lastKey.value === "a") { player.value.moving = true; player.value.image = player.value.sprites.left; for (let i = 0; i < boundaries.length; i++) { if ( rectengularCollision(player.value, { ...boundaries[i], position: { x: boundaries[i].position.x + Sprite.force, y: boundaries[i].position.y }, }) ) { moving = false; break; } } if (!moving) return; player.value.position.x -= Sprite.force; } else if (keys.s.pressed && lastKey.value === "s") { player.value.moving = true; player.value.image = player.value.sprites.down; for (let i = 0; i < boundaries.length; i++) { if ( rectengularCollision(player.value, { ...boundaries[i], position: { x: boundaries[i].position.x, y: boundaries[i].position.y - Sprite.force }, }) ) { moving = false; break; } } if (!moving) return; player.value.position.y += Sprite.force; } else if (keys.d.pressed && lastKey.value === "d") { player.value.moving = true; player.value.image = player.value.sprites.right; for (let i = 0; i < boundaries.length; i++) { if ( rectengularCollision(player.value, { ...boundaries[i], position: { x: boundaries[i].position.x - Sprite.force, y: boundaries[i].position.y }, }) ) { moving = false; break; } } if (!moving) return; player.value.position.x += Sprite.force; } } export class Sprite { static force: number = 3; // speed, velocity, acceleration, etc. frames: number; spriteIteration: number = 0; elapsed: number = 0; defaultSrc: string; image: HTMLImageElement; sprites: { up: HTMLImageElement; down: HTMLImageElement; left: HTMLImageElement; right: HTMLImageElement }; position: { x: number; y: number }; width: number = 0; height: number = 0; moving: boolean = false; constructor( position: { x: number; y: number }, src : string, frames: number = 1, sprites: { up: string; down: string; left: string; right: string } = { up: "", down: "", left: "", right: "" }, ) { this.defaultSrc = src; this.moving = false; const { up, down, left, right } = this.initSprites(sprites); this.sprites = { up, down, left, right }; this.image = down; this.frames = frames; this.position = position; this.image.onload = () => { this.width = this.image.width / this.frames; this.height = this.image.height; }; } draw(ctx: CanvasRenderingContext2D) { ctx.drawImage( // src this.image, // crop from x axis this.spriteIteration * this.width, // crop from y axis 0, // crop width this.image.width / this.frames, // crop height this.image.height, // x position on canvas this.position.x, // y position on canvas this.position.y, // width on canvas this.image.width / this.frames, // height on canvas this.image.height, ); } initSprites(sprites: { up: string; down: string; left: string; right: string }) { const up = new Image(); up.src = sprites.up; const down = new Image(); down.src = sprites.down !== "" ? sprites.down : this.defaultSrc; const left = new Image(); left.src = sprites.left; const right = new Image(); right.src = sprites.right; return { up, down, left, right }; } } |
PEP8, blank line convention and reduced readability in dense code Posted: 16 Jul 2022 03:53 AM PDT Most of the time, PEP8 does not allow more than 1 blank line inside function or more than 2 blank lines between functions. When code is dense, even 2 blank lines can reduce readability. Is there any guidance how to overcome this? Use some visual elements composed of ASCII characters? def fun1(): """ This does x """ ## Problem 1 # Subproblem 1.1 ... # Subproblem 1.2 ... ## ------------------- ## Problem 2 ... # ------------------------ def fun2(): """ This does y """ pass |
"error CS0103: The name 'targetAngle' does not exist in the current context" in unity 3d while was trying to make a 3rd person camera Posted: 16 Jul 2022 03:54 AM PDT So, I've been trying to make a third-person camera for the game I'm making in Unity 3D. I'm new to game dev(but I understand some things in this because I tried to make games earlier and tried to learn Java a bit) so I used Brackeys' guide on this (https://www.youtube.com/watch?v=4HpC--2iowE), but every time I'm trying to compile the code, it just says that variable targetAngle where's stored math Atan function cannot be used in another variable moveDir for some reason. this is the error "Assets\Scripts\PlayerMovement.cs(67,48): error CS0103: The name 'targetAngle' does not exist in the current context", and here's the code using System.Collections; using System.Collections.Generic; using UnityEngine; public class PlayerMovement : MonoBehaviour { public CharacterController controller; public Transform cam; public float speed = 12f; public float gravity = -9.81f; public float jumpHeight = 3f; public float _doubleJumpMultiplier = 1.5f; public float turnSmoothTime = 0.1f; private float turnSmoothVelocity; public Transform groundCheck; public float groundDistance = 0.4f; public LayerMask groundMask; Vector3 velocity; bool isGrounded; private bool _canDoubleJump = false; bool _playerMove = false; private void Start() { _playerMove = GetComponent<PlayerMovement>(); } void Update() { isGrounded = Physics.CheckSphere(groundCheck.position, groundDistance, groundMask); if(isGrounded && velocity.y < 0) { _canDoubleJump = true; velocity.y = -2f; } else { if(Input.GetButtonDown("Jump") && _canDoubleJump) { velocity.y = 3f * _doubleJumpMultiplier; _canDoubleJump = false; } } float vertical = Input.GetAxisRaw("Vertical"); float horizontal = Input.GetAxisRaw("Horizontal"); Vector3 direction = new Vector3(horizontal, 0f, vertical).normalized; if(direction.magnitude >= 0.1f) { float targetAngle = Mathf.Atan2(direction.x, direction.z) * Mathf.Rad2Deg + cam.eulerAngles.y; float angle = Mathf.SmoothDampAngle(transform.eulerAngles.y, targetAngle, ref turnSmoothVelocity, turnSmoothTime); transform.rotation = Quaternion.Euler(0f, angle, 0f); } Vector3 moveDir = Quaternion.Euler(0f, targetAngle, 0f) * Vector3.forward; controller.Move(moveDir * speed * Time.deltaTime); if(Input.GetButtonDown("Vertical") && isGrounded && _canDoubleJump) { _playerMove = true; } else if(!Input.GetButtonDown("Vertical") && isGrounded && _canDoubleJump) { _playerMove = false; } if(Input.GetButtonDown("Horizontal") && isGrounded && _canDoubleJump) { _playerMove = true; } else if(!Input.GetButtonDown("Horizontal") && isGrounded && _canDoubleJump) { _playerMove = false; } if(Input.GetButtonDown("Jump") && isGrounded) { velocity.y = Mathf.Sqrt(jumpHeight * -2 * gravity); } velocity.y += gravity * Time.deltaTime; controller.Move(velocity * Time.deltaTime); } } |
javascript detect scrolling past the end of the window when scroll event doesn't fire Posted: 16 Jul 2022 03:56 AM PDT I have a site in which all sections take 100vh/vw, and I want to animate the opacity transition when user attempts to scroll up/down. The thing is, the scroll event doesn't fire because the window hasn't really scrolled. here's the codepen, and the gist of it: // css .section { width: 100vw; height: 100vh; opacity: 0; transition: opacity 0.5s; } .section.active { opacity: 1; } // html <div className="section active">Some stuff here...</div> <div className="section">Some stuff here...</div> // js window.addEventListener("scroll", () => { console.log("never fires") }) is this even possible? And if not, any ideas for a workaround? |
What is the error in the code ? I want to call game, then call full name then for output Posted: 16 Jul 2022 03:54 AM PDT // I want to change program namespace WebApplication1.Controllers { public class DomainController : Controller { public string Game() { public string FullName(string first, string last) { if (!string.IsNullOrEmpty(first) && string.IsNullOrEmpty(last)) return "Your First Name is = " + first; else if (string.IsNullOrEmpty(first) && !string.IsNullOrEmpty(last)) return "Last Name is = " + last; else return "Your First Name is = " + first + "And Last Name is = " + last; } return Game(); // I want to call this } } } |
convert dict to csv and upload to folder(csv name should be what df is grouped by) Posted: 16 Jul 2022 03:53 AM PDT I have created a folder called Data_test . The dictionary contains data frames that a grouped by a specific column. I want to loop through the dictionary and convert to csv and have it in the Data_test folder . Each csv name should be what the df is grouped by; for example, if grouped by 'orange' the name of the csv should be orange.csv import pandas as pd import numpy as np import os #create folder to upload CSV too folderName = "Data_test" if os.path.exists(folderName): shutil.rmtree(folderName) os.mkdir(folderName) dirName = os.path.abspath(folderName) #dict contains csvs grouped by specific col grouped_dict_dfs = {key: df.loc[value] for key, value in df.groupby("col1").groups.items()} |
how to save local file content using fetch in javascript [duplicate] Posted: 16 Jul 2022 03:55 AM PDT I have a text.txt file and I want to save its content in a variable. My problem is that I can log the text but I can't store it in a var let fileText; fetch("./text.txt") .then(response => response.text()) .then(text => { fileText = text; }); console.log(fileText); // undefined |
Bad Request 400; Reason "invalid" while creating user (Firebase-Pyrebase4) Posted: 16 Jul 2022 03:54 AM PDT I am trying to: i. Create a user ii. Send verification email with link iii. once verified; use web-app; iv. next time; login directly
There are two ways; using email provider; i. with email and password; ii. password less sign in
I am using pyrebase4 wrapper; and managing login state using flask-sessions; When I try to create user with user = auth.create_user_with_email_and_password(email, password) from signUp page; it throws error 400; bad request; reason='invalid' . And the verification email is never send/received on my email. Login function works just fine (I tried adding an email manually in firebase console and tried login in using pyrebase4). Route I wrote for signUp: @app.route('/signUp', methods=['POST', 'GET']) def signUp(): if request.method == 'POST': email = request.form['email'] password = request.form['password'] try: user = auth.create_user_with_email_and_password(email, password) auth.send_email_verification(user['idToken']) session['user'] = user return redirect(url_for('home')) except requests.exceptions.HTTPError as e: print(e) return render_template('Fails/fail.html', error=e) return render_template('SignIn/signup.html') Code for login looks same; but with user = auth.sign_in_with_email_and_password(email, password) function.
Complete error log: [Errno 400 Client Error: Bad Request for url: https://www.googleapis.com/identitytoolkit/v3/relyingparty/verifyPassword?key=AIzaSyAP2eMADsSDfWBRVvzD7dGCBEA2BeP9zrQ] { "error": { "code": 400, "message": "EMAIL_NOT_FOUND", "errors": [ { "message": "EMAIL_NOT_FOUND", "domain": "global", "reason": "invalid" } ] } } I have referenced this question and other many questions like such on SO: i. Getting a bad request bad request 400 when creating user(Firebase) ii. Why do I see a "400 (Bad Request)" in my developer console when sign-in to Firebase Authentication fails? As referenced in the above question, the pyrebase while does the same, actually didn't register the user in this case, hence didn't work here Most other answers are implemented using JS (as is the case in official docs); Pyrebase/Pyrebase4 docs do not seem to have a function for password-less signIn (?) |
add some delays between request in promis.map using cheerio and nodejs? Posted: 16 Jul 2022 03:54 AM PDT I have following code: urls have 5000 different url, when I try to grab and scrape these urls , I ran into a 500 Error, so I decide to add some delay between each request, I add the {concurrency: 1} but nothing changed. Promise.map(urls, requestPromise) .map((htmlOnePage, index) => { const $ = cheerio.load(htmlOnePage); $('.txtSearch1').each(function () { var h=""; h=$(this).text() h= h.replace(/(\r\n|\n|\r)/gm, "") html44.push (h) }) shareTuple=html44 // ... // some works return shareTuple; }, {concurrency: 1}) .then () .catch((e) => console.log('We encountered an error' + e)); how I can add some random delay between each request here? |
Fill a board using rectangles and L shaped blocks with given size Posted: 16 Jul 2022 03:55 AM PDT This might be an easy problem, but I'm not quite getting it: Given a rectangular puzzle board and 10 puzzle pieces, determine which pieces will fill the puzzle grid. Pieces are shaped as either a rectangle or the letter "L." Use the following rules in order to fill the puzzle board: Pieces must be placed in the board from large to small. If multiple pieces have the same area, use the one with the largest width first. The first puzzle piece is placed in the lower left hand corner of the grid. The following pieces are placed in the leftmost cell of the bottommost row where it will fit. Continue to place pieces in the grid using the rules above until the grid is filled or no more pieces will fit. Print the pieces in the order they fit into the board; if the board cannot be completely filled, print "NONE". Pieces cannot be rotated or flipped in any way. The largest puzzle board will be 9x9. Rectangular pieces are described by 2-character strings, the width followed by height. The "L" pieces are described by 3-character strings: width, height of the vertical part, the width of the vertical part; the base of the "L" has a height of 1. INPUT: There will be 11 lines of input. The first line will contain the 10 puzzle pieces: 2-character or 3-character numeric strings. The remaining 10 lines will each contain 2 integers, representing the width and height, respectively, of the puzzle board. Use only rectangular pieces for the first 5 boards; the last 5 boards can use the "L" shaped puzzle pieces. OUTPUT: Print the pieces used to fill the puzzle board in the order they were used. If the board can't be filled, print NONE. Some examples SAMPLE INPUT: 12, 22, 32, 23, 43, 31, 44, 33, 443, 11 7, 4 6, 3 3, 2 3, 5 2, 2 4, 4 3, 3 5, 3 6, 2 8, 4 SAMPLE OUTPUT: 44, 33, 31 43, 23 22, 12 33, 32 NONE 443, 12,11 32, 31 43,12, 11 32, 22, 12 44, 443, 12, 11 I tried to create a Width by Height 2D array filled with boolean and made it True when placed with block. However, it didn't seem to work. I'm quite new to this type of question. Can someone please provide a solution or give a hint? |
MPDF not downloading PDF on cPanel but works fine when locally hosted (XAMPP) Posted: 16 Jul 2022 03:55 AM PDT Here is the generatepdf.php: <?php include('db.php'); require_once 'vendor/autoload.php'; ob_start(); ?> <?php $student_id = 0; if (isset($_GET['id'])) { $student_id = $_GET['id']; } // var_dump($student_id); $fetchUser = $conn->query("SELECT * from student where id = $student_id")->fetchAll(PDO::FETCH_ASSOC); $subjects = $conn->query("SELECT * FROM subjects WHERE student_id = $student_id")->fetchAll(PDO::FETCH_ASSOC); // // var_dump($fetchUser); // Student Info $name = $fetchUser[0]['name']; $rollno = $fetchUser[0]['rollno']; $image = $fetchUser[0]['image']; $center = $fetchUser[0]['center']; $division = $fetchUser[0]['division']; $academic_year = $fetchUser[0]['academic_year']; $class = $fetchUser[0]['class']; $session = $fetchUser[0]['session1'] . ' - ' . $fetchUser[0]['session2']; $father = $fetchUser[0]['father']; $stream = $fetchUser[0]['stream']; $totalmarks = $fetchUser[0]['totalmarks'];; $obtmarks = $fetchUser[0]['obtmarks']; $marksinwords = $fetchUser[0]['marksinwords']; $percentage = ($fetchUser[0]['obtmarks'] / $fetchUser[0]['totalmarks']) * 100; $percentage = number_format($percentage, 2); $todaysDate = gmdate("M d, Y", strtotime('now')); $html = ' <html> <head> <style> body {font-family: sans-serif; font-size: 10pt; } p { margin: 0pt; } table.items { border: 0.1mm solid #000000; } td { vertical-align: top; } .items td { border-left: 0.1mm solid #000000; border-right: 0.1mm solid #000000; } table thead td { background-color: #EEEEEE; text-align: center; border: 0.1mm solid #000000; font-variant: small-caps; } .items td.blanktotal { background-color: #EEEEEE; border: 0.1mm solid #000000; background-color: #FFFFFF; border: 0mm none #000000; border-top: 0.1mm solid #000000; border-right: 0.1mm solid #000000; } .items td.totals { text-align: right; border: 0.1mm solid #000000; } .items td.cost { text-align: "." center; } </style> </head> <body> <!--mpdf <htmlpageheader name="myheader"> <table width="100%"><tr> <td width="80%" style="color:#000; "><span style="font-weight: bold; font-size: 14pt;">Online Marksheet For TELEGANA UNIVERSITY</span></td> // <td width="20%" style="text-align: right;">Date: ' . $todaysDate . '<br /> </tr></table> </htmlpageheader> <htmlpagefooter name="myfooter"> <div style="border-top: 1px solid #000000; font-size: 9pt; text-align: center; padding-top: 3mm; "> Page {PAGENO} of {nb} </div> </htmlpagefooter> <sethtmlpageheader name="myheader" value="on" show-this-page="1" /> <sethtmlpagefooter name="myfooter" value="on" /> mpdf--> <img style="margin-top: -50px;padding: 15px; border: 2px solid #000; height: 100px;margin: auto !important;width: 100px;background-size: contain;background-repeat: no-repeat;background-position: center;margin-left: 80px !important;" src="images/' . $image . '" class="img-thumbnail"> <table width="100%" style="font-family: serif;" cellpadding="10"><tr> <td width="55%"><br /><br /><span style="font-weight: bold;">Name:</span> ' . $name . '<br /><span style="font-weight: bold;">Father:</span> ' . $father . '<br /><span style="font-weight: bold;">Center:</span> ' . $center . '<br /><span style="font-weight: bold;">Division:</span> ' . $division . '<br /><span style="font-weight: bold;">Class:</span> ' . $class . '</td> <td width="5%"> </td> <td width="40%"><br /><br /><span style="font-weight: bold;">Hall Ticket / Roll No:</span> ' . $rollno . '<br /><span style="font-weight: bold;">Session:</span> ' . $session . '<br /><span style="font-weight: bold;">Stream:</span> ' . $stream . '<br /><span style="font-weight: bold;">Year of Passing:</span> ' . $academic_year . '</td> </tr></table> <br /> <table class="items" width="100%" style="font-size: 9pt; border-collapse: collapse; " cellpadding="8"> <thead> <tr> <td width="15%">Sub Code</td> <td width="40%">Subject Name</td> <td width="10%">Theory</td> <td width="15%">Practicals</td> <td width="20%">Marks Secured</td> </tr> </thead> <tbody> <!-- ITEMS HERE --> '; foreach ($subjects as $subject) { $html .= '<tr>'; $html .= '<td align="center">' . $subject['subcode'] . '</td>'; $html .= '<td align="center">' . $subject['subject_name'] . '</td>'; $html .= '<td>' . $subject['total_marks'] . '</td>'; $html .= '<td class="cost">' . $subject['obtained_marks'] . '</td>'; $html .= '<td class="cost">' . $subject['marksinwords'] . '</td>'; $html .= '</tr>'; } $html .= ' <tr style="border-top: 2px solid #000;"> <td style="border-top: 2px solid #000;" align="center" >Percentage: ' . $percentage . '</td> <td style="border-top: 2px solid #000;" align="center"></td> <td style="border-top: 2px solid #000;">' . $totalmarks . '</td> <td style="border-top: 2px solid #000;" class="cost">' . $obtmarks . '</td> <td style="border-top: 2px solid #000;" class="cost">' . $marksinwords . '</td> </tr> </tbody> </table> </body> </html> '; require_once 'bootstrap.php'; $mpdf = new \Mpdf\Mpdf([ 'margin_left' => 10, 'margin_right' => 10, 'margin_top' => 30, 'margin_bottom' => 25, 'margin_header' => 10, 'margin_footer' => 10 ]); $mpdf->SetTitle("Online Marksheet"); $mpdf->SetDisplayMode('fullpage'); $mpdf->WriteHTML($html); $mpdf->Output(); This is working perfectly fine in XAMPP for me, and is downloading the PDF every time I load the page. But when I hosted these exact same files on cPanel's File Manager - it's only showing me a blank page. No errors. What can I do? I've checked the PHP versions of both my XAMPP (v8.0) and PHP(v7.3) but that doesn't seem to be the issue (unless one of you think it is?) |
map.items is not function how do i slove this? Posted: 16 Jul 2022 03:54 AM PDT |
adding new column assigning other column first value from list Posted: 16 Jul 2022 03:53 AM PDT hello i have got a situation here. got dataset and in several 'price' columns there are two values instead of one. looks like "$1.99 64.78" etc.. data look like this my code looks like no_na['Kaina'] = no_na['price'].str.split(' ').astype('str') no_na this creates new column and adds list of prices. the question is how to add only one element from list to a new column? tried to use pop but got errors well it worked with no_na['Kaina'] = no_na['price'].apply(lambda x: x[0:5]).astype(float) no_na but still i believe there should be a better way, because if price is 111.11 the result would be 111.1 i guess. now looks like this |
sympy:Please tell me about the line.equation() Posted: 16 Jul 2022 03:53 AM PDT sympy.line.equation() Same value and type, but what's the difference?" How can I fix it? What is the difference between z1 and z2? from sympy import * var('x y z1 z2') z1=8*x+6*y+48 print("#z1",z1,type(z1)) z2=Line(Point(-6,0),Point(0,-8)).equation() print("#z2",z2,type(z2)) if type(z1)==type(z2): print("#","type==") else: print("#","type<>") if z1==z2: print("#","==") else: print("#","<>") #z1 8*x + 6*y + 48 <class 'sympy.core.add.Add'> #z2 8*x + 6*y + 48 <class 'sympy.core.add.Add'> # type== # <> I try add .expand().simplify() 30 mins ago from sympy import * var('x y') print("#z1#",solve(8*x+6*y+ 48 ,y)) print("# ", Line(Point(-6,0),Point(0,-8)).equation().expand().simplify() ) print("#z2#",solve(Line(Point(-6,0),Point(0,-8)).equation().expand().simplify(),y)) #z1# [-4*x/3 - 8] # 8*x + 6*y + 48 #z2# [] Thank you. from sympy import * var('x y') print("#z1#",solve(8*x+6*y+ 48 ,y)) print("# ", Line(Point(-6,0),Point(0,-8)).equation() ) print("#z2#",solve(sympify(str(Line(Point(-6,0),Point(0,-8)).equation())),y)) #z1# [-4*x/3 - 8] # 8*x + 6*y + 48 #z2# [-4*x/3 - 8] |
IPython.notebook.kernel.execute in the same cell Posted: 16 Jul 2022 03:53 AM PDT I have a follow up question to Can a Jupyter / IPython notebook take arguments in the URL? There is an assumption here that the HTML object should be the last one in the cell and the print URL is in the next one. Is it possible to get the URL directly without these assumptions? I need it in an app that runs through a package voila. A snippet of code(like below from the other query on stackoverflow) in a single cell would be ideal. *from IPython.display import HTML HTML(''' <script type="text/javascript"> IPython.notebook.kernel.execute("URL = '" + window.location + "'") </script>''') print(URL)* |
Pydantic - Allow missing field Posted: 16 Jul 2022 03:54 AM PDT I have a pydantic model. One of its fields must be supplied by user, however, the second one can be present but it is totally okay if it is missing. In case of missing age , I don't want it to be present on pydantic model instance at all. My Model: from pydantic import BaseModel class Employee(BaseModel): name: str age: Optional[int] Problem: e = Employee(name="Harwey Smith") e.age # Has age parameter equal to None, even if not provided. How do I setup my Employee pydantic model not to have age attribute at all if it is not provided on init? If I would try to access e.nonexistent attribute, AttributeError would be thrown. This is what I want to happen for e.age , if not provided. |
Pycharm matplotlib figure opened but i'm still getting error Posted: 16 Jul 2022 03:54 AM PDT I've created a graph. The keys have become inactive and the unresponsive error continues. The buttons are not active. I installed the latest version, but it still didn't happen I'm getting an error that the graph is not responding even though it occurs. enter image description here import seaborn as sns import matplotlib.pyplot as plt df = sns.load_dataset("titanic") plt.boxplot(df["fare"]) plt.show() |
When clicking on a button inside another button, the functions for both buttons are run Posted: 16 Jul 2022 03:55 AM PDT I have show-button that, when clicked, expands and shows some text and a collapse-button : <button id='show-button'> <p>Test</p> <button id='collapse-button'></button> </button> When show-button is clicked, it expands and shows the paragraph and the collapse button. When the collapse-button is clicked, it collapses back to the original size where it's all hidden. The problem is the following: When I click on the collapse-button , the event listener for click is run and everything collapses. However, for some reason, the event listener of the show-button is also triggered and everything is shown again. A loop. You can show but never collapse it again. How can I make sure that when collapse-button is pressed, show-button isn't also triggered? Thanks |
problems with IDE IJ Community vs IJ Ultimate Posted: 16 Jul 2022 03:53 AM PDT I create a Maven project with IJ Community Edition, and it's work with no errors. After I try to open this project with IJ Ultimate, but my progect(exercises) went to break up in both IDE. Abnormal build process termination: /home/viktoriya/.jdks/adopt-openjdk-1.8.0_292/bin/java -Xmx700m - Djava.awt.headless=true -Djava.endorsed.dirs=\"\" Dexternal.project.config=/home/viktoriya/.cache/JetBrains/IntelliJIdea2021.2/external_bui ld_system/aop.8b786682 -Dcompile.parallel=false -Drebuild.on.dependency.change=true - Djdt.compiler.useSingleThread=true -Daether.connector.resumeDownloads=false - Dio.netty.initialSeedUniquifier=-3134077656729915217 -Dfile.encoding=UTF-8 - Duser.language=it -Duser.country=IT -Didea.paths.selector=IntelliJIdea2021.2 - Didea.home.path=/snap/intellij-idea-ultimate/311 - Didea.config.path=/home/viktoriya/.config/JetBrains/IntelliJIdea2021.2 - Didea.plugins.path=/home/viktoriya/.local/share/JetBrains/IntelliJIdea2021.2 - Djps.log.dir=/home/viktoriya/.cache/JetBrains/IntelliJIdea2021.2/log/build-log - Djps.fallback.jdk.home=/snap/intellij-idea-ultimate/311/jbr - Djps.fallback.jdk.version=11.0.11 -Dio.netty.noUnsafe=true - Djava.io.tmpdir=/home/viktoriya/.cache/JetBrains/IntelliJIdea2021.2/compile- server/aop_fceb3a58/_temp_ -Djps.backward.ref.index.builder=true - Dtmh.instrument.annotations=true -Dtmh.generate.line.numbers=true - Dkotlin.incremental.compilation=true -Dkotlin.incremental.compilation.js=true - Dkotlin.daemon.enabled -Dkotlin.daemon.client.alive.path=\"/tmp/kotlin-idea- 12642686614178805058-is-running\" -classpath /snap/intellij-idea- ultimate/311/plugins/java/lib/jps-launcher.jar:/home/viktoriya/.jdks/adopt-openjdk- 1.8.0_292/lib/tools.jar org.jetbrains.jps.cmdline.Launcher /snap/intellij-idea- ultimate/311/lib/jps-model.jar:/snap/intellij-idea- ultimate/311/plugins/java/lib/maven-resolver-transport-file-1.3.3.jar:/snap/intellij- idea-ultimate/311/lib/forms_rt.jar:/snap/intellij-idea-ultimate/311/lib/jna- platform.jar:/snap/intellij-idea-ultimate/311/plugins/java/lib/jps- builders.jar:/snap/intellij-idea-ultimate/311/plugins/java/lib/jps-builders- 6.jar:/snap/intellij-idea-ultimate/311/lib/kotlin-stdlib-jdk8.jar:/snap/intellij- idea-ultimate/311/lib/slf4j.jar:/snap/intellij-idea-ultimate/311/lib/protobuf-java- 3.15.8.jar:/snap/intellij-idea-ultimate/311/plugins/java/lib/maven-resolver- connector-basic-1.3.3.jar:/snap/intellij-idea- ultimate/311/lib/idea_rt.jar:/snap/intellij-idea-ultimate/311/plugins/java/lib/maven- resolver-transport-http-1.3.3.jar:/snap/intellij-idea- ultimate/311/lib/jna.jar:/snap/intellij-idea- ultimate/311/plugins/java/lib/javac2.jar:/snap/intellij-idea-ultimate/311/lib/3rd- party.jar:/snap/intellij-idea-ultimate/311/plugins/java/lib/jps-javac-extension- 1.jar:/snap/intellij-idea-ultimate/311/lib/util.jar:/snap/intellij-idea- ultimate/311/lib/annotations.jar:/snap/intellij-idea- ultimate/311/plugins/java/lib/aether-dependency-resolver.jar:/snap/intellij-idea- ultimate/311/lib/platform-api.jar:/snap/intellij-idea- ultimate/311/plugins/JavaEE/lib/jasper-v2-rt.jar:/snap/intellij-idea- ultimate/311/plugins/Kotlin/lib/kotlin-reflect.jar:/snap/intellij-idea- ultimate/311/plugins/Kotlin/lib/kotlin-plugin.jar:/snap/intellij-idea- ultimate/311/plugins/ant/lib/ant-jps.jar:/snap/intellij-idea- ultimate/311/plugins/uiDesigner/lib/jps/java-guiForms-jps.jar:/snap/intellij-idea- ultimate/311/plugins/eclipse/lib/eclipse-jps.jar:/snap/intellij-idea- ultimate/311/plugins/eclipse/lib/eclipse-common.jar:/snap/intellij-idea- ultimate/311/plugins/IntelliLang/lib/java-langInjection-jps.jar:/snap/intellij-idea- ultimate/311/plugins/Groovy/lib/groovy-jps.jar:/snap/intellij-idea- ultimate/311/plugins/Groovy/lib/groovy-constants-rt.jar:/snap/intellij-idea- ultimate/311/plugins/maven/lib/maven-jps.jar:/snap/intellij-idea- ultimate/311/plugins/gradle-java/lib/gradle-jps.jar:/snap/intellij-idea- ultimate/311/plugins/devkit/lib/devkit-jps.jar:/snap/intellij-idea- ultimate/311/plugins/javaFX/lib/javaFX-jps.jar:/snap/intellij-idea- ultimate/311/plugins/javaFX/lib/javaFX-common.jar:/snap/intellij-idea- ultimate/311/plugins/JavaEE/lib/javaee-jps.jar:/snap/intellij-idea- ultimate/311/plugins/webSphereIntegration/lib/jps/javaee-appServers-websphere- jps.jar:/snap/intellij-idea-ultimate/311/plugins/weblogicIntegration/lib/jps/javaee- appServers-weblogic-jps.jar:/snap/intellij-idea- ultimate/311/plugins/JPA/lib/jps/javaee-jpa-jps.jar:/snap/intellij-idea- ultimate/311/plugins/Grails/lib/groovy-grails-jps.jar:/snap/intellij-idea- ultimate/311/plugins/Grails/lib/groovy-grails-compilerPatch.jar:/snap/intellij-idea- ultimate/311/plugins/Kotlin/lib/jps/kotlin-jps-plugin.jar:/snap/intellij-idea- ultimate/311/plugins/Kotlin/lib/kotlin-jps-common.jar:/snap/intellij-idea- ultimate/311/plugins/Kotlin/lib/kotlin-common.jar org.jetbrains.jps.cmdline.BuildMain 127.0.0.1 36431 07bedbac-3b45-46ae-985c-23aa3cfc7910 /home/viktoriya/.cache/JetBrains/IntelliJIdea2021.2/compile-server /home/viktoriya/.jdks/adopt-openjdk-1.8.0_292/bin/java: 1: ��ELF: not found /home/viktoriya/.jdks/adopt-openjdk-1.8.0_292/bin/java: 2: ��: not found /home/viktoriya/.jdks/adopt-openjdk-1.8.0_292/bin/java: 3: ��: not found /home/viktoriya/.jdks/adopt-openjdk-1.8.0_292/bin/java: 4: ����: not found /home/viktoriya/.jdks/adopt-openjdk-1.8.0_292/bin/java: 5: ��: not found /home/viktoriya/.jdks/adopt-openjdk-1.8.0_292/bin/java: 6: ��: not found /home/viktoriya/.jdks/adopt-openjdk-1.8.0_292/bin/java: 7: TTT: not found /home/viktoriya/.jdks/adopt-openjdk-1.8.0_292/bin/java: 8: ��: not found /home/viktoriya/.jdks/adopt-openjdk-1.8.0_292/bin/java: 9: ��: not found /home/viktoriya/.jdks/adopt-openjdk-1.8.0_292/bin/java: 10: PP/lib64/ld-linux- x86-64.so.2GNU: not found /home/viktoriya/.jdks/adopt-openjdk-1.8.0_292/bin/java: 16: Syntax error: ")" unexpected` So I try to open it again with IJ Community, but I's was also broked. I create a new one,identical, with the same classes and the same Maven dependecies with IJ Community, I change just the name progect, and it's work. So my question is why IJ Utilmate broke my progect and how may I adjust it. After I create a simple Maven progect with just an System.out.println("hello"); with Ij Ultimate, and I've got the same results like in my firs progect, so was broked with the same message about "Abnormal buiild process terminated". So the problem it's not in my code, but with IJ Ultimate Ide. How may I fix it? Because I prefer work with Ultimate edition. Thank you |
chrome.scripting.executeScript not working in my manifest v3 Chrome Extension Posted: 16 Jul 2022 03:54 AM PDT I have an extension where I call function doScript(window) { chrome.scripting.executeScript( { target: {tabId: window.tabs[0].id}, files: ['myscript.js'], }); } myscript.js simply has alert("Made it") but I get no alert in my tab. If I change the tabId to something random like 123 chrome.scripting.executeScript( { target: {tabId: 123}, files: ['myscript.js'], }); then I get an error "Unchecked runtime.lastError: No tab with id: 123" So it looks like my tabId is right, but for some reason myscript.js is not triggering an alert. If I mess up the script name like this chrome.scripting.executeScript( { target: {tabId: window.tabs[0].id}}, files: ['ttttttttttt.js'], }); I get "runtime.lastError: Could not load file: 'ttttttttttt.js'." I tried looking through the console logs and the only thing I see is this error upon clicking but it looks like a red herring. "Unchecked runtime.lastError: Cannot access contents of url "". Extension manifest must request permission to access this host." https://github.com/GoogleChrome/web-vitals-extension/issues/54 Here is my manifest { "manifest_version": 3, "name": "pokemon bokemon", "description": "", "version": "0.3.0", "action": { "default_popup": "popup.html" }, "icons": { "16": "icon16.png", "32": "icon32.png" }, "permissions": [ "tabs", "storage", "scripting", "activeTab", "cookies" ], "host_permissions": [ "*://*/*", "<all_urls>" ], "options_page": "options.html" } EDIT: Apparently it's a bug in chrome/manifest v3. Opened a bug here: https://bugs.chromium.org/p/chromium/issues/detail?id=1191971 |
Parallel JavaScript Code Posted: 16 Jul 2022 03:53 AM PDT Is it possible to run JavaScript code in parallel in the browser? I'm willing to sacrifice some browser support (IE, Opera, anything else) to gain some edge here. |
No comments:
Post a Comment