Skip to main content

Posts

Showing posts from December, 2021

Laravel Eloquent Relationship Join

carts:- id product_name price ratings:- id product_id user_id I have these two table. And i have defined a relationship in product model for geting rating of particular product. and output of the code is this:- "data": [ { "id": 4200, "name": "Anti gravity Beer Cake", "modal": "", "price": 1800, "discount": 0, "quantity": 20, "discription": "Good Quality Product!", "p_status": "active", "m_id": 664, "product_link": "anti-gravity-beer-cake--6040c2b317894", "product_picture": " ", "weight": 0, "weight_type": "Kilogram", "rating": { "id": 4,

How to deal with SettingWithCopyWarning

hi i had this error and don't know what should i do i don't know what should i be replacing .loc whith is there a way to ignore this warning or something eslse C:\Users\LO'AY\AppData\Local\Temp/ipykernel_9408/708385938.py:14: SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame. Try using .loc[row_indexer,col_indexer] = value instead See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy X[i]=ED C:\Users\LO'AY\AppData\Local\Temp/ipykernel_9408/708385938.py:26: SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame. Try using .loc[row_indexer,col_indexer] = value instead See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy X["Cluster"]=C the the code that generate the error message diff = 1 j=0 while(diff!=0):

Add a class to every children of a slot

I'm trying to set up a component with a slot, that when rendered adds a class to every children of that slot. In a very simplified manner: <template> <div> <slot name="footerItems"></slot> </div> </template> How would I go about this? My current solution is to add the class to the elements in an onBeforeUpdate hook: <script setup lang="ts"> import { useSlots, onMounted, onBeforeUpdate } from 'vue'; onBeforeUpdate(() => addClassToFooterItems()); onMounted(() => addClassToFooterItems()); function addClassToFooterItems() { const slots = useSlots(); if (slots && slots.footerItems) { for (const item of slots.footerItems()) { item.el?.classList.add("card-footer-item"); } } } </script> However, the elements lose the styling whenever it's rerendered (using npm run serve ) and also jest tests give me a warning: [Vue warn]: Slot "footerItems" in

Best way to minimise/streamline/use synergies of code to populate several webpages with different content but same layout? [closed]

sorry for the non-specific title but my question relates to coding strategy and best practice. I'm new to coding and I'm working on a website on a local server. I'm learning a lot of new coding languages (html, css, php, jquery, javascript, ajax and mysql) as I need them but I'm conscious that I'm a complate amateur when it comes to the best way to apply them. Background My website has header and footer pages that include all the menu navigation, login system, css/js link type of things. Every other webpage leverages the header and footer pages, therefore the other webpages only contain content (I'll call these pages "article webpages" for clarity below). The layout of all the article webpages is the same but headings, images, colour schemes and text will vary from one article webpage to another. Lastly, I also have one other over-arching webpage that includes buttons and each button sends the user to an individual article webpage when clicked.

Scraping a javascript response through beautifulsoup, possible?

The server returns the below response, it is apparantly javascript contents and I wanted to scrape it but I am unable to do it. Element.update("to_users2", "\n\n\n<div class="label-field-pair">\n <div class="label-field-pair11">\n <label for="student_grade">Select member\n <div class ="scrolable" >\n <div class="scroll-inside">\n <div class="hover"><a href="#" class="all" onClick="add_all_recipient('2,4')">Select all Add \n\n \n \n \n <div class="hover"><a href="#" before="Element.show('loader')" class="individual" onClick="add_recipient(2)" success="Element.hide('loader')">TestUserOne Add \n\n \n \n \n <div class="hover"><a href="#" before="Element.show('loader')" class="individual" onClic

there is other way to get properties of cell in JS then event.target.nodeName.toLowerCase()? [closed]

so I have this problem that I want to compare 2 cells of Chess table that I did. When I click on cell, I'm getting in console.log only td, and the comparison I'm using I have the cell itself (I added photo for example) so there is other way to get the cell properties when click on it then the event.target.nodeName.toLowerCase() ? here in this function im sending cell and try to compare it to event.target.nodeName.toLowerCase() the problem is, that in event.target.nodeName.toLowerCase() i have "td" and not the "cell" like shonw in the right side of the photo, so i want to know if there is other opetion whel im clicking on some cell of grid(chess table) that i can get the cell itself to be compared. const handler= Click.bind(null, cell); table.addEventListener("click", handler); function Click(cell, event) { if (event.target.nodeName.toLowerCase() === 'td' ) { event.target.style.backgroundColor = &

Ajax json doesnt show any instances

that even if i connected json data to ajax, it doesnt show me any results. def get_json_categories(request): query_get = request.GET if query_get: query_get = query_get['q'] categories = EcommerceProductCategory.objects.filter(name__contains=query_get).order_by('name') else: categories = EcommerceProductCategory.objects.order_by('name') data = {} data['results'] = [] for category in categories: data_to_return = {} data_to_return['id'] = category.id data_to_return['name'] = category.name data['results'].append(data_to_return) return JsonResponse(data) And i urled that to ecommerce/get_json_categories and in the Django html <div class="mt-2"> <hr> <div class="form-group"> <select class="form-control w-30" name="category_select" id=&q

Issue while trying to receive message notifications from Slack

About I am trying to receive message posted on my server as soon as user post message the message in group or channel or direct in slack. App Status Code in the verified file where challenge was posted. header('Content-type: application/json'); $myfile = fopen("test.txt", "w") or die("Unable to open file!"); $data = json_decode(file_get_contents('php://input'), true); fwrite($myfile, $data["challenge"]); fclose($myfile); $json = '{"challenge":' . $data["challenge"] . '}'; echo json_encode(["challenge" => $json]); Question Now that the above url has been verified successfully, I am still not able to receive the posted messages. I was expecting messages posted at same url which was used to verify challenge parameter. Is that correct? Am I missing anything retrieving the messages posted on my server? source https://stackoverflow.com/questions/70535363/issue-while-trying-to-r

Capturing first frame takes up to 1 second

I am running a simple python program using OpenCV on a Raspberry Pi 4. The problem is that when taking the first frame it takes up to 1 second, which seems very strange to me. The forms that I used were the following and in both, I had the same result. camera = cv2.VideoCapture(0) _, img = camera.read() The other option is: camera = cv2.VideoCapture(0, cv2.CAP_V4L2) _, img = camera.read() I am using a USB camera. source https://stackoverflow.com/questions/70535763/capturing-first-frame-takes-up-to-1-second

React-Redux most recently POSTed object is always undefined until I refresh

So I'm working with react and redux to make a simple blog app where you fill out a form and onSubmit that data is added to a grid of other posts. However, when I use the useSelector() method to gather the state, the most recently POST'd object is always undefined, even though it properly makes it through redux. Here's the flow: From Form: const handleSubmit = (e) => { e.preventDefault() console.log("FORM DATA:") console.log(postData); dispatch(createPost(postData)); } Here's the action dispatched: export const createPost = (post) => async (dispatch) => { try { const data = await api.createPost(post); console.log("ACTION DATA:"); console.log(data.data); dispatch({ type: "CREATE", payload: data.data}); } catch (error) { console.log(error.message); } } Here is the reducer associated with the action, with the case being 'CREA

Converting Time with timezone PHP

I'd like to convert value/date/time that I got from callback raw value that I got is like this $value='2021-01-20T19:03:52.355+0300'; I need to convert it into like this $value='20-01-2021 23.03.52,355000 +07:00'; what I've done some substr and concat but unfortunately it ends up with string and my db datatype format is timestamp and i can't insert the value to db read some about DateTime::createFromFormat and I can convert the time format but still no clue for converting to another timezone source https://stackoverflow.com/questions/70529737/converting-time-with-timezone-php

Formula for rotating a 4 point (rectangle) polygon?

I am using Zelle graphics, but I suppose it is the same for any graphics program. From what I can tell, Zelle graphics does not have a "setheading" or "rotate" command for the rectangle (this is probably because the bounding box is created with two points). In turtle graphics it is easy with setheading(). So presently, I have a class that creates a polygon. I have a draw method and a rotate method. In the rotate method I am changing the Point(x1,y1) for each corner in a FOR LOOP. I broke out some graph paper to get the initial first few points to rotate, there is complex math I believe that would make this more palatable. Presently this is my init method with these attributes, but I am sure there is a better way: class create(): def __init__(self, p1x,p1y,p2x,p2y,p3x,p3y,p4x,p4y): self.p1x = p1x self.p2x = p2x self.p3x = p3x self.p4x = p4x self.p1y = p1y self.p2y = p2y self.p3y = p3y self.p4y = p4y NOTE : this is not the entiret

I have a small problem with engine.runAndWait()

I have a program that's detects and recognizes faces, but thats not the point , while im trying to include "voice follower". engine = pyttsx3.init() engine.say("I will speak this text") engine.runAndWait() It is actually does saying and then after a few seconds the whole program is just crashes. Could you please help me? Thank you in advance! source https://stackoverflow.com/questions/70524149/i-have-a-small-problem-with-engine-runandwait

Method call with no-op proxy

I thought javascript proxy can handle method calls, but this simple script fail to do so. let s = new String("12345") let p = new Proxy(s, {}) let x = p.startsWith("1") // type error here Gives me, TypeError: String.prototype.toString requires that 'this' be a String. I think startsWith method were called with this=Proxy. How to properly redirect proxy's target to 'this' ? Via Active questions tagged javascript - Stack Overflow https://ift.tt/2FdjaAW

Force browser to display PDF file instead of download

I found some solution for my issue by googling but none of them worked for me. I want to show a PDF file in a webpage but browser makes user to download it! How can I solve this? My code is below. <?php session_start(); $name = $_SESSION['src']; $file= 'usr/'.$name.'/out.pdf' ?> <!DOCTYPE html> <html> <page size="A4"><embed src=<?php echo $file?> type="application/pdf" width="800px" height="1100px" /></page> </html> source https://stackoverflow.com/questions/70524443/force-browser-to-display-pdf-file-instead-of-download

ImportError: cannot import name 'force_text' from 'django.utils.encoding' (/usr/local/lib/python3.9/site-packages/django/utils/encoding.py)

I get the error below when I add 'graphene_django' inside INSTALLED_APPS in the settings.py After running python3 manage.py runserver graphene_django is installed successfully using pip install django graphene_django This is full error that i get Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "/usr/local/Cellar/python@3.9/3.9.9/Frameworks/Python.framework/Versions/3.9/lib/python3.9/threading.py", line 973, in _bootstrap_inner self.run() File "/usr/local/Cellar/python@3.9/3.9.9/Frameworks/Python.framework/Versions/3.9/lib/python3.9/threading.py", line 910, in run self._target(*self._args, **self._kwargs) File "/usr/local/lib/python3.9/site-packages/django/utils/autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "/usr/local/lib/python3.9/site-packages/django/core/management/commands/runserver.py", line 115, in inner_run auto

Function goes to recursive mode on submit

I am getting username and password through queryparams and showing that data in input field of php website and using javascript to show dashboard instead of login page. But website goes to recursive mode when directly calling login button function, for that i am using alert to stop for 2 seconds. Is it possible to directly get that data and show dashboard. I am new to javascript, can anyone help me out yrr. Thank you! echo ' Username ---> ' .$_GET['xuser_name']; echo ' password ---> ' .$_GET['xuser_password']; $str .= getFormRowTextInput('xuser_name', $l['w_username'], $l['h_login_name'], '', $username, '', 255, false, false, false, ''); $str .= getFormRowTextInput('xuser_password', $l['w_password'], $l['h_password'], '', $password, '', 255, false, false, true, ''); $str .= '<input type="submit" name="login"

How to access json file in jupyter?

I want to access the json file and convert to it dataframe but show's invalid argument. import json import pandas as pd a='https://power.larc.nasa.gov/api/temporal/daily/point?parameters=WS10M_MAX&community=RE&longitude=85.1500&latitude=25.6100&start=20210101&end=20210331&format=JSON' data = json.load(open(a)) df = pd.DataFrame(data) Error is- OSError: [Errno 22] Invalid argument: 'https://power.larc.nasa.gov/api/temporal/daily/point?parameters=WS10M_MAX&community=RE&longitude=85.1500&latitude=25.6100&start=20210101&end=20210331&format=JSON' source https://stackoverflow.com/questions/70511747/how-to-access-json-file-in-jupyter

HTML/JS Kanban Board doesn't let me drop newly created tasks into other columns

I am creating a Kanban Board in HTML/JS/CSS and am close to finishing my MVP here. Everything is working as expected, except for one thing. When I create a new task, I am able to drag it (seemingly) but not DROP it into any other columns. The sample tasks I have do not have this problem and I am ripping my hair out trying to figure out what the issue is. When I attempt to drag and drop newly created tasks into other columns, I get this error: TypeError: Failed to execute 'appendChild' on 'Node': parameter 1 is not of type 'Node'. at drop (/script.js:31:13) at HTMLDivElement.ondrop (/:45:112) I am using basic drag and drop API stuff for HTML and JS and literally only need to make this work in order to finish my MVP. Any help is appreciated. NOTE: The line numbers in the above error change based on what column I try to drop the new task into but the error itself stays the same. Here is my code: index.html: <!DOCTYPE html> <html> <head

php handling character set

I have an issue with encoding json to sent to datatable.net. I received DataTables warning: "table id=varietyTable - Invalid JSON response. For more information about this error, please see http://datatables.net/tn/1." Checked the development tool. I found out that there is no response. There apparently there is something wrong with json_encode. I look at the record. it seems to have problem handing ascii code 160. The same code running on my local machine (running xampp). There is no problem. I tried to echo the page. I see unreadable character on the remote server but no local host. output on remote server: Alma�� output on local host: Alma (note that there are spaces behind the word Alma). The php code are identical. I am just wondering whether the local php setting is different so that the special characters can handle properly. Thanks. here are some code from php code that receiving the records and return as Json. The code is rather long. I am posting the parts the

How to handle file delete after returning it has response in Django rest framework

I am performing the below steps in my DRF code. Capturing the file name in a request Searching the given file name in a SFTP server. If the file is available in SFTP server,downloading it to local path in a folder called "downloads" Returning the file as response with FileResponse I need to delete the file which i downloaded from SFTP or simply delete everything in downloads folder. What is the best approach to achieve this? How about an async celery task before returning FileResponse? source https://stackoverflow.com/questions/70510878/how-to-handle-file-delete-after-returning-it-has-response-in-django-rest-framewo

Track the actions that led to a multi-level drop down menu to open

Goal: Track all the actions required to reach a certain level in a multi-level dropdown. Example: A multi-level dropdown like https://s.bootsnipp.com/iframe/xr4GW which can be opened by hovering on it. Once a menu item is clicked on the dropdown, how can one figure out what hover actions led to that part of the menu being opened ? In the above bootsnip demo, if the first link in level 3 is clicked on, I want to be able to say that: 3rd link in level 1 --> 2nd link in level 2, resulted in being able to ----> click the 1st link in level 3 Current direction: Currently I'm using mouseover and click events to see if I can some-how co-relate all the events together. But no luck as of yet. Thank you in advance :) Via Active questions tagged javascript - Stack Overflow https://ift.tt/2FdjaAW

Date.today is not a function after J-Query 3.x Upgrade

After recently updating my local J-Query library from 1.9.1 to 3.6.0 I have noticed some strange issues. I did not see anything online for this, and most of these functions are standard JavaScript functions I believe, and not J-Query. I am seeing that Date() objects are undefined. Also the following errors with Date and Array objects are happening. If I revert the code to 1.9.1 there is no issue. *Also this is a Node.js project, I dont know if that matters. TypeError: Date.today is not a function at Object. (main.js:8:126614) Cannot read properties of undefined (reading 'includes') TypeError: i.add is not a function Sample Code var today = Date.today(); UPDATE: It looks like the code that is not working is coming from this node.js package. https://github.com/datejs/Datejs When I change the code to var today = new Date(); var numberOfDays = today.add(5).days(); Then there is a problem with the add method, see the error listed above. // Type definitions for Da

Braintree PHP How To Get Nonce Without DropIn for Vaulting

For our use case, we have an existing form that captures the customer's credit card information. To smooth out the transition from one payment processor to the next since we're not sure when that will happen, we would like to vault the payment method in Braintree without charging the card but keep our existing form. I see how to vault the nonce that we receive from the Drop-In UI, and I was able to find an answer on SO that described how to pass the payment information directly to Braintree and charging it, however, I have had no luck in finding a way to just pass the card information to braintree for the purposes of vaulting the payment method (with or without the intermediate step of receiving a nonce). source https://stackoverflow.com/questions/70511004/braintree-php-how-to-get-nonce-without-dropin-for-vaulting

How do I pass the values of my checkboxes with PHP to mySQL database?

Now the value in my database is just "Array". Because, well it is an array. It can see whether I checked at least one thing, or no things at all. If I don't check any checkboxes it returns nothing, if I check at least one thing it returns "Array". I haven't worked with PHP before, and we didn't get any classes about this, but after a few days of trying I couldn't figure it out. <?php // Show all errors (for educational purposes) ini_set('error_reporting', E_ALL); ini_set('display_errors', 0); // Constanten (connectie-instellingen databank) define('DB_HOST', ''); define('DB_USER', ''); define('DB_PASS', ''); define('DB_NAME', ''); date_default_timezone_set('Europe/Brussels'); // Verbinding maken met de databank try { $db = new PDO('mysql:host=' . DB_HOST . ';dbname=' . DB_NAME . ';charset=utf8mb4', DB_USER, DB_PASS); $db->

Select a record when the timestamp has passed by a certain amount of time MYSQL/PHP

I'm trying to select sessions that are younger than 6 hours old with this query like so: "SELECT * FROM sessions WHERE members=1 AND ipRCreator != '$usn' AND tStamp < DATE_SUB(CURRENT_TIMESTAMP, INTERVAL 6 HOURS"; The problem is that the query condition is always false and never manages to find the sessions even when a record actually has a timeStamp of a few seconds ago. obviously I am very sure that the problem is in the condition of the: tStamp < DATE_SUB (CURRENT_TIMESTAMP, INTERVAL 6 HOURS) I insert the data records in the table like this: $timestamp = date("Y-m-d H:i:s"); $mysqli->query("INSERT INTO sessions (sessionId, members, ipRCreator, tStamp) VALUES('$sId', 1, '$usn', '$timestamp');") ; I thought the problem was the formatting of the date but I don't think since the insert works well and the date is correctly inserted in the DB. This is the sql structure of the table: `sessionId` tex

getting internal error 500 while using google signup method [duplicate]

my _config.php <?php session_start(); require_once 'vendor/autoload.php'; $google_client = new Google_Client(); $google_client->setClientId('16194638744-qm9esnsemf65s3ghch246sprp7jimrcp.apps.googleusercontent.com'); $google_client->setClientSecret('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'); $google_client->setRedirectUri('http://localhost/houzz/partials/g-callback.php'); $google_client->addScope('email'); $google_client->addScope('profile'); ?> my g-callback.php <?php require_once "_config.php"; if(isset($_GET['code'])){ $token = $google_client->fetchAccessTokenWithAuthCode($_GET['code']); $_SESSION['access_token'] = $token; }else if(isset($_SESSION['access_token'])){ $google_client->setAccessToken($_SESSION['access_token']); }else{ header('Location: localhost/houzz/partials/_otp.php'); exit(); } $Oauth = new Google_Service_

sequilize Referencing column 'partner_id' and referenced column 'id' in foreign key constraint 'partnerserviceareas_ibfk_1' are incompatible

This is my partner model const { Sequelize, DataTypes } = require('sequelize'); const sequelize = require('../connection'); const PartnerInfo = sequelize.define( 'partnerinfo', { id: { type: DataTypes.UUID, allowNull: false, defaultValue: Sequelize.UUIDV4, primaryKey: true, }, name: { type: DataTypes.STRING, allowNull: false, }, email: { type: DataTypes.STRING, allowNull: false, unique: true, }, phone: { type: DataTypes.STRING, allowNull: false, unique: true, }, loginSecret: { type: DataTypes.STRING, allowNull: true, }, gender: { type: DataTypes.INTEGER, defaultValue: 0, // 0:Female 1:male }, dob: { type: DataTypes.STRING, allowNull: true, }, image: { type: DataTypes.STRING, allowNull: true, }, type: { type: DataTypes.INTEGER, defaultValue: 0, // 0:Value 1:Eli

How do I ckeck if the column contains the $_POST of the form?

I have an issue with the following code : $recherche = $_POST['recherche']; $recherche = '%'.$recherche.'%'; $selecPrepare = self::$bdd->prepare("SELECT culmn where column LIKE '%{$recherche}%'"); $tab = array($_POST['recherche']); $selecPrepare->execute($tab); return $tab; I'm sorry if someone asks the same question before, let me know if you find something about it. Thanks. source https://stackoverflow.com/questions/70499683/how-do-i-ckeck-if-the-column-contains-the-post-of-the-form

Find all players with the longest winning streak

I am trying to crack the problem of finding the player(s) with the longest streak of winning using Python's 3.2. I am only able to work out an unscalable solution, but I could not come up with a better one yet. Can anyone please help me with a better solution? Also, I am curious how to adapt such solution to output the player(s) with the longest winning streak per month or year? Below is the sample dataframe players_results Player_id Match_Date Match_Result 401 2021-05-04 00:00:00 W 401 2021-05-09 00:00:00 L 401 2021-05-16 00:00:00 W 401 2021-05-18 00:00:00 W 401 2021-05-22 00:00:00 L 401 2021-06-15 00:00:00 L 401 2021-06-16 00:00:00 W 401 2021-06-18 00:00:00 W 402 2021-05-14 00:00:00 L 402 2021-05-23 00:00:00 L 402 2021-05-24 00:00:00 W 402 2021-06-01 00:00:00 W 402 2021-06-02 00:00:00 W 402

How to make node to ignore json file of the same name as a package?

With the following folder structure: mypackage/ index.js package.json mypackage.json When I run node mypackage , node quits without running the program, because of mypackage.json . If I rename it to mypackage.jsonx , then the program executes as expected. I really want this file to be named mypackage.json , and I want to run program with a package name without specifying path to index.js , because I want to use an advantage of exports and different entrypoints. I've tried to specify node ./mypackage and node ./mypackage/ and node mypackage/ - it still "runs" the json. Via Active questions tagged javascript - Stack Overflow https://ift.tt/2FdjaAW

How to process insane date inputs with php

I have a code in php for processing the personal details of a person. I need code to handle the date input such that when the user inputs a year like 1900 and below then the program outputs That is impossible . I have successfully handled how the program should respond if the date input is in the future . The program takes date input from the user in the European Date Format for example 21-10-1990 , Am having a hard time processing this because the php in-built function time() returns a unix timestamp measured since January 1st 1970 . Is there a way I can circumvent this to achieve detection of years startimg from 1900 and below without applying a conditional structure to the year directly? Code <?php class User{ //initialize the user properties public string $name=""; public string $dob=""; public string $national_id=""; public string $tel=""; public string $email=""; public function User($user_nam

Load raw JS file from GitHub [duplicate]

I'm trying to load an external js file from my github repo here: <html> <body> <h1>The script src attribute</h1> <script type="text/javascript" src="http://raw.githubusercontent.com/segevngr/gls-assignment/main/player.js" ></script> </body> </html> The GitHub JS file: window.myFunc = function myFunc() { console.log("helooo") } When opening the HTML file im getting the following warning in console: Cross-Origin Read Blocking (CORB) blocked cross-origin response https://raw.githubusercontent.com/segevngr/gls-assignment/main/player.js with MIME type text/plain. See https://www.chromestatus.com/feature/5629709824032768 for more details. And when running myFunc() in devTools console i get myFunc not defined error. Any ideas? Via Active questions tagged javascript - Stack Overflow https://ift.tt/2FdjaAW

Converting JS API request to Powershell

I'm trying to convert some JS code to powershell but getting to a dead end with creating API request. i'm attaching the only part I really can't figure out var ip = "127.0.0.1"; var apiSession = { hostname: ip, port: 443, path: '/api/v1/sessions', method: 'POST', headers: { 'Content-Type': 'application/json charset=utf-8', 'Date': dateFormat(new Date(),"UTC:dddd, dd-mmmm-yy HH:MM:ss Z"), } }; function createSession() { var jsonSession = '{"username":"user","password":"pass"}' apiSession.headers['Content-MD5'] = crypto.createHash('md5').update(jsonSession).digest("base64"); var req = https.request(apiSession, function(res) { res.on('data', function (body) { var jsonContent = JSON.parse(body); if (jsonContent.hasOwnProperty('id') && jsonContent.hasOwnProperty(

How can i convert the PHP string into an integer, but php string is fetched from javascript written in the same page?

<!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>if else in php</title> </head> <body> <script> var a = 123; //to send the prompt value to php, reference taken from stack overflow </script> <?php $a = "<script>document.writeln(a)</script>"; echo $a; ?> </body> </html> in the code above, i fetched the value of javascript variable 'a' in PHP i successfully get it in the variable $a and i tried to print it then also it got printed successfully. As $a would be containing number '123' in string i tried to convert it into an integer using intval() function but, it always shows me value of $a as 0 when i

Check if list is sublist of another list and the elements are in the same order

#sub list test 1 a = [1,1,2] b = [0, 1,1,1,2,1] #sub list test 2 c = [4,5] d = [2,3,4,5,6] if all(i in a for i in b): print("Yes I have all the elements but not sure about their order :( ") I have tried all() or using counter() from collections module. I can't seem to figure it out how to check their order too. source https://stackoverflow.com/questions/70488936/check-if-list-is-sublist-of-another-list-and-the-elements-are-in-the-same-order

how to have different anchor tag in the same for loop

** **``` ``` In this code for loop helping to display 6 typer of excercises on my html page. I want to add anchor tags for user so that if the user click on the singing image he get redirected to singing excercise page and same for other excercises. source https://stackoverflow.com/questions/70489142/how-to-have-different-anchor-tag-in-the-same-for-loop

How do I fix a HTTP Error 400: Bad Request in python3?

I am trying to access checkpoint firewall by using it's API but for some reason I am getting HTTP Error 400: Bad Request, I have never had this before. Any ideas? Here is my code: import json import ssl import urllib.request, urllib.parse, urllib.error import urllib.request, urllib.error, urllib.parse import requests from requests.packages.urllib3.exceptions import InsecureRequestWarning requests.packages.urllib3.disable_warnings(InsecureRequestWarning) sslctx = ssl.create_default_context() sslctx.check_hostname = False sslctx.verify_mode = ssl.CERT_NONE def checkpoint_api_call(cp_ip, port, command, json_payload, sid): apiurl = 'https://' + cp_ip + '/web_api/' + command req = urllib.request.Request(apiurl) if sid == '': req.add_header('Content-Type', 'application/json') else: req.add_header('Content-Type', 'application/json') req.add_header('X-chkp-sid', sid) try: d

Python - IF statement inside a for loop checking on a Json File

Here is my code, I'm trying to scan user's input against Json file that contains a wordlist of negative words in order to get the sum of negative words in a user's input. Note: I take the user input in a list. current Output: No output that relates to the code below is printed. def SumOfNegWords(wordsInTweet): f = open ('wordList.json') wordList = json.load(f) NegAmount = 0 for words in wordsInTweet: #for words in the input if wordsInTweet in wordList['negative']: NegAmount += 1 print("The Sum of Negative Words =", NegAmount) else: print("No negative words found") source https://stackoverflow.com/questions/70488967/python-if-statement-inside-a-for-loop-checking-on-a-json-file

Python Pandas Error trying to drop the first column

I'm trying to drop the first column of a data frame, when I run X.columns.tolist() I get this: ['colors', 'num_critic_for_reviews', 'duration', 'director_facebook_likes', 'actor_3_facebook_likes'] so, I want to drop 'colors', but when I run X = X.drop('colors', index=1) I get: KeyError: "['colors'] not found in axis" I tried with the column index and also with the column label, but keep getting the same error. The funny thing is if I tried to access and use the column colors it works, but again if I try to drop it, get the Not found in the axis error. source https://stackoverflow.com/questions/70488183/python-pandas-error-trying-to-drop-the-first-column

Show/hide button based on if condition React

I have a button called download, it is a component. The functionality is written in a container. I want the button to be hidden as default, unless the "(i === number)" condition is true in the download function. However, it is tricky, since this condition will only be validated when I click "download". I am not sure how do I validate this logic beforehand to determine if the button needs to be displayed or not. Can you please help? What would be the most convenient way in this case My code basically looks like this - container: download = async () => { const data = await this.props.client .query({ query: numberQuery, fetchPolicy: "no-cache", }) // retrive data from number qeury .... const contentData = data.data.content; // retrieve and format numbers const numbers = this.getNumbers(contentData); // call get number and get the individual number here const number = await this.getNumber(); numbers.forEach((i) =

PHP Echo with html inside, not working on mobile browser

Anyone know why this code not working? if (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH'] == "appname") { echo 'webview'; }else{ echo '<style>header {display:none !important;}</style>'; } This part only work if used PC browser, but not if used the mobile browser: echo '<style>header {display:none !important;}</style>'; source https://stackoverflow.com/questions/70482237/php-echo-with-html-inside-not-working-on-mobile-browser

Add value for submit of a form [closed]

Every time someone submits my form I want to add 1 to a value (MySQL). Then I want to include the number of submission in my PDF. Like: submissions: 002 ---> submission of form ---> adding 1 to the value---> submissions: 003 ---> print the number of submissions on the pdf. <script> // Function to GeneratePdf function GeneratePdf() { var element = document.getElementById('message'); var element = document.getElementById('name'); html2pdf(element); } </script> source https://stackoverflow.com/questions/70473157/add-value-for-submit-of-a-form

How to properly format a JSON array | PHP

Essentially I have the following array with various values that are being passed through a function. The output of each needs to then be assembled into a JSON Array that looks like the following: "response": { "firstvalue": 4, "secondvalue": 1, "thirdvalue": "String Response 1", "fourthvalue": "String Response 2" } Code So Far: <?php header('Content-Type: application/json'); $arrayvalues = ["34jkw9k2k9w", "k4otk320el01oeoo20", "30f0w2l020wk3pld==", "3c2x3123m4k43=="]; foreach($arrayvalues as $item) { $decrypted = myFunction($item, $action = 'decrypt'); $response["firstvalue"] = $decrypted; $response["secondvalue"] = $decrypted; $response["thirdvalue"] = $decrypted; echo json_encode($response); } ?> How can

How to execute while loop inside single quote string in php

I am a PHP beginner and working on a simple project for learning purpose and at this point am trying to execute a while loop inside another while loop. But the second loop is inside a single quote string. The outputs of both loops are stored in a normal html/bootstrap table cells. At first I was able to get the output of the first loop but the problem came in when I added the second loop inside the string. I have already researched about using quotations in PHP but I still can't figure out the problem. Below is the code. Someone help please. $output .='<div class="table-responsive"> <table class="table table-bordered"><form>'; while($row = $result->fetch_assoc()){ $output .=' <tr> <td width="30%"><label>Price</label></td> <td> <div class="form-group"> <input type="text" class="form-control" placeholder