Skip to main content

Posts

Showing posts from November, 2021

Two ways to automate php scripts, which is more resource efficient? [closed]

I need to update several userdata regularly within a project. Assuming I have 50 users, which way is more resource efficient? A separate script runs every hour for each user Or There are 5 scripts running in parallel every hour, each of which processes 10 users one after the other. ? Thanks source https://stackoverflow.com/questions/70174216/two-ways-to-automate-php-scripts-which-is-more-resource-efficient

Jupiter saves an empty photo, although it shows it before. How to fix that?

I'm reading and output the picture as a plot: import numpy as np import os import matplotlib.pyplot as plt import matplotlib.ticker as tkr fig, ax = plt.subplots() path = 'photo.jpg' im = plt.imread(path) ax.imshow(im) Output After I want to save it and check(see) the image before saving, but my code generate empty image:( plt.axis("off") plt.gca().xaxis.set_major_locator(tkr.NullLocator()) plt.gca().yaxis.set_major_locator(tkr.NullLocator()) filename = os.path.basename(path).split(".")[0] output_path = os.path.join("test", filename+".png").replace("/", "") plt.savefig(output_path, bbox_inches="tight", pad_inches=0.0) plt.show() plt.close() Output source https://stackoverflow.com/questions/70106331/jupiter-saves-an-empty-photo-although-it-shows-it-before-how-to-fix-that

How to reorder rows in pandas dataframe by factor level in python?

I've created a small dataset comparing coffee drink prices per cup size. When I pivot my dataset the output automatically reorders the index (the 'Size' column) alphabetically. Is there a way to assign the different sizes a numerical level (e.g. small = 0, medium = 1, large = 2) and reorder the rows this way instead? I'm know this can be done in R using the forcats library (using fct_relevel for example), but I'm not aware of how to do this in python. I would prefer to keep the solution to using numpy and pandas. data = {'Item': np.repeat(['Latte', 'Americano', 'Cappuccino'], 3), 'Size': ['Small', 'Medium', 'Large']*3, 'Price': [2.25, 2.60, 2.85, 1.95, 2.25, 2.45, 2.65, 2.95, 3.25] } df = pd.DataFrame(data, columns = ['Item', 'Size', 'Price']) df = pd.pivot_table(df, index = ['Size'], columns = 'Item') df # Price # Item...

Calculating end-time from user given start-time and minutes in Python

I am trying to calculate and store an end-time (formatted as hh:mm:ss) in my database given a user input start-time (formatted as hh:mm) that I add 'x' minutes to. What tools does Python offer to help with this? EDIT: Sorry I hastily posted this question. Allow me to add more specifics! I need to parse an input time given by the user. I use Flask WTForms to have the user input a start time in the format "hh:mm" I then want to take that form data, add 'x' minutes to it, and store it in my database as a TIME field, which is formatted as "hh:mm:ss". source https://stackoverflow.com/questions/70174736/calculating-end-time-from-user-given-start-time-and-minutes-in-python

Pyspark action df.show() returns Java error

I was setting up my Spark development via Anaconda package on my Windows10 desktop. I used to have this set up earlier in the same machine working fine..was doing some cleanup and installing fresh again...but I am now getting issues when I invoke spark to show the data. Initializing, loading data to a data frame, importing libraries are all fine...until I call the action show ....something to do with my environment setting, what am I doing wrong? Environment: spark-3.1.2-bin-hadoop2.7 (SPARK_HOME & HADOOP_HOME) jdk1.8.0_281 (JAVA_HOME) Anaconda Spyder IDE winutils (for hadoop 2.7.7) Python 3.9.7 (default, Sep 16 2021, 16:59:28) [MSC v.1916 64 bit (AMD64)] Type "copyright", "credits" or "license" for more information. IPython 7.29.0 -- An enhanced Interactive Python. import pyspark from pyspark.sql import SparkSession from pyspark.sql import Row from pyspark.sql.types import StringType, StructType, StructField from pyspark.sql import ...

How to do this task? [closed]

main.py (compulsory file) contains main loop where the app prints all selectable options for user (e.g main menu and possible submenus) after showing options to select main loop waits user input (use your own input functions) according selections calls your own input functions for asking user to enter strings (file names etc) and/or numbers when all necessary info has been asked from user, processes and shows the results. inputs.py contains tool functions like user input functions including data validations function who asks user to input integer between range, should take a prompt and list of possible selections (or min, max). And - of course - validate and return integer function who asks user to input string, should take a prompt and list of possible selections. And - of course - validate and return selected string contains tool functions for reading and showing file (excel, csv, json) data One of the functions is that who asks the file path and returns it. Also the function should ...

Formatting table in a dataframe Pandas BeautifulSoup

I would format tables from a website like a dataframe with rows and columns. In this example the url is https://www.soccerstats.com/pmatch.asp?league=england&stats=418-17-15-2022 but is the same for other links stats of matches from https://www.soccerstats.com . Code headers = {'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.212 Safari/537.36'} s = requests.Session() s.headers.update(headers) response = s.get(url, headers=headers) soup = BeautifulSoup(response.text, 'html.parser') ##FIND THE RELATIVE TABLE FROM THE WEBSITE for ta in soup.findAll('table'): for s in ta.findPreviousSiblings(): if s.name == 'h2': if s.text == 'Goal statistics': goal_stats_table = ta else: break Expected Output should be a dataframe, same for all the stats in the table source https://stackoverflow.com/questions/70...

Processing Strings into Date Datatype column in RDS using PySpark

A date column in a file(In AWS S3) is in "July 28, 2021" Format.Since it is a file it is being treated as String datatype.I am trying to load the data in to RDS(Postgres). The RDS Column is in date datatype. I am using the below line to convert the string into date but NULLS getting loaded in the date column , rest string/integer columns are getting loaded correctly. df_S3=df_S3.withColumn('visit_date', to_date(df_S3.visit_date, 'MON DD, YYYY')) I changed the date from "July 28, 2021" to "28-JUL-2021" in the S3 File and used the below line of code to process the data into RDS - df_S3=df_S3.withColumn('visit_date', to_date(df_S3.visit_date, 'DD-MMM-YYYY')) And dates got loaded correctly into RDS. Could you please advise how to convert/load "July 28, 2021" into a date datatype column using PySpark ? Thanks. source https://stackoverflow.com/questions/70174472/processing-strings-into-date-datatype-column-in-rds...

Cannot GET page in an ejs file

I am trying to open a new file when someone clicks on the "Lets edit stuff" button but I get the error Cannot GET /edit.ejs Both of these files are in the same folder off views/pages/ but I keep getting this error. I have the server.js file running from node. <body class="container"> <main> <ul class="nav nav-pills nav-fill"> <li class="nav-item"> <a class="nav-link active" aria-current="page" href="#">Homepage</a> </li> <li class="nav-item"> <a class="nav-link" href="edit.ejs">Lets edit stuff</a> </li> <li class="nav-item"> <a class="nav-link" href="#">Link</a> </li> </ul> This is what I see on the page Cannot GET /edit.ejs ...

Search for substring in an object using full string

There are full paths to files like libs/shared/util/something/tsconfig.spec.json apps/project/backend/subfolder/project.json this/has/no/match.json root-file.json and I need to check if the file is inside of a path in the given projects object: const projects = { "just-a-library": "libs/shared/util/something", "project-backend": "apps/project/backend" } My problem is, that it will never fully match, but only the beginning of the string - as there are optional subfolders and of course filenames. If there is a match, it should return the object key. So for libs/shared/util/something/tsconfig.spec.json it should return just-a-library and this/has/no/match.json there should be no result. I can't use string.includes(substring) or string.indexOf(substring) as this is the other way round: The full string is the filepath input and I'm searching for a possible substring element. Via Active questions tagged javascript - Stack Ov...

Node LDAP/AD hashing?

I'm having both of a backend and a frontend, my backend running on Node, my Frontend as a simple BrowserApp. I'm using the node-module activedirectory2 to verify a user on our AD-Server. But ad.authenticateUser(username, password) only takes PlainText as password... and I really don't want to send the password from the frontend with a simple "encryption", even tho I'm using TLS 1.3 I'm searching the entire internet for a module which takes hashed values as input to compare credentials. Is there a good way to pass a hashed value to the AD? Or should I be "safe" sending PlainText over TLS 1.3? Via Active questions tagged javascript - Stack Overflow https://ift.tt/2FdjaAW

Why is val() function from jquery throwing TypeError?

let myVariable = $(myinputselector).val When a console.log myVariable it says it's a function, but when I call it with myVariable() it throws a "Uncaught TypeError: this is undefined". Can't I just get and set the input text like this, it's a limitation of jQuery or am I doing something wrong? Via Active questions tagged javascript - Stack Overflow https://ift.tt/2FdjaAW

How can I properly encode a GLTF while also preserving the encoding of other meshes and textures?

I'm building a web ar app that allows users to wear GLTF head models. ( https://www.head5.camera/ ) In order to get the correct lighting on the GLTF, I have set renderer.outputEncoding = THREE.sRGBEncoding and this works great BUT it also adjusts the lighting of my THREE.VideoTexture from my video stream. Is there a way to encode just the GLTF but preserve the LinearEncoding? of the rest of the scene. Any help is much appreciated. Here's an example of what I mean: The background is lighter than it is supposed to be because it is also being encoded. Via Active questions tagged javascript - Stack Overflow https://ift.tt/2FdjaAW

Resolve a multi dimensional array into fully specified endpoints

I need to turn each end-point in a multi-dimensional array (of any dimension) into a row containing the all the descendant nodes using PHP. In other words, I want to resolve each complete branch in the array. I am not sure how to state this more clearly, so maybe the best way is to give an example. If I start with an array like: $arr = array( 'A'=>array( 'a'=>array( 'i'=>1, 'j'=>2), 'b'=>3 ), 'B'=>array( 'a'=>array( 'm'=>4, 'n'=>5), 'b'=>6 ) ); There are 6 end points, namely the numbers 1 to 6, in the array and I would like to generate the 6 rows as: A,a,i,1 A,a,j,2 A,b,2 B,a,m,3 B,a,n,4 B,b,2 Each row contains full path of descendants to the end-point. As the array can have any number of dimensions, this suggested a recursive PHP function and I tried: function array2Rows($arr, $str='', $out='') ...

how to get name attributes and name product together, after call "woocommerce_thankyou"?

$order_items = $order->get_items(); foreach ($order_items as $item_key => $item) { $product = $item->get_product(); // Get the WC_Product Object if( $product->is_type( 'variation' ) ){ $attributes = $product->get_attributes(); $variation_names = array(); if( $attributes ){ foreach ( $attributes as $key => $value) { $variation_key = end(explode('-', $key)); $variation_names[] = ucfirst($variation_key) .' : '. $value; } } echo implode( '<br>', $variation_names ); } } The output of this code is as follows: after echo: %da%86%d8%b1%d8%a8%db%8c and Incompatible with Persian language I need something like this: "product Name , color:red, size:85" source https://stackoverflow.com/questions/70173746/how-to-get-name-attributes-and-name-product-together-after-call-woocommerce-th

How to save column position using Dragula (MySQL / JavaScript / JQuery)

I already have loading from mysql using dragula to display the contents but I can't for the life of me figure out how to save to mysql when a column is changed in dragula (drop function).. What I would like is to have mysql save upon dropping from dragula the column id number. Basically what is occuring right now on load is that it takes the leadStatusId and adds it to the column-# to load in the correct column. But saving upon drop isn't something that I understand. If I could use jquery or javascript to receive the new column id upon drop so that I could pass that onto mysql that would be amazing. <div id="bfl" class="boardflowlead"> <div class="scrolling-wrapper row flex-row flex-nowrap overflow-auto"> <?php $sql = "SELECT user.userid AS uuid, user.name AS uname, user.avatar AS uavatar, lead_status.id AS leadStatusId, lead_status.NAME, lead_status.sort, le...

Create url using data fetched from database in my webpage

I have a database that has a table of assignments CREATE TABLE `assignments` ( `a_id` int NOT NULL AUTO_INCREMENT, `title` varchar(50) NOT NULL, `description` varchar(250) NOT NULL, `file` varchar(50) NOT NULL, ` deadline ` datetime NOT NULL, PRIMARY KEY (`a_id`) ) in my website I would like to view assignments by title, then click on each title (title should be hyperlinked ) to be redirected to details of this specific assignment. here's what I've got so far // Get records from the database $query = $db->query("SELECT * FROM assignments ORDER BY a_id ASC "); if($query->num_rows > 0){ while($row = $query->fetch_assoc()){ $assigment_title = $row['a_id']; ?> <div class="list_item"> <?php echo "<tr><td><a href= 'A i'>" . $row["title"]. "</a></td></tr>"; ?></div> the problem...

How to download blob file using php

I'm trying to download this BLOB file from my database. My php code: <?php $connection = mysqli_connect("localhost","root","","blog") or die('Database Connection Failed'); mysqli_set_charset($connection,'utf-8'); $id = 33; // Use a prepared statement in production to avoid SQL injection; // we can get away with this here because we're the only ones who // are going to use this script. $query = "SELECT * " ."FROM tblog WHERE id = '$id'"; $result = mysqli_query($connection,$query) or die('Error, query failed'); list($id, $file, $type, $size,$content) = mysqli_fetch_array($result); header("Content-length: $size"); header("Content-type: $type"); header("Content-Disposition: attachment; filename=$file"); ob_clean(); flush(); echo $content; mysqli_close($connection); exit; ?> I used this script to download this ...

PHP / mySQL -database connection successful, but I can't write or display data

DB connection is successfull, but I can't write data to DB neather display it to html/php file. I use 000webhost with mySQL. This is project for university, web programming. I must make website (portfolio) but it has to include php and database. Can you help me to find errors because I'm desperate, I tried everything so far. also, my login doesn't work, I feel like I haven't connected to the database at all even though it says otherwise. THIS IS ADMIN PANEL (When login is successfull, it has to redirect to admin-panel) include 'connect.php'; $sql = "SELECT * FROM projekt_web;"; $result = mysqli_query($connection, $sql); $resultCheck = mysqli_num_rows($result); if ($resultCheck > 0) { while($row = mysqli_fetch_assoc($result)) { echo "ID: " . $row["id"]. " Name: " . $row["firstName"]." E-mail: " . $row["email"]. "Poruka: " . $row["poruka"]. "<br>"; ...

Program in Numpy (Python) that takes in five points from a graph and returns the coefficients for the function of that graph

I want to create a program in Numpy (Python) that takes in five points from a graph and returns the coefficients for the function of that graph. Mathematically it would be like this: PS: I know this question is a lot so even if you can't completely answer it I understand but I would appreciate a tip or at least the name of a NumPy library that could help me do this and I'll research it. From that, I just want to know how to implement it into NumPy. Please help! I know I have to subtract the polynomials so I have this: def find_conic(): # define the polynomials # p(x) = 5(x**2) + (-2)x +5 px = (5,-2,5) # q(x) = 2(x**2) + (-5)x +2 qx = (2,-5,2) # subtract the polynomials rx = np.polynomial.polynomial.polysub(px,qx) # print the resultant polynomial print(rx) find_conic() I would then have to substitute the subtracted equation into each other to get the equation for a for example. source https://stackoverflow.com/questions/70160614/program-in-nu...

How to send data to running django management command?

I have a custom django management command that is constantly running through the supervisor (keep alive) I need under certain circumstances (for example, a signal in the project, or a change in the database) the django management process reacted to these changes. Tried looking for something similar but can't seem to find a simple implementation. UPD: In the management command I start the stream process to the twitter API to track new tweets for the tags from django database. When adding a new tag to the database, I want to restart the stream connection. source https://stackoverflow.com/questions/70160705/how-to-send-data-to-running-django-management-command

Reading large compressed files in python

This might be a simple question but I can't seem to find the answer to this or why it is not working on this specific case. I want to read large files, they can be compressed or not. I used contextlib to write a contextmanager function to handle this. Then using the with statement I read the files in the main script. My problem here is that the script uses a lot of memory then get's killed (testing using a compressed file). What am I doing wrong? Should I approach this differently? def process_vcf(location): logging.info('Processing vcf') logging.debug(location) with read_compressed_or_not(location) as vcf: for line in vcf.readlines(): if line.startswith('#'): logging.debug(line) @contextmanager def read_compressed_or_not(location): if location.endswith('.gz'): try: file = gzip.open(location) yield file finally: file.close() else: try:...

Removing a dimension from netcdf file in xarray

I have a dataset ( ds ) loaded from a netcdf file in xarray that looks like this: Where the coordinates (lon, lat) and the data variable (tasmax) are tied to the region dimension. Instead of region , I'd like the dimensions to be lat , lon , time . When I try to remove the region dimension using ds.drop_dim('region') I end up with this: Which makes it so anything tied to region is gone. How can I reset the dimensions on this dataset so that they are based on lat , lon , and time ? source https://stackoverflow.com/questions/70160807/removing-a-dimension-from-netcdf-file-in-xarray

TypeError: axios(...).then is not a function

I am creating a javascript function to use in glideapps, following this process . The function takes in a google maps api url as a string input, and returns the json file as a string output. Using the example from google , I creaced this test which works fine. function test(request_url){ var axios = require('axios'); var config = { method: 'get', url: request_url, headers: { } }; var final = axios(config) .then(function (response) { console.log(JSON.stringify(response.data)); }) .catch(function (error) { console.log(error); }) return final} When I use the same function in the code for the glideapp function, I get two errors. First, I got the error: Error: Module name "axios" has not been loaded yet for context: _. Use require([]) and addressed it by using var axios = require(['foo'], function (foo) instead. window.function=function(request_url){ var axios = require(['axios'], function (axios) { ...

How to move search bar div to the top of the page after button is clicked in vanilla JavaScript

Fairly new to JavaScript so bear with me! I'm currently building a simple TV show rating search app, using TVmaze's API and I'm having trouble figuring out how I can have the search bar move to the top of the page after the search button is clicked. I tried creating a function called searchBarPos to remove the class "center" but I can't seem to figure out why it won't work within my click event listener. Any tips on how to solve this is much appreciated! JS code: const form = document.querySelector("#searchForm"); let div = document.querySelector("#container"); const ul = document.querySelector("#ratingList"); const reset = () => { ul.innerText = ''; } form.addEventListener('submit', async function (e) { e.preventDefault(); reset(); const showName = form.elements.query.value; const config = { params: { q: showName } } const res = await axios.get(`https://api.tvmaze.com/search/sho...

My browser lags when I try a loop function?

I wrote a simple nested loop function to multiply all items in an array and output the total value, but each time is I run a loop function my browser either crashes or doesn't stop loading function multiplyAll(arr){ Let product = 1; for(let i = 0; i < arr.length; i++){ for(let j = 0; j < arr[i].length; j *= product); } return product; } multiplyAll([[1], [2], [3]]); Via Active questions tagged javascript - Stack Overflow https://ift.tt/2FdjaAW

How to Filter multi-select values in nested array of objects

Please find the demo link. https://codesandbox.io/s/agitated-dubinsky-t0hcn?file=/src/nestead-table/index.js I am not able to filter multi-valued selected items in JSON data. this is the data we are passing. const jsonData = [ { isMaster: false, selected: false, ID: 0, "Profile Type": "Line of Business", Risk: [ { isMaster: false, selected: false, ID: 0.1, "Overall Control Effectiveness Rating and Residual Risk Rating": "Not Assessed", Control: [ { isMaster: false, selected: false, ID: 0.2, "Control Classification": "Key", "Control Effectiveness Rating": "Partially Effective" }, { isMaster: false, selected: false, ID: 0.21, "Control Classification": "Compensating", ...

I'm trying to add a user to a role when reacting to an embed and won't add them

I made a command when using an embed the bot reacts to it and when anyone else reacts to it, it will add them to a rule. But it isn't adding the user to the role and I'm unsure why. const {MessageEmbed} = require("discord.js"); module.exports = { name: "reactionrole", async execute(message, args, client) { const channel = '914676864004554803'; const memberRole = message.guild.roles.cache.find(role => role.name === "Members"); const emojireact = '👍'; let embed = new MessageEmbed() .setColor("#e42643") .setTitle("MineCraft Server Rules") .setDescription( "To keep our server safe we need a few basic rules for everyone to follow!" ) .setFooter("Please press 👍 to verify and unlock the rest of the server!") let messageEmbed = await message.channel.send({ embeds: [embed] }); messageEmbed.react(emojireact); client...

how to show alert in the redirected page?

in index.php I have 3 buttons (add, delete, edit) if I click to delete it will redirect to the delete page query (delete.php) after delete success, the page redirects to index.php and the sweet alert2 will popup with a success message (deleted successfully) if I add a user the msg will change to added successfully it depends on where I redirect to index.php so what I can do? source https://stackoverflow.com/questions/70159593/how-to-show-alert-in-the-redirected-page

How to add a new url route to an existing CakePHP (2) project

A client of mine has a legacy CakePHP2 website which needs updating with a new page to produce a PDF and I'm really struggling to get the new method within the Controller to be called. I have a lot of experience with PHP but I've not used it a great deal in the last five years and I've never touched CakePHP. The site was maintained by someone else but they asked me to take a look since that person has left. I know the site is running a very old version of Cake, which I've told them, but they don't want it updated at this point as it's being replaced anyway. I've gone through the CakePHP Docs for v2 but my clients routes.php file does not seem to match up to the wildcard paths suggested in the docs. The entry in routes.php that routes to several existing methods is: Router::connect('/', array('controller' => 'surveys', 'action' => 'index')); I've then edited the Controller/SurveysController.php file to ad...

Regex to match and extract North American phone numbers

I need to match and extract phone numbers from text ... phone numbers that are in this format: 589-845-2889 (589)-845-2889 589.845.2889 589 845 2889 5898452889 (589) 845 2889 The following operation matches the above with great accuracy: preg_match_all("/(\()?\d{3}(?(1)\))[-. ]?\d{3}[-. ]?\d{4}/", $test, $result); So I need to extend it to support international prefix, such as 1 or +1 . Hence, it should also match 1(589) 845 2889 , +1(589) 845 2889 , 1589 845 2889 , 1 589 845 2889 , 15898452889 , etc. Any help would be greatly appreciated. source https://stackoverflow.com/questions/70150895/regex-to-match-and-extract-north-american-phone-numbers

Correct Homepage Link [closed]

I am creating a basic website with navigation link, however when i try to get to the home page, it says the file cannot be found, i have put it in the right file folder path and linked it correctly, but it doesn't work. P.S. When i wants to go to about.html or contact.html, the page says the file cannot be found after moving back to the other page. does anyone know how to fix this source https://stackoverflow.com/questions/70159384/correct-homepage-link

What is the correct way to get the object instance inside its own method in zval format and update a property with a long value?

I'm creating an extension for php in c, but I'm having an error updating a property of type long. I'm trying to use the code below to update the property. zend_update_property_long(kaya_class_entry, getThis(), "lastError", sizeof("lastError") - 1, error); This is my implementation of the method that uses "getThis()" everywhere I use "getThis()" throws an error. PHP_METHOD (Kaya, login) { KAYA *ptr = NULL; zend_string * username; zend_string * password; ZEND_PARSE_PARAMETERS_START(2, 2) Z_PARAM_STR(username) Z_PARAM_STR(password) ZEND_PARSE_PARAMETERS_END(); zend_resource *kaya; zval kaya_ptr; int error; char *mUsername = ZSTR_VAL(username); char *mPassword = ZSTR_VAL(password); char *mLicenseDir = licenseDir(); ptr = fn_kaya_login(mLicenseDir, mUsername, mPassword, &error); if (mLicenseDir != NULL) free(mLicenseDir); zend_update_property_long(ka...

List bbPress topics by month in sidebar

I’m trying to create a navigation sidebar for users to navigate my bbPress forum. I’ve seen WordPress themes with a navigation sidebar for blog posts which has a list of months and years, as in: August 2021 September 2021 October 2021 And clicking any of those list items will show the user any blog posts created in the given month. This is what I’d like to emulate with bbPress — a sidebar with links to different months, and clicking the link will show the user all forum topics created in that month. Does anyone have advice on how to do this? I’ve looked through the bbPress settings and even installed the bbp style pack plugin , but I can’t find a setting that will do what I’m trying to do. Is there a plugin or setting that I’ve missed? I don’t mind writing code to solve this problem, but I’m a PHP beginner so I’m not sure where to start. I’m using WordPress 5.7.2 and bbPress 2.6.6. I don’t have a live version of my site to show. source https://stackoverflow.com/questions/701...

Sort array by current date

I am looking to sort the values in an array based on the current date. My values : [{ date: "2000-12-28", id: 1 }, { date: "2000-11-30", id: 2 }, { date: "2000-09-30", id: 3 }, { date: "2000-05-30", id: 4 }] If it's November 29th : [{ date: "2000-11-30", id: 2 }, { date: "2000-12-28", id: 1 }, { date: "2000-05-30", id: 4 }, { date: "2000-09-30", id: 3 }] I tried to do something like this, but it doesn't really work : var array = [{id: 1, date:'2000-12-28'}, {id: 2, date:'2000-11-30'}, {id: 3, date:'2000-09-30'}, {id: 4, date:'2000-05-30'}]; const now = Date.now(); array.sort(function(a, b) { var c = new Date(a.date); var d = new Date(b.date); return (now-c)-(now-d); }); console.log(array); Via Active questions tagged javascript - Stack Overflow https://ift.tt/2FdjaAW

Why do I get this error in my localHost: Cannot get?

I am trying to make a register system but I cannot get it to work. Whenever I try to run it in LocalHost I get the error "Cannot get" and I also need it to save the data in a JSON file. I hope you can help me. :) Thank you in advance! My server file: const express = require('express'); const app = express(); const brugerCont = require("./controllers/brugerCont"); app.use(express.static("./frontend")); app.use(express.json()); app.use("/brugere", brugerCont); const PORT = 1700; app.listen(PORT, () => { console.log(`Server lytter på http://localhost:${PORT}`); }); My index file: const { response } = require("express"); const { json } = require("body-parser"); document.addEventListener("DOMContentLoaded", (event) => { document.getElementById("form").addEventListener("submit", (event) => { event.preventDefault(); const email = document.getElementById...

How to modify file in form and submit the form with modified data?

I have a simple form: <form id="uploadForm"> <input type="file" name="files"> <br/><br/> <button type="submit">Upload</button> </form> Also i have a function, which gets the file as an input and returns the blob as an output, e.g. async function doSmthWithFile(File) { var objFile=File; var plainTextBytes=await readFile(objFile) .catch(function(err){ console.error(err); }); plainTextBytes=new Uint8Array(plainTextBytes); return new Blob([plainTextBytes], {type: 'image/jpeg'}); } i do want to get file, which user put in the form, modify it, using doSmthWithFile function and submit the form with the blob, which i received from doSmthWithFile ! the condition i want to succeed is that the form should be sent as default one, because in that case, the redirect happens on the server side. On my server side i have an endpoint which seems like: @...

Actionscript ( ) vs Javascript ( )

For same string actionScript's function charCodeAt returns unicode character 13 and javascript's function charCodeAt returns unicode character 10 . Is there a reason why a line feed is returned by JS and a carriage return is returned by AS. After reading a few answers online I have come to the conclusion that both of these do not have much difference, can anyone please explain why was this change made. Via Active questions tagged javascript - Stack Overflow https://ift.tt/2FdjaAW

Add a sortable/searchable "Customer Country" column to the WooCommerce orders table

I added a "Customer Country" column to the WooCommerce orders table (in admin dashboard), but I can't figure how to make it sortable. Any help? It would be a nice bonus if it could be made also searchable. add_filter( 'manage_edit-shop_order_columns', function( $columns ) { $columns['customer_country'] = 'Customer Country'; return $columns; }, 10, 1 ); add_action( 'manage_shop_order_posts_custom_column', function( $column ) { global $post; if( 'customer_country' === $column ) { $order = wc_get_order( $post->ID ); echo get_user_geo_country( $order->get_customer_ip_address() ); } }, 10, 1 ); add_filter( 'manage_edit-shop_order_sortable_columns', function( $columns ) { $columns['customer_country'] = 'customer_country'; return $columns; }, 10, 1 ); add_action( 'pre_get_posts', function( $query ) { if( ! is_admin() ) { return; } // ???? }, 10, 1...

How to add a third language in PHP?

How to add a third language with this specific code format? I have successfully managed 2 languages. I would like to add more than 3 languages. Thank you in advance. <?php session_start(); if (!isset($_SESSION['lang'])) $_SESSION['lang'] = "en"; else if (!isset($_GET['lang']) && $_SESSION['lang'] != $_GET['lang'] && !empty($_GET['lang'])) { if ($_GET['lang'] == "en") $_SESSION['lang'] = "en"; else if ($_GET['lang'] == "sp") $_SESSION['lang'] = "sp";} source https://stackoverflow.com/questions/70146241/how-to-add-a-third-language-in-php

How can i retrieve the formated text from DB and display it in HTML using the PHP?

I have a form that has a field called post content , I am using WYSIWYG Editor to allow the end-user to format the text before saving it or update into the database. the problem that I am facing when it retrieves such content using echo like: <p><?php echo $post_content ?></p> it will be displayed like that to the end-user. This <b>Course </b>is Wonderful. I encourage everyone to take it. So how can i display the retrieved data correctly as per their formates? source https://stackoverflow.com/questions/70146276/how-can-i-retrieve-the-formated-text-from-db-and-display-it-in-html-using-the-ph

Create hierarchy from JSON data

I have a JSON file that contains categories. The idea is to add this to the database with a hierarchical structure. The data is stored in the JSON file like this: [{"productCategory":"Clothes - Pants - Jeans"},{"productCategory":"Clothes - Pants - Chinos"}] How my database table should look like: | taxonomy_id | taxonomy_name | taxonomy_parent | taxonomy_type | | ----------- | ------------- | --------------- | ------------- | | 1 | Clothes | 0 | Category | | 2 | Pants | 1 | Category | | 3 | Jeans | 2 | Category | | 4 | Chinos | 2 | Category | I've got it halfway. But I'm stuck on figuring out the rest. Maybe I need to to this a different way, but I want to check here first. My code: <?php include_once('../../../products/categories.inc.php'); $string = file_get_contents(".....

Can't print attributes from inherited classes [duplicate]

I'm trying to print 2 attributes of an object of a class called Computer. The class Computer inherited the classes Processor, RAM and HD, like in the code provided. In the main code, the first print works, but the second doesn't. When I run the code, it gives me the following error: Traceback (most recent call last): File "/home/ezau/PycharmProjects/Guppe/teste2.py", line 58, in module print(pc1.get_hd_size()) File "/home/ezau/PycharmProjects/Guppe/teste2.py", line 49, in get_hd_size return self.__hd_size AttributeError: 'Computer' object has no attribute '_HD__hd_size' How can the class Computer inherit the attributes and methods in the super classes? The code is provided below: class Processor: def __init__(self): self.__brand = 'AMD' self.__model = 'Ryzen 5 3400g' def get_processor_model(self): return self.__model class RAM: def __init__(self): self.__amount = ...

Programming using selection [closed]

How do I write a python program that asks the user to enter a number between 1 and 12 and displays the name for that month (e.g. an input of 5 would produce the output May). Ho do I write a program that asks the user to enter three numbers for year, month number, and date (e.g. 2001, 5, 11) and outputs the date in the form 5th November 2001. How can I extend your program for displaying dates so that it only accepts valid dates (to ignore leap years). For example, an input of 1999, 2, 30 should be rejected as 30th February is not a valid date. source https://stackoverflow.com/questions/70146683/programming-using-selection

How to use the result of a function to another function in python?

please help I was trying to create Class and Object about pay roll but I got stuck when I tried to use another function to complete the computation for my another funtion I cant think of any idea how can i use the result of hourly rate to compute my overtime pay, to compute my overtime pay it needs the result of hourly rate and multiply them in my overtime hours employee1 = Employee("001", "Joss Rees", 700, 24, 4, 500, 1) class Employee: def __init__(self, employee_number, name, daily_rate, days_worked, overtime_hours, cash_advance, days_absent): self.employee_number = employee_number self.name = name self.daily_rate = daily_rate self.days_worked = days_worked self.overtime_hours = overtime_hours self.cash_advance = cash_advance self.days_absent = days_absent def hourly_rate(self): return print(self.daily_rate / 8) def monthly_rate(self): return print(self.daily_rate * self.da...

Application Default Credentials in Google Cloud Build

Within my code, I am attempting to gather the Application Default Credentials from the associated service account in Cloud Build: from google.auth import default credentials, project_id = default() This works fine in my local space because I have set the environment variable GOOGLE_APPLICATION_CREDENTIALS appropriately. However, when this line is executed (via a test step in my build configuration) within Cloud Build, the following error is raised: google.auth.exceptions.DefaultCredentialsError: Could not automatically determine credentials. Please set GOOGLE_APPLICATION_CREDENTIALS or explicitly create credentials and re-run the application. For more information, please see https://cloud.google.com/docs/authentication/getting-started This is confusing me because, according to the docs: By default, Cloud Build uses a special service account to execute builds on your behalf. This service account is called the Cloud Build service account and it is created automatically when you...

I am trying to find the p value using python, but I have problems [closed]

This is the code I typed in to get the p value, but I got an error. Can someone pls help me? Find the p-value for: 𝐻0 : 𝑝=0.44 vs. 𝐻𝑎 : 𝑝>0.44 𝑝̂ =0.51 𝑛=38 import numpy import scipy p = 0.44 p_hat = 0.51 n = 38 SE = numpy.sqrt((p*(1-p))/n) z = (p_hat-p)/SE p_value = 1 - stats.norm.cdf(z) print(p_value) round(p_value, 6) AttributeError Traceback (most recent call last) <ipython-input-8-5cd3d51cd0b9> in <module> 7 SE = numpy.sqrt((p*(1-p))/n) 8 z = (p_hat-p)/SE ----> 9 p_value = 1 - stats.norm.cdf(z) 10 print(p_value) 11 round(p_value, 6) AttributeError: module 'scipy' has no attribute 'norm' source https://stackoverflow.com/questions/70146660/i-am-trying-to-find-the-p-value-using-python-but-i-have-problems

Flask sends cookie on local server but not when deployed to heroku

I'm using cookies for login auth on a Flask/Nuxt.js website and it works when I run the server locally when but not on my Heroku deployment. I don't believe it's a front end issue because when it works it works on both local and Vercel front end and the same rule applies when it doesn't work. Also, I have no code in the front end to receive the cookie. Setting the cookie: res = make_response({'user': user}, 200) res.set_cookie( 'token', value=token, httponly=True, samesite='strict', secure=True, expires=(datetime.utcnow() + timedelta(weeks=1)) ) return res After request: @app.after_request def after_request(response): response.headers.add( 'Access-Control-Allow-Origins', ['<deployment-site>', '<localhost>'] ) respo...

POST request response undefined , but REQUEST works

userSlice import { createSlice, createAsyncThunk } from "@reduxjs/toolkit"; import LoginService from "../../Services/Login.service"; export const userRegister = createAsyncThunk( "users/register", async (params) => { try { const { registerForm } = params; const { data } = await LoginService.register(registerForm); return data; } catch (error) { } } ); const initialState = { userData: {}, errorResponse: null, status: "idle", }; export const userSlice = createSlice({ name: "User", initialState, reducers: {}, extraReducers: { [userRegister.pending]: (state, action) => { state.status = "loading"; }, [userRegister.fulfilled]: (state, action) => { state.status = "succeeded"; state.userData = action.payload; }, [userRegister.error]: (state, action) => { state.status = "failed"; state.errorResponse =...

Google Charts {c:[v: new Date()]} fails on "JSON.parse" in jsapi_compiled_default_module.js

The Google Charts documentation states that new Date() can be used as a value and that you can load data from remote sources. Documentation: https://developers.google.com/chart/interactive/docs/reference#format-of-the-constructors-javascript-literal-data-parameter See the 'cols Property' section: 'datetime' - JavaScript Date object including the time. Example value: v:new Date(2008, 0, 15, 14, 30, 45) The example also contains a new Date() value: {v: new Date(2008, 1, 28, 0, 31, 26), f: '2/28/08 12:31 AM'} Using this example from Google I load the data and populate the graph: https://developers.google.com/chart/interactive/docs/php_example Using a JSON file without new Date works fine and the Graph gets drawn ok: { "cols": [ {"id":"","label":"Topping","pattern":"","type":"string"}, {"id":"","label":"Slices",...

How do I write this kind of PHP code in Javascript? [duplicate]

I am trying to convert a JSON file to XML using JavaScript. Until now, I used this library : https://github.com/abdolence/x2js ; It does give me the results, but not in the way I want them. Here's what my JSON looks like : { "data": { "key4":{ "sample8": [ { "sample9":"val", "sample10":"val" }, { "sample11":"val", "sample12":"val" }, { "sample13":"val", "sample14":"val" } ] } } } Here's what the XML I get from the library looks like : <data> <key4> <sample8> <sample9>val</sample9> <sample10>val...