instruction
stringlengths
0
30k
The problem is in the way you provide file destination folder in the multer's `destination` method: you're using absolute, instead of a path relative to your project folder, here: cb(null, path.resolve("./public/upload")); which then gets saved like that, and then the frontend tries to load it from the file system, and you get the error. So, try changing the code to use path relative to the project folder in the `destination` method: cb(null, "./public/upload"); Image path should now read `public\upload\1710572384640-solid black.jpg` so, change the `src` in the template attribute to use just the path from the database: src={ post?.image } However, that will not show, because here: app.use(express.static(path.join(__dirname, "public"))); it mounts `public` folder on `/` path, so the path to image is actually `upload\1710572384640-solid black.jpg` So, you can remove `public` part from image path string, for example something like this: src={ post?.image.replace('public', '') } But it would be better to refactor the repository, and move upload folder from public folder, as a separate folder, to avoid mixing with public and better handling, and then you can either make it public (or create a separate route, add auth middleware etc.) For example, you could make `upload` a separate folder, and mount it on a path matching file destinatnio: app.use('/upload', express.static(path.join(__dirname, 'upload'))); Or also save and then use only filename to serve the file from now public upload folder (without `upload` part in path): app.use('/', [express.static('public'), express.static('upload')]); // now you can use just filename: 1710572384640-solid black.jpg` src={ post?.filename }
The d.docx document only a table, across four pages, the last page is a blank page, there is no content. However, if the mouse cursor is located at the top of the blank page, it will become recognized to the state of the form, then right-click the mouse, open source to see the "Delete Cells" option, if you click to delete the cell, the dialog box will pop up, and then choose to delete the line, so three times in a row. This is the third consecutive time, the blank page will disappear. This should be the form of overflow, resulting in a blank page! I tried, Open XML, DocX, Microsoft.Office.Interop.Word, none of them can remove the last blank page. I put the document (d.docx) in the gitgub directory, see link below. [text](https://github.com/angmangm/test) It's better not to use paid dlls, like aspose, etc. [enter image description here](https://i.stack.imgur.com/5wWB9.png)
I can't delete the last blank page in word with c#
|c#|
null
do you mean you want ListA to always be generated before ListB? are there other constraints on ListB, rather than on its size?
[![Error response from FastAPI i.e. deployed on lambda](https://i.stack.imgur.com/QZ0Jd.png)](https://i.stack.imgur.com/QZ0Jd.png) Is there a way to pass query parameter the the `last-n` endpoint and how do i make it to work in AWS lambda Below is my code for reference: ```python import os import smtplib import uvicorn from fastapi import FastAPI, HTTPException, Query from pydantic import BaseModel, Field from mangum import Mangum from fastapi.responses import JSONResponse import mysql.connector from datetime import datetime import json from dbConfig import DBConnector app = FastAPI() handler = Mangum(app) # Define Pydantic model for request body class UserInteraction(BaseModel): usr_id: int usr_info: dict cpt_dttm: str interaction_type: str interaction_detail: str # Creating Database Object db_obj = DBConnector(DB_NAME) @app.get("/") def read_root(): return JSONResponse({"message": "Welcome to GEM AI Layer API interface"}) # Define FastAPI endpoint for inserting data into the table @app.post("/user_interactions/") async def create_user_interaction(user_interaction: UserInteraction): # Insert data into the table query = """ INSERT INTO `USER_INTERACTIONS` (`USR_ID`, `USR_INFO`, `CPT_DTTM`, `INTERACTION_TYPE`, `INTERACTION_DETAIL`) VALUES (%s, %s, %s, %s, %s) """ values = ( user_interaction.usr_id, json.dumps(user_interaction.usr_info), user_interaction.cpt_dttm, user_interaction.interaction_type, user_interaction.interaction_detail ) db_obj.write(query, values) return JSONResponse({"message": "User interaction data inserted successfully"}) # FastAPI endpoint for fetching last "n" records @app.get("/user-interactions/last-n/") async def get_last_n_user_interactions(n: int = Query(..., gt=0)): try: if n > 10: return JSONResponse({"message": "Input parameter is out of range (keep it below 10)"}) query = "SELECT * FROM USER_INTERACTIONS ORDER BY CPT_DTTM DESC LIMIT "+ str(n) records = db_obj.read(query) if records == []: return JSONResponse({"message": "Empty"}) return {"user_interactions": records} except Exception as e: raise HTTPException(status_code=500, detail=f"An error occurred: {str(e)}") if __name__ == '__main__': uvicorn.run(app, host="0.0.0.0", port=5000) ```
Query parameter works fine with fastapi application when tested locally but not working when the FastAPI application is deployed on AWS lambda
|python|rest|aws-lambda|fastapi|crud|
null
Using `List.containsAll()` and `Truth.assertThat(list).contains(originalList)` behaves differently. Working as expected ``` assertThat(getItemsByChannelId.containsAll(entitiesChannelAPage2)).isTrue() ``` Not working as expected ``` assertThat(getItemsByChannelId).contains(entitiesChannelAPage2) ``` I am trying to verify whether the list of data class returned from query on local db are the same set of items from what was previously inserted after performing some deletion. Is there something I am missing here or the first approach is the real solution for such validation? I was hoping to utilize Truth's API to the utmost.
Google Truth.assertThat.contains does not behave similar to List.contains
How can I parse an relative path to an image inside a React Native Image component source?
|react-native|
> How do a build a "Calendar app" in Java? Per your design above, your app will have the following: 1. A UI for adding records (currently command line, but you might want to consider a web UI, Android, Swing or other alternatives) 2. A UI for displaying records 3. A data store for saving records (currently a text file, but you might want to consider a "structured text" format like JSON or XML, or a database). > How do I save a new calendar record in the correct position? I would suggest: 1. Write a "TaskList" class for holding your calendar records. SIMPLE EXAMPLE: public class TaskList { public List<TaskRecord> tasks; public void save(string filename) { ... } public void load(string filename) { ... } } 2. Write a "TaskRecord" class for individual tasks: SIMPLE EXAMPLE: public class TaskRecord { public Date dateTime; public String taskText; } 3. It's important to keep the "date" separate from your "text" in your class. If you want a simple text file, and you want everything on the same line, then choose a delimiter that makes it easy to parse. For example, you can separate "date" and "time" with a tab (`\t`): `10-6-2020 6:30 am\tWake up` 4. It might be unimportant to "insert the record in the right place" until you're ready to "save" the updated file. You can simply "sort()" (by date/time) before you "write()": SIMPLE EXAMPLE: public class TaskRecord implements Comparator<Date> { public Date dateTime; public String taskText; @Override public int compare(TaskRecord a, TaskRecord b) { return a.datetime.compareTo(b.datetime); } } 5. If you really wanted to sort each new record as you insert it, you'd still probably want to implement "Comparator" (as above). You'd loop through your list until you find a time/date >= your new date, then `List.add()` at that index. 6. You'd probably also want to add methods to your "TaskList" class to add, modify and/or delete records. 7. ["Encapsulation"](https://stackify.com/oop-concept-for-beginners-what-is-encapsulation/) can make your classes more robust. You want to *hide* everything about the class that's not "essential" from users of that class SIMPLE EXAMPLE: public class TaskRecord implements Comparator<Date> { private Date dateTime; private String taskText; // Initialize object state in constructor public TaskRecord(Date dateTime, String taskText) { this.dateTime = dateTime; this.taskText = taskText; } // "Getter" methods for read-only access Date getDateTime() { return dateTime; } String getTaskText() { return taskText; } @Override public int compare(TaskRecord a, TaskRecord b) { return a.datetime.compareTo(b.datetime); } }
The problem is that when you put HTML into innerHTML the system adds closing tags. s You can see this by using your browser devtools inspect facility. Hence you are ending up with more than one table. A simple way of preventing this automatic closure is to make a string of all the HTML and then copy the string into the innerHTML. Here is the code (it cannot be a snippet as the snippet system does not allow access to local storage.) <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Package Tracking - Admin</title> </head> <body> <h1>Admin Page</h1> <label for="packageIdAdmin">Package ID:</label> <input type="text" id="packageIdAdmin"> <br> <label for="status">Status:</label> <input type="text" id="status"> <br> <label for="location">Location:</label> <input type="text" id="location"> <br> <label for="estimatedDelivery">Estimated Delivery:</label> <input type="text" id="estimatedDelivery"> <br> <button onclick="addPackage()">Add Package</button> <br><br> <h2>List of Saved Packages</h2> <button onclick="viewPackageList()">View Package List</button> <div id="packageList"></div> <script> // Function to store package data function storePackage(packageId, status, location, estimatedDelivery) { const packageData = { status: status, location: location, estimatedDelivery: estimatedDelivery }; localStorage.setItem(packageId, JSON.stringify(packageData)); } // Function to retrieve package data function retrievePackage(packageId) { const storedPackage = localStorage.getItem(packageId); return storedPackage ? JSON.parse(storedPackage) : null; } // Function to add package by admin function addPackage() { const packageId = document.getElementById("packageIdAdmin").value.trim(); const status = document.getElementById("status").value.trim(); const location = document.getElementById("location").value.trim(); const estimatedDelivery = document.getElementById("estimatedDelivery").value.trim(); if (packageId && status && location && estimatedDelivery) { storePackage(packageId, status, location, estimatedDelivery); alert("Package added successfully!"); } else { alert("Please fill in all fields."); } } // Function to view list of saved packages by admin function viewPackageList() { const packageListDiv = document.getElementById("packageList"); let str = ""; str += "<table border='1'><tr><th>Package ID</th><th>Status</th><th>Location</th><th>Estimated Delivery</th></tr>"; for (let i = 0; i < localStorage.length; i++) { const packageId = localStorage.key(i); const packageData = JSON.parse(localStorage.getItem(packageId)); console.log(localStorage.length); str += ` <tr> <td>${packageId}</td> <td>${packageData.status}</td> <td>${packageData.location}</td> <td>${packageData.estimatedDelivery}</td> <br> </tr> `; } str += "</table>"; packageListDiv.innerHTML = str; } localStorage.clear(); </script> </body> </html>
HotChocolate gives me "Cannot access a disposed context instance." for my DB Context
|c#|entity-framework|graphql|hotchocolate|
Is there's a way to capture a dynamic div content using html2canvas ? Actually I'm using React-rnd in a div and I can't seem to capture the canvas content using html2canvas. Any help is very much appreciated. Thanks. I've tried some example from html2canvas but all I've got is white screen.
html2canvas capture dynamic div content
|html2canvas|
null
yes, it's a dependency issue. you need the oracle driver dependency in your pom.xml not just Oracle, any datasource you use, you must add its driver dependency in your pom.xml > <dependency> > <groupId>com.oracle.database.jdbc</groupId> > <artifactId>ojdbc11</artifactId> > <scope>runtime</scope> > </dependency>
i have a problem with my redirection. ``` <?php // Inclure les fichiers d'initialisation require_once("../inc/init.inc.php"); require_once("../inc/haut.inc.php"); ob_start(); // Assurez-vous que l'intervention_id est passé en paramètre dans l'URL if (isset($_GET['id_intervention']) && is_numeric($_GET['id_intervention'])) { $intervention_id = intval($_GET['id_intervention']); // Récupérez les données existantes de la base de données $selectStmt = $mysqli->prepare("SELECT heure_debut, heure_fin FROM intervention_site WHERE intervention_id = ?"); $selectStmt->bind_param("i", $intervention_id); $selectStmt->execute(); $result = $selectStmt->get_result(); $row = $result->fetch_assoc(); $heure_debut = $row['heure_debut'] ?? null; $heure_fin = $row['heure_fin'] ?? null; $selectStmt->close(); // Extrait les deux premiers caractères pour obtenir l'heure $heure_debut_affichage = substr($heure_debut, 0, 5); // Format "HH:MM" // Vérifiez si le formulaire a été soumis pour l'heure de début if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['heure_debut'])) { // Vérifiez le jeton CSRF if (!isset($_POST['csrf_token']) || $_POST['csrf_token'] !== $_SESSION['csrf_token']) { // Jeton CSRF invalide, traitement de l'erreur (par exemple, redirection ou affichage d'un message d'erreur) header("Location: erreur.php"); exit; } // Récupérez l'heure de début depuis $_POST $heure_debut = $_POST['heure_debut']; // Vérifiez si une entrée existe déjà dans la table intervention_site $selectStmt = $mysqli->prepare("SELECT heure_debut FROM intervention_site WHERE intervention_id = ?"); $selectStmt->bind_param("i", $intervention_id); $selectStmt->execute(); $selectStmt->store_result(); if ($selectStmt->num_rows > 0) { // Une entrée existe déjà, effectuez une mise à jour $sql = "UPDATE intervention_site SET heure_debut = ? WHERE intervention_id = ?"; $stmt = $mysqli->prepare($sql); $stmt->bind_param("si", $heure_debut, $intervention_id); if ($stmt->execute()) { // L'heure de début a été mise à jour avec succès // Mettre à jour le statut dans la table interventions à "en cours" $statut = "En cours"; $updateStatusStmt = $mysqli->prepare("UPDATE interventions SET statut = ? WHERE id_intervention = ?"); $updateStatusStmt->bind_param("si", $statut, $intervention_id); if ($updateStatusStmt->execute()) { echo "Mis à jour table interventions 1 ok "; header("Location: intervention_journaliere.php"); exit(); } else { echo "Erreur lors de la mise à jour du statut: " . $updateStatusStmt->error; } echo "Insertion intervention site 2ok "; header("Location: intervention_journaliere.php"); exit(); $updateStatusStmt->close(); } else { echo "Erreur lors de la mise à jour de l'heure de début : " . $stmt->error; } $stmt->close(); } else { // Aucune entrée n'existe, insérez une nouvelle entrée $sql = "INSERT INTO intervention_site (intervention_id, heure_debut) VALUES (?, ?)"; $stmt = $mysqli->prepare($sql); $stmt->bind_param("is", $intervention_id, $heure_debut); if ($stmt->execute()) { // L'heure de début a été insérée avec succès // Mettre à jour le statut dans la table interventions à "en cours" $statut = "En cours"; $updateStatusStmt = $mysqli->prepare("UPDATE interventions SET statut = ? WHERE id_intervention = ?"); $updateStatusStmt->bind_param("si", $statut, $intervention_id); if ($updateStatusStmt->execute()) { echo "Mis à jour table interventions 2 ok "; header("Location: intervention_journaliere.php"); exit(); } else { echo "Erreur lors de la mise à jour du statut: " . $updateStatusStmt->error; } echo "Insertion intervention site 2 ok "; header("Location: intervention_journaliere.php"); exit(); $updateStatusStmt->close(); } else { echo "Erreur lors de l'insertion de l'heure de début : " . $stmt->error; } $stmt->close(); } } // Générez un jeton CSRF et stockez-le en session $csrf_token = bin2hex(random_bytes(32)); $_SESSION['csrf_token'] = $csrf_token; } else { // Ajoutez un message d'erreur ou une redirection ici si nécessaire echo "Erreur : ID d'intervention non valide."; exit; } ?> <div class="container heure-arrivee-container"> <!-- Utilisez une classe spécifique pour le conteneur --> <h2>Validation de l'heure d'arrivée</h2> <form class="intervention-form heure-arrivee-form" method="POST" action="" enctype="multipart/form-data"> <input type="hidden" name="intervention_id" value="<?php echo htmlspecialchars($intervention_id); ?>"> <input type="hidden" name="csrf_token" value="<?php echo htmlspecialchars($csrf_token); ?>"> <label for="heure_debut">Heure d'arrivée :</label> <input type="time" id="heure_debut" name="heure_debut" value="<?php echo htmlspecialchars($heure_debut_affichage); ?>" required> <input type="submit" value="Valider l'heure de début"> </form> <a href="intervention_journaliere.php" class="return-link">Retour aux plannings journaliers</a> </div> <?php ob_end_flush(); // Affiche le contenu mis en mémoire tampon et désactive la mise en mémoire tampon // Inclure le fichier de pied de page require_once("../inc/bas.inc.php"); ?> ``` The message "mise a jour table ok" and "insertion intervention" is displayed correctly. In my another page the redirection work but here it dont. Do you now why ? I try to change my redirection but it's the same
Use the [deny](https://api.flutter.dev/flutter/services/FilteringTextInputFormatter/FilteringTextInputFormatter.deny.html) method, and the following Regex - `[|]`. FilteringTextInputFormatter.deny(RegExp(r'[|]'))
I have a production. In the queues in front of the respective machine, I would like to prioritize the orders that have the shortest processing time. The information is read from a table. What is the best way to implement this? So far I have tried to prioritize the agent with the smallest number. But it did not work. [![Screenshot](https://i.stack.imgur.com/dhNHQ.png)](https://i.stack.imgur.com/dhNHQ.png)
Queue Anylogic Prio-based
|queue|anylogic|
null
I am trying to fix an issue on one of my Varnish Cache + Nginx setup on a Wordpress website. I am running the following server stack Nginx( HTTPS - 443 ) -> Varnish ( HTTP - 80 ) -> Nginx (HTTP - 8080 ) I am using a vhost method for Varnish cache so that I can host multiple site on he same varnish server. Currently this server is hosting only one website on Wordpress. The Issue ? The varnish is delivering random images / CSS file or even robot.txt to all pages while accessing the website. I included the following vcl file in default.vcl **mydomain.com.vcl** # Auto Generated Varnish Configuration # Wordpress Varnish Optimizations # Build time : 2024-03-15 14:19:11.575844 # Domain : mydomain.com import proxy; sub vcl_recv { if (req.http.host=="mydomain.com" || req.http.host=="www.mydomain.com") { # Set the backend set req.backend_hint = ip_3a355ffbe92e19d4c646b0943e689d609954ef7d; # Remove empty query string parameters if (req.url ~ "\?$") { set req.url = regsub(req.url, "\?$", ""); } # Sorts query string parameters alphabetically for cache normalization purposes set req.url = std.querysort(req.url); # Remove the proxy header to mitigate the httpoxy vulnerability unset req.http.proxy; # Add X-Forwarded-Proto header when using https if (!req.http.X-Forwarded-Proto) { if(std.port(server.ip) == 443 || proxy.is_ssl()) { set req.http.X-Forwarded-Proto = "https"; } else { set req.http.X-Forwarded-Proto = "http"; } } # Only handle relevant HTTP request methods if ( req.method != "GET" && req.method != "HEAD" && req.method != "PUT" && req.method != "POST" && req.method != "PATCH" && req.method != "TRACE" && req.method != "OPTIONS" && req.method != "DELETE" ) { return (pipe); } # Only cache GET and HEAD requests if (req.method != "GET" && req.method != "HEAD") { set req.http.X-Cacheable = "NO:REQUEST-METHOD"; return(pass); } # Mark static files with the X-Static-File header, and remove any cookies # X-Static-File is also used in vcl_backend_response to identify static files if (req.url ~ "^[^?]*\.(7z|avi|bmp|bz2|css|csv|doc|docx|eot|flac|flv|gif|gz|ico|jpeg|jpg|js|less|mka|mkv|mov|mp3|mp4|mpeg|mpg|odt|ogg|ogm|opus|otf|pdf|png|ppt|pptx|rar|rtf|svg|svgz|swf|tar|tbz|tgz|ttf|txt|txz|wav|webm|webp|woff|woff2|xls|xlsx|xml|xz|zip)(\?.*)?$") { set req.http.X-Static-File = "true"; # unset req.http.Cookie; # return(hash); # return(pass); #=> If I pass the image the site works fine } # No caching of special URLs, logged in users and some plugins if ( req.http.Cookie ~ "wordpress_(?!test_)[a-zA-Z0-9_]+|wp-postpass|comment_author_[a-zA-Z0-9_]+|woocommerce_cart_hash|woocommerce_items_in_cart|wp_woocommerce_session_[a-zA-Z0-9]+|wordpress_logged_in_|comment_author|PHPSESSID" || req.http.Authorization || req.url ~ "add_to_cart" || req.url ~ "edd_action" || req.url ~ "nocache" || req.url ~ "^/addons" || req.url ~ "^/bb-admin" || req.url ~ "^/bb-login.php" || req.url ~ "^/bb-reset-password.php" || req.url ~ "^/cart" || req.url ~ "^/checkout" || req.url ~ "^/control.php" || req.url ~ "^/login" || req.url ~ "^/logout" || req.url ~ "^/lost-password" || req.url ~ "^/my-account" || req.url ~ "^/product" || req.url ~ "^/register" || req.url ~ "^/register.php" || req.url ~ "^/server-status" || req.url ~ "^/signin" || req.url ~ "^/signup" || req.url ~ "^/stats" || req.url ~ "^/wc-api" || req.url ~ "^/wp-admin" || req.url ~ "^/wp-comments-post.php" || req.url ~ "^/wp-cron.php" || req.url ~ "^/wp-login.php" || req.url ~ "^/wp-activate.php" || req.url ~ "^/wp-mail.php" || req.url ~ "^/wp-login.php" || req.url ~ "^\?add-to-cart=" || req.url ~ "^\?wc-api=" || req.url ~ "^/preview=" || req.url ~ "^/\.well-known/acme-challenge/" ) { set req.http.X-Cacheable = "NO:Logged in/Got Sessions"; if(req.http.X-Requested-With == "XMLHttpRequest") { set req.http.X-Cacheable = "NO:Ajax"; } return(pass); } # Enable GZIP compression if (req.http.Accept-Encoding) { if (req.url ~ "^[^?]*\.(7z|avi|bmp|bz2|css|csv|doc|docx|eot|flac|flv|gif|gz|ico|jpeg|jpg|js|less|mka|mkv|mov|mp3|mp4|mpeg|mpg|odt|ogg|ogm|opus|otf|pdf|png|ppt|pptx|rar|rtf|svg|svgz|swf|tar|tbz|tgz|ttf|txt|txz|wav|webm|webp|woff|woff2|xls|xlsx|xml|xz|zip)(\?.*)?$") { unset req.http.Accept-Encoding; } elsif (req.http.Accept-Encoding ~ "gzip") { set req.http.Accept-Encoding = "gzip"; } elsif (req.http.Accept-Encoding ~ "deflate" && req.http.user-agent !~ "MSIE") { set req.http.Accept-Encoding = "deflate"; } else { unset req.http.Accept-Encoding; } } # Remove any cookies left unset req.http.Cookie; return(hash); } } sub vcl_hash { if (req.http.host=="mydomain.com" || req.http.host=="www.mydomain.com") { if(req.http.X-Forwarded-Proto) { # Create cache variations depending on the request protocol hash_data(req.http.X-Forwarded-Proto); } return (lookup); } } sub vcl_backend_response { if (bereq.http.host=="mydomain.com" || bereq.http.host=="www.mydomain.com") { # Do not cache 404 error if ( beresp.status >= 301 ) { set beresp.ttl = 30s; set beresp.uncacheable = true; return (deliver); } # Inject URL & Host header into the object for asynchronous banning purposes set beresp.http.x-url = bereq.url; set beresp.http.x-host = bereq.http.host; # If we dont get a Cache-Control header from the backend # we default to 1h cache for all objects if (!beresp.http.Cache-Control) { set beresp.ttl = 1h; set beresp.http.X-Cacheable = "YES:Forced"; } # If the file is marked as static we cache it for 1 day if (bereq.http.X-Static-File == "true") { unset beresp.http.Set-Cookie; set beresp.http.X-Cacheable = "YES:Forced"; set beresp.ttl = 1d; } # Remove the Set-Cookie header when a specific Wordfence cookie is set if (beresp.http.Set-Cookie ~ "wfvt_|wordfence_verifiedHuman") { unset beresp.http.Set-Cookie; } if (beresp.http.Set-Cookie) { set beresp.http.X-Cacheable = "NO:Got Cookies"; } elseif(beresp.http.Cache-Control ~ "private") { set beresp.http.X-Cacheable = "NO:Cache-Control=private"; } elseif (beresp.http.Cache-Control ~ "must-revalidate") { set beresp.grace = 0s; } # Removice cookies on static files if (bereq.url ~ "^[^?]*\.(7z|avi|bmp|bz2|css|csv|doc|docx|eot|flac|flv|gif|gz|ico|jpeg|jpg|js|less|mka|mkv|mov|mp3|mp4|mpeg|mpg|odt|ogg|ogm|opus|otf|pdf|png|ppt|pptx|rar|rtf|svg|svgz|swf|tar|tbz|tgz|ttf|txt|txz|wav|webm|webp|woff|woff2|xls|xlsx|xml|xz|zip)(\?.*)?$") { unset beresp.http.cookie; } # Gzip compression if (beresp.http.url ~ "^[^?]*\.(7z|avi|bmp|bz2|css|csv|doc|docx|eot|flac|flv|gif|gz|ico|jpeg|jpg|js|less|mka|mkv|mov|mp3|mp4|mpeg|mpg|odt|ogg|ogm|opus|otf|pdf|png|ppt|pptx|rar|rtf|svg|svgz|swf|tar|tbz|tgz|ttf|txt|txz|wav|webm|webp|woff|woff2|xls|xlsx|xml|xz|zip)(\?.*)?$") { set beresp.do_gzip = false; } else { set beresp.do_gzip = true; set beresp.http.X-Cache = "ZIP"; } # Do not cache 301, 302, 404, 403, 502 .etc. error return (deliver); } } sub vcl_deliver { if (req.http.host=="mydomain.com" || req.http.host=="www.mydomain.com") { # You can do accounting or modifying the final object here. if (obj.hits) { # Add debug header to see if it's a HIT/MISS and the number of hits, disable when not needed set resp.http.X-Cache = "HIT"; } else { set resp.http.X-Cache = "MISS"; } # Cleanup of headers unset resp.http.x-url; unset resp.http.x-host; unset resp.http.x-powered-by; unset resp.http.X-Powered-By; return (deliver); } } # Bypass webmail , eenos etc,. # Domain : mail.mydomain.com sub vcl_recv { # Set the backend if (req.http.host=="mail.mydomain.com" || req.http.host=="www.mail.mydomain.com" || req.http.host=="eenos.mydomain.com"){ set req.backend_hint = ip_3a355ffbe92e19d4c646b0943e689d609954ef7d; return (pass); } } As you can see this is the same official varnish Wordpress settings provided from their website with some minor changes. The following is my **Varnish SSL termination** on Nginx #.......... HTTPS VHOST .................................. # Varnish ssl termination server { listen 10.0.0.79:443 ssl ; http2 on; server_name mydomain.com www.mydomain.com; ssl_certificate /etc/letsencrypt/live/mydomain.com/fullchain.pem; ssl_certificate_key /etc/letsencrypt/live/mydomain.com/privkey.pem; ssl_protocols TLSv1.3 TLSv1.2; ssl_ciphers ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:DHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES256-GCM-SHA384:ECDHE-RSA-AES128-SHA; # Browser control ssl ciphers ssl_prefer_server_ciphers off; ssl_session_cache shared:SSL:20m; ssl_session_timeout 60m; # All access logs will be handled by proxy access_log off; # Disable direct access to .ht files and folders location ~ /\.(ht|ini|log|conf)$ { deny all; } keepalive_requests 100; keepalive_timeout 60s; # Directory listing disabled autoindex off; # External Alias location / { proxy_pass http://10.0.0.79:80; proxy_set_header Host $host; proxy_set_header X-Forwarded-Host $http_host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto https; proxy_set_header X-Forwarded-Port 443; proxy_set_header HTTPS "on"; proxy_buffering on; proxy_send_timeout 600s; proxy_read_timeout 600s; proxy_buffer_size 256k; proxy_buffers 128 256k; proxy_busy_buffers_size 256k; proxy_temp_file_write_size 256k; proxy_connect_timeout 300s; proxy_http_version 1.1; } } **The Nginx Wordpress Vhost** server { listen 10.0.0.79:8080; server_name mydomain.com www.mydomain.com; # lets encrypt auto ssl acme validation location ^~ /.well-known/acme-challenge/ { default_type "text/plain"; root /var/www/html; } root /home/site/public_html; index index.php index.perl index.pl index.cgi index.phtml index.shtml index.xhtml index.html index.htm index.wml Default.html Default.htm default.html default.htm home.html home.htm eenos.html; location = /favicon.ico { log_not_found off; } # All access logs access_log /var/log/domlogs/mydomain.com main; access_log /var/log/domlogs/mydomain.com-bytes_log bytes_log; referer_hash_bucket_size 512; # Run static file directly from nginx location ~* ^.+.(jpg|jpeg|gif|png|ico|zip|tgz|gz|rar|bz2|iso|doc|xls|exe|pdf|ppt|txt|tar|mid|midi|wav|bmp|rtf|mp3|ogv|ogg|flv|swf|mpeg|mpg|mpeg4|mp4|avi|wmv|js|css|3gp|sis|sisx|nth)$ { expires 30d; } # Disable direct access to .ht files and folders location ~ /\.(ht|ini|log|conf)$ { deny all; } keepalive_requests 100; keepalive_timeout 60s; # Directory listing disabled autoindex off; #phpfiles location ~ \.php$ { try_files $uri =404; fastcgi_pass 127.0.0.1:9000; #fastcgi_pass unix:/var/run/3446b18857ef807e294d091515955c3666797768.sock; fastcgi_index index.php; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; include /etc/nginx/fastcgi_params; } # Disable direct access to .php files in the following on a wordpress site location ~* /(?:uploads|files)/.*\.php$ { deny all; } location / { client_max_body_size 2000m; client_body_buffer_size 512k; try_files $uri $uri/ /index.php?$args; } } if I add **return(pass);** in the vcl file **X-Static-File** section , the website works fine, but the varnish don't cache the static files . Does anyone ever faced the issue. I am running Varnish 7.4
Varnish Cache Strange Issue showing same images /css/txt files on index page or other pages
|wordpress|nginx|varnish|varnish-vcl|varnish-4|
{"Voters":[{"Id":53341,"DisplayName":"MatBailie","BindingReason":{"GoldTagBadge":"sql"}}]}
How do I access "properties" of my `.resw` resource file in code? --- For example, take this example RESW file (from MSDN): [![screenshot of resw editor, with properties like 'Greeting.Text' and 'Farewell'][1]][1] I can access `Farewell` easily: ```cpp auto resourceLoader{ Windows::ApplicationModel::Resources::ResourceLoader::GetForCurrentView() }; const auto myString = resourceLoader.GetString(L"Farewell"); ``` But if I try to do the same thing with `Greeting.Text` (which automatically sets the `Text` property of a control with `x:Uid="Greeting"`, so I can't change it), my app crashes: ```cpp auto resourceLoader{ Windows::ApplicationModel::Resources::ResourceLoader::GetForCurrentView() }; const auto myString = resourceLoader.GetString(L"Greeting.Text"); // crashes ``` Can I access this resource in code without duplicating it? [1]: https://i.stack.imgur.com/Op288.png
|android|unit-testing|assertion|instrumented-test|google-truth|
I have a SQL like this ```sql select * from sys_region as sr left join (select count(*) as c,parent_code from sys_region * group by parent_code ) as c on c.parent_code = sr.parent_code ``` Also, there is entity ```java @Getter @Setter @CTE public class SysRegion extends BaseIdEntity { @Column(length = 128) private String name; @Column private Short level; @Column @ColumnDefault("0") private BigInteger parentCode; @Column @ColumnDefault("0") private BigInteger areaCode; @Column private String cityCode; @Column private Integer zipCode; @Column @ColumnDefault("0.0") private BigDecimal lng; @Column @ColumnDefault("0.0") private BigDecimal lat; @Column private String shortName; @Column private String mergerName; } ``` And I am using quarkus with queryDSL and Blaze persistence How to implement SQL query using that mapping to my entity? And I saw [this link][1] [1]: https://persistence.blazebit.com/documentation/1.6/core/manual/en_US/index.html#querydsl-features Do not have full example for this case `left join with sub query and mapping to entity`?
null
I am observing a strange behaviour where GCC (but not clang) will skip a pointer-reset-after-free expression in the global destruction phase and with certain values of `-O?`. I can reproduce this with every version I tried (7.2.0, 9.4.0, 12.3.0 and 13.2.0) and I'm trying to understand if this is a bug or not. The phenomenon occurs in the [C++ wrapper for lmdb][1]; here are the functions that are involved directly: static inline void lmdb::env_close(MDB_env* const env) noexcept { delete ::mdb_env_close(env); } class lmdb::env { protected: MDB_env* _handle{nullptr}; public: ~env() noexcept { try { close(); } catch (...) {} } MDB_env* handle() const noexcept { return _handle; } void close() noexcept { if (handle()) { lmdb::env_close(handle()); _handle = nullptr; // std::cerr << " handle now " << handle(); } // std::cerr << "\n"; } I use this wrapper in a class `LMDBHook` of which I create a single, static global variable: class LMDBHook { public: ~LMDBHook() { if (s_envExists) { s_lmdbEnv.close(); s_envExists = false; delete[] s_lz4CompState; } } static bool init() { if (!s_envExists) { try { s_lmdbEnv = lmdb::env::create(); //snip } catch (const lmdb::error &e) { // as per the documentation: the environment must be closed even if creation failed! s_lmdbEnv.close(); } } return false; } //snip static lmdb::env s_lmdbEnv; static bool s_envExists; static char* s_lz4CompState; static size_t s_mapSize; }; static LMDBHook LMDB; lmdb::env LMDBHook::s_lmdbEnv{nullptr}; bool LMDBHook::s_envExists = false; char *LMDBHook::s_lz4CompState = nullptr; // set the initial map size to 64Mb size_t LMDBHook::s_mapSize = 1024UL * 1024UL * 64UL; I first came across this issue because an application using `LMDBHook` would crash just before exit when built with GCC but not with clang, and initially thought that this was some subtle compiler influence on the order of calling dtors in the global destruction phase. Indeed, allocating `LMDH` *after* initialising the static member variables will not trigger the issue. But the underlying issue here is that the line `_handle = nullptr;` from `lmdb::env::close()` will be skipped by GCC in the global destruction phase (but not when called e.g. just after `lmdb::env::create()` in `LMDBHook::init()`) and "only" when compiled with -O1, -O2 -O3 or -Ofast (so not with -O0, -Og, -Os or -Oz). The 2 trace output exprs in `lmdb::env::close()` are mine; if I outcomment them the reset instruction is not skipped. The facts that it happens since so many releases and only under specific circumstances during global destruction makes me think it is maybe not a bug though if so the behaviour should not depend on the optimisation level (I think). I have made a self-contained/standalone demonstrator that contains the `lmdb++` headerfile extended with trace output exprs and where the create and close functions simply allocate the `MDB_env` structure with `new` and `delete`, plus the `lmdb` headerfile with an added definition of the `MDB_env` structure (normally it's opaque) : https://github.com/RJVB/gcc_potential_optimiser_bug.git . The README has instructions how to use the Makefile but it should be pretty self-explanatory. Here's some example output: > make -B CXX=g++-mp-12 && lmdbhook g++-mp-12 --version g++-mp-12 (MacPorts gcc12 12.3.0_4+cpucompat+libcxx) 12.3.0 Copyright (C) 2022 Free Software Foundation, Inc. This is free software; see the source for copying conditions. There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. g++-mp-12 -std=c++11 -O3 -o lmdbhook lmdbhook.cpp LMDBHook::LMDBHook() s_lmdbEnv=0x404248 lmdb::env::env(MDB_env*) this=0x404248 handle=0 lmdb::env::env(MDB_env*) this=0x7ffec95f40f8 handle=0x1333020 lmdb::env::~env() this=0x7ffec95f40f8 void lmdb::env::close() this=0x7ffec95f40f8 handle=0 static bool LMDBHook::init() s_lmdbEnv=0x1333020 handle=0x1333020 void lmdb::env::close() this=0x404248 handle=0x1333020 void lmdb::env_close(MDB_env*) env=0x1333020 static bool LMDBHook::init() s_lmdbEnv=0 handle=0 lmdb::env::env(MDB_env*) this=0x7ffec95f40f8 handle=0x1333020 lmdb::env::~env() this=0x7ffec95f40f8 void lmdb::env::close() this=0x7ffec95f40f8 handle=0 static bool LMDBHook::init() s_lmdbEnv=0x1333020 handle=0x1333020 mapsize=67108864 LZ4 state buffer:16384 LMDB instance is 0x404248 lmdb::env::~env() this=0x404248 void lmdb::env::close() this=0x404248 handle=0x1333020 void lmdb::env_close(MDB_env*) env=0x1333020 LMDBHook::~LMDBHook() void lmdb::env::close() this=0x404248 handle=0x1333020 void lmdb::env_close(MDB_env*) env=0x1333020 *** Error in `lmdbhook': double free or corruption (!prev): 0x0000000001333020 *** Abort > make -B CXX=clang++-mp-12 && lmdbhook clang++-mp-12 --version clang version 12.0.1 Target: x86_64-unknown-linux-gnu Thread model: posix InstalledDir: /opt/local/libexec/llvm-12/bin clang++-mp-12 -std=c++11 -O3 -o lmdbhook lmdbhook.cpp LMDBHook::LMDBHook() s_lmdbEnv=0x205090 lmdb::env::env(MDB_env *const) this=0x205090 handle=0 lmdb::env::env(MDB_env *const) this=0x7ffef6c06ca0 handle=0x2e8c20 lmdb::env::~env() this=0x7ffef6c06ca0 void lmdb::env::close() this=0x7ffef6c06ca0 handle=0 static bool LMDBHook::init() s_lmdbEnv=0x2e8c20 handle=0x2e8c20 void lmdb::env::close() this=0x205090 handle=0x2e8c20 void lmdb::env_close(MDB_env *const) env=0x2e8c20 static bool LMDBHook::init() s_lmdbEnv=0 handle=0 lmdb::env::env(MDB_env *const) this=0x7ffef6c06ca0 handle=0x2e8c20 lmdb::env::~env() this=0x7ffef6c06ca0 void lmdb::env::close() this=0x7ffef6c06ca0 handle=0 static bool LMDBHook::init() s_lmdbEnv=0x2e8c20 handle=0x2e8c20 mapsize=67108864 LZ4 state buffer:16384 LMDB instance is 0x205090 lmdb::env::~env() this=0x205090 void lmdb::env::close() this=0x205090 handle=0x2e8c20 void lmdb::env_close(MDB_env *const) env=0x2e8c20 LMDBHook::~LMDBHook() void lmdb::env::close() this=0x205090 handle=0 EDIT: The above examples are with self-built compilers on Linux but the system compilers show the same behaviour, also on Mac, and the choice of C++ runtime (libc++ or libstdc++) has no influence on either platform. EDIT2: the demonstrator also has an alternative implementation of `lmdb::env::close()` as I would have written it, which caches the `_handle` ptr in a tmp. variable, resets `_handle` and only then frees the cached pointer. This implementation is not subject to whatever this issue really is. EDIT3: I had a quick look at the assembly code via gdb (13.2). Not that I can really read it, but I don't see anything in it that could explain conditional behaviour. Built with `g++ -O1 -g` an with a breakpoint on `lmdh::env::close()` (which apparently has 6 locations!) and running through until the invocation where things go awry, I see Breakpoint 1.1, lmdb::env::close (this=0x405250 <LMDBHook::s_lmdbEnv>) at lmdb+++.h:1185 1185 std::cerr << __PRETTY_FUNCTION__ << " this=" << this << " handle=" << handle() << "\n"; (gdb) n void lmdb::env::close() this=0x405250 handle=0x418020 1187 if (handle()) { (gdb) n 1188 lmdb::env_close(handle()); (gdb) void lmdb::env_close(MDB_env*) env=0x418020 lmdb::env::~env (this=<optimised out>, __in_chrg=<optimised out>) at lmdb+++.h:1189 1189 _handle = nullptr; (gdb) p _handle value has been optimised out (gdb) info line 1189 Line 1189 of "lmdb+++.h" starts at address 0x401672 <_ZN4lmdb3envD2Ev+270> and ends at 0x401679. (gdb) disas 0x401672,0x401679 Dump of assembler code from 0x401672 to 0x401679: => 0x0000000000401672 <_ZN4lmdb3envD2Ev+270>: add $0x8,%rsp 0x0000000000401676 <_ZN4lmdb3envD2Ev+274>: pop %rbx 0x0000000000401677 <_ZN4lmdb3envD2Ev+275>: pop %rbp 0x0000000000401678 <_ZN4lmdb3envD2Ev+276>: ret End of assembler dump. (gdb) c Continuing. LMDBHook::~LMDBHook() Breakpoint 1.2, lmdb::env::close (this=0x405250 <LMDBHook::s_lmdbEnv>) at lmdb+++.h:1185 1185 std::cerr << __PRETTY_FUNCTION__ << " this=" << this << " handle=" << handle() << "\n"; (gdb) c Continuing. void lmdb::env::close() this=0x405250 handle=0x418020 void lmdb::env_close(MDB_env*) env=0x418020 *** Error in `/home/bertin/work/src/Scratch/KDE/KF5/LMDBHookTest/lmdbhook': double free or corruption (!prev): 0x0000000000418020 *** Program received signal SIGABRT, Aborted. The 2 asm instructions just above the disassembled line 1189 above: 0x000000000040166a <+262>: mov %rbx,%rdi 0x000000000040166d <+265>: call 0x4010c0 <_ZdlPv@plt> Which I can recognise as a call to `delete(env)`. The 3 following instructions don't seem to set anything to NULL but as I said, I don't really read x86 assembly. Here's the assemble for the same 2 lines built with `clang++-12 -O1 -g`: Line 1188 of "./lmdb+++.h" starts at address 0x202f3b <_ZN4lmdb3env5closeEv+107> and ends at 0x202f43 <_ZN4lmdb3env5closeEv+115>. (gdb) info line 1189 Line 1189 of "./lmdb+++.h" starts at address 0x202f4b <_ZN4lmdb3env5closeEv+123> and ends at 0x202f52 <_ZN4lmdb3env5closeEv+130>. (gdb) disas 0x202f3b,0x202f52 Dump of assembler code from 0x202f3b to 0x202f52: 0x0000000000202f3b <_ZN4lmdb3env5closeEv+107>: mov %r14,%rdi 0x0000000000202f3e <_ZN4lmdb3env5closeEv+110>: call 0x202f70 <_ZNK4lmdb3env6handleEv> 0x0000000000202f43 <_ZN4lmdb3env5closeEv+115>: mov %rax,%rdi 0x0000000000202f46 <_ZN4lmdb3env5closeEv+118>: call 0x202860 <_ZN4lmdbL9env_closeEP7MDB_env> => 0x0000000000202f4b <_ZN4lmdb3env5closeEv+123>: movq $0x0,(%r14) End of assembler dump. Clang doesn't inline the `env_close` function with -O1, but generates a nice pointer reset even I recognise. [1]: https://github.com/bendiken/lmdbxx
I am learning Spring boot JPA hibernate mapping. I am trying to create 2 tables Employee and Address. It is a unidirectional OneToOne mapping. I am creating foreign key in Employee table. Employee contains address and it is a strong association. Without Employee, Address doesn't exist. My createEmployee controller is working fine but when I'm trying to updateEmployee, it is creating a new entry in the Address table. Please tell me if anything I am missing or doing wrong. Thanks! Below is the code. **Address.java** ``` @Entity @Table @NoArgsConstructor @Getter @Setter public class Address { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "addr_id") private Integer addressId; private String addr; public Address(String addr) { this.addr = addr; } ``` **Employee.java** ``` @Table @Entity @NoArgsConstructor @Getter @Setter public class Employee { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Integer empId; private String name; @OneToOne(cascade = CascadeType.ALL) @JoinColumn(name = "address_id", referencedColumnName = "addr_id") private Address address; public Employee(String name, Address address) { this.name = name; this.address = address; } ``` **AddressRepo.java** ``` public interface AddressRepo extends JpaRepository<Address, Integer> { } ``` ``` public interface EmployeeRepo extends JpaRepository<Employee, Integer> { } ``` ``` @Service public class EmployeeServiceImpl implements EmployeeService { @Autowired private EmployeeRepo employeeRepo; @Override public Employee createEmployee(Employee employee) { Employee tempEmployee = this.employeeRepo.save(employee); return tempEmployee; } @Override public Employee updateEmployee(Employee employee, Integer id) { Employee tempEmployee = this.employeeRepo.findById(id).get(); tempEmployee.setName(employee.getName()); tempEmployee.setAddress(employee.getAddress()); System.out.println(employee); return employeeRepo.save(tempEmployee); } @Override public Employee getEmployee(Integer id) { return this.employeeRepo.findById(id).get(); } @Override public Employee deleteEmployee(Integer id) { Employee employee = getEmployee(id); this.employeeRepo.deleteById(id); return employee; } @Override public List<Employee> getAllEmployeees() { return this.employeeRepo.findAll(); } } ``` ``` @RestController @RequestMapping("/employee") public class EmployeeController { @Autowired private EmployeeService employeeService; // Get all employees @GetMapping("/") public List<Employee> getAllEmployees() { return this.employeeService.getAllEmployeees(); } // Get one employee @GetMapping("/{employeeId}") public Employee getEmployee(@PathVariable("employeeId") Integer employeeId) { return this.getEmployee(employeeId); } // save employee @PostMapping("/") public Employee createEmployee(@RequestBody Employee employee) { return this.employeeService.createEmployee(employee); } // update employee @PutMapping("/{employeeId}") public Employee updateEmployee(@PathVariable("employeeId") Integer employeeId, @RequestBody Employee employee) { return this.employeeService.updateEmployee(employee, employeeId); } // delete employee @DeleteMapping("/{employeeId}") public Employee deleteEmployee(@PathVariable("employeeId") Integer employeeId) { return this.employeeService.deleteEmployee(employeeId); } } ``` My HTTP request: [![Postman][1]][1] [1]: https://i.stack.imgur.com/rQ75G.png
I want to run the code from this git-repo on a high performance cluster running Red Hat Enterprise Linux 8.6 (Ootpa). To prepare, I connected via ssl, set up a python 3.6 venv 'hgclr_venv', cloned the repo and installed all necessary packages as stated in requirement.txt with more or less ease. Only the last package, torch-sparse 0.6.12 does not work. I tried `pip install torch-sparse==0.6.12` and got the longes error-output I ever saw. See my command and complete output below. I tried to search the web for solutions but got nowhere. One tip I saw was to install GCC, but when I check, it is already installed. Unfortunately I don't even know where to look for clues in this error-output and would greatly appreciate any help. ``` (hgclr_venv) [ul_rpv49@uc2n996 hgclr_venv]$ pip install torch-sparse==0.6.12 Collecting torch-sparse==0.6.12 Using cached torch_sparse-0.6.12.tar.gz (43 kB) Preparing metadata (setup.py) ... done Requirement already satisfied: scipy in ./lib/python3.6/site-packages (from torch-sparse==0.6.12) (1.5.4) Requirement already satisfied: numpy>=1.14.5 in ./lib/python3.6/site-packages (from scipy->torch-sparse==0.6.12) (1.19.5) Using legacy 'setup.py install' for torch-sparse, since package 'wheel' is not installed. Installing collected packages: torch-sparse Running setup.py install for torch-sparse ... error ERROR: Command errored out with exit status 1: command: /pfs/data5/home/ul/ul_student/ul_rpv49/contrastive-htc/hgclr_venv/bin/python -u -c 'import io, os, sys, setuptools, tokenize; sys.argv[0] = '"'"'/scratch/pip-install-cju09brx/torch-sparse_0e0832cccd184eb19ed9a06356a54e91/setup.py'"'"'; __file__='"'"'/scratch/pip-install-cju09brx/torch-sparse_0e0832cccd184eb19ed9a06356a54e91/setup.py'"'"';f = getattr(tokenize, '"'"'open'"'"', open)(__file__) if os.path.exists(__file__) else io.StringIO('"'"'from setuptools import setup; setup()'"'"');code = f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record /scratch/pip-record-gxct63ib/install-record.txt --single-version-externally-managed --compile --install-headers /pfs/data5/home/ul/ul_student/ul_rpv49/contrastive-htc/hgclr_venv/include/site/python3.6/torch-sparse cwd: /scratch/pip-install-cju09brx/torch-sparse_0e0832cccd184eb19ed9a06356a54e91/ Complete output (85 lines): running install running build running build_py creating build creating build/lib.linux-x86_64-3.6 creating build/lib.linux-x86_64-3.6/torch_sparse copying torch_sparse/__init__.py -> build/lib.linux-x86_64-3.6/torch_sparse copying torch_sparse/add.py -> build/lib.linux-x86_64-3.6/torch_sparse copying torch_sparse/bandwidth.py -> build/lib.linux-x86_64-3.6/torch_sparse copying torch_sparse/cat.py -> build/lib.linux-x86_64-3.6/torch_sparse copying torch_sparse/coalesce.py -> build/lib.linux-x86_64-3.6/torch_sparse copying torch_sparse/convert.py -> build/lib.linux-x86_64-3.6/torch_sparse copying torch_sparse/diag.py -> build/lib.linux-x86_64-3.6/torch_sparse copying torch_sparse/eye.py -> build/lib.linux-x86_64-3.6/torch_sparse copying torch_sparse/index_select.py -> build/lib.linux-x86_64-3.6/torch_sparse copying torch_sparse/masked_select.py -> build/lib.linux-x86_64-3.6/torch_sparse copying torch_sparse/matmul.py -> build/lib.linux-x86_64-3.6/torch_sparse copying torch_sparse/metis.py -> build/lib.linux-x86_64-3.6/torch_sparse copying torch_sparse/mul.py -> build/lib.linux-x86_64-3.6/torch_sparse copying torch_sparse/narrow.py -> build/lib.linux-x86_64-3.6/torch_sparse copying torch_sparse/padding.py -> build/lib.linux-x86_64-3.6/torch_sparse copying torch_sparse/permute.py -> build/lib.linux-x86_64-3.6/torch_sparse copying torch_sparse/reduce.py -> build/lib.linux-x86_64-3.6/torch_sparse copying torch_sparse/rw.py -> build/lib.linux-x86_64-3.6/torch_sparse copying torch_sparse/saint.py -> build/lib.linux-x86_64-3.6/torch_sparse copying torch_sparse/sample.py -> build/lib.linux-x86_64-3.6/torch_sparse copying torch_sparse/select.py -> build/lib.linux-x86_64-3.6/torch_sparse copying torch_sparse/spmm.py -> build/lib.linux-x86_64-3.6/torch_sparse copying torch_sparse/spspmm.py -> build/lib.linux-x86_64-3.6/torch_sparse copying torch_sparse/storage.py -> build/lib.linux-x86_64-3.6/torch_sparse copying torch_sparse/tensor.py -> build/lib.linux-x86_64-3.6/torch_sparse copying torch_sparse/transpose.py -> build/lib.linux-x86_64-3.6/torch_sparse copying torch_sparse/utils.py -> build/lib.linux-x86_64-3.6/torch_sparse running build_ext building 'torch_sparse._convert_cpu' extension creating build/temp.linux-x86_64-3.6 creating build/temp.linux-x86_64-3.6/csrc creating build/temp.linux-x86_64-3.6/csrc/cpu gcc -pthread -Wno-unused-result -Wsign-compare -DDYNAMIC_ANNOTATIONS_ENABLED=1 -DNDEBUG -O2 -g -pipe -Wall -Werror=format-security -Wp,-D_FORTIFY_SOURCE=2 -Wp,-D_GLIBCXX_ASSERTIONS -fexceptions -fstack-protector-strong -grecord-gcc-switches -m64 -mtune=generic -fasynchronous-unwind-tables -fstack-clash-protection -fcf-protection -D_GNU_SOURCE -fPIC -fwrapv -O2 -g -pipe -Wall -Werror=format-security -Wp,-D_FORTIFY_SOURCE=2 -Wp,-D_GLIBCXX_ASSERTIONS -fexceptions -fstack-protector-strong -grecord-gcc-switches -m64 -mtune=generic -fasynchronous-unwind-tables -fstack-clash-protection -fcf-protection -D_GNU_SOURCE -fPIC -fwrapv -O2 -g -pipe -Wall -Werror=format-security -Wp,-D_FORTIFY_SOURCE=2 -Wp,-D_GLIBCXX_ASSERTIONS -fexceptions -fstack-protector-strong -grecord-gcc-switches -m64 -mtune=generic -fasynchronous-unwind-tables -fstack-clash-protection -fcf-protection -D_GNU_SOURCE -fPIC -fwrapv -fPIC -Icsrc -I/pfs/data5/home/ul/ul_student/ul_rpv49/contrastive-htc/hgclr_venv/lib64/python3.6/site-packages/torch/include -I/pfs/data5/home/ul/ul_student/ul_rpv49/contrastive-htc/hgclr_venv/lib64/python3.6/site-packages/torch/include/torch/csrc/api/include -I/pfs/data5/home/ul/ul_student/ul_rpv49/contrastive-htc/hgclr_venv/lib64/python3.6/site-packages/torch/include/TH -I/pfs/data5/home/ul/ul_student/ul_rpv49/contrastive-htc/hgclr_venv/lib64/python3.6/site-packages/torch/include/THC -I/pfs/data5/home/ul/ul_student/ul_rpv49/contrastive-htc/hgclr_venv/include -I/usr/include/python3.6m -c csrc/convert.cpp -o build/temp.linux-x86_64-3.6/csrc/convert.o -O2 -DAT_PARALLEL_OPENMP -fopenmp -DTORCH_API_INCLUDE_EXTENSION_H -DTORCH_EXTENSION_NAME=_convert_cpu -D_GLIBCXX_USE_CXX11_ABI=0 -std=c++14 gcc -pthread -Wno-unused-result -Wsign-compare -DDYNAMIC_ANNOTATIONS_ENABLED=1 -DNDEBUG -O2 -g -pipe -Wall -Werror=format-security -Wp,-D_FORTIFY_SOURCE=2 -Wp,-D_GLIBCXX_ASSERTIONS -fexceptions -fstack-protector-strong -grecord-gcc-switches -m64 -mtune=generic -fasynchronous-unwind-tables -fstack-clash-protection -fcf-protection -D_GNU_SOURCE -fPIC -fwrapv -O2 -g -pipe -Wall -Werror=format-security -Wp,-D_FORTIFY_SOURCE=2 -Wp,-D_GLIBCXX_ASSERTIONS -fexceptions -fstack-protector-strong -grecord-gcc-switches -m64 -mtune=generic -fasynchronous-unwind-tables -fstack-clash-protection -fcf-protection -D_GNU_SOURCE -fPIC -fwrapv -O2 -g -pipe -Wall -Werror=format-security -Wp,-D_FORTIFY_SOURCE=2 -Wp,-D_GLIBCXX_ASSERTIONS -fexceptions -fstack-protector-strong -grecord-gcc-switches -m64 -mtune=generic -fasynchronous-unwind-tables -fstack-clash-protection -fcf-protection -D_GNU_SOURCE -fPIC -fwrapv -fPIC -Icsrc -I/pfs/data5/home/ul/ul_student/ul_rpv49/contrastive-htc/hgclr_venv/lib64/python3.6/site-packages/torch/include -I/pfs/data5/home/ul/ul_student/ul_rpv49/contrastive-htc/hgclr_venv/lib64/python3.6/site-packages/torch/include/torch/csrc/api/include -I/pfs/data5/home/ul/ul_student/ul_rpv49/contrastive-htc/hgclr_venv/lib64/python3.6/site-packages/torch/include/TH -I/pfs/data5/home/ul/ul_student/ul_rpv49/contrastive-htc/hgclr_venv/lib64/python3.6/site-packages/torch/include/THC -I/pfs/data5/home/ul/ul_student/ul_rpv49/contrastive-htc/hgclr_venv/include -I/usr/include/python3.6m -c csrc/cpu/convert_cpu.cpp -o build/temp.linux-x86_64-3.6/csrc/cpu/convert_cpu.o -O2 -DAT_PARALLEL_OPENMP -fopenmp -DTORCH_API_INCLUDE_EXTENSION_H -DTORCH_EXTENSION_NAME=_convert_cpu -D_GLIBCXX_USE_CXX11_ABI=0 -std=c++14 In file included from csrc/cpu/convert_cpu.cpp:5: csrc/cpu/utils.h: In function ‘at::Tensor from_vector(const std::vector<T>&, bool)’: csrc/cpu/utils.h:24:42: error: ‘CppTypeToScalarType’ is not a member of ‘c10’ c10::CppTypeToScalarType<scalar_t>::value); ^~~~~~~~~~~~~~~~~~~ csrc/cpu/utils.h:24:42: note: suggested alternative: ‘typeMetaToScalarType’ c10::CppTypeToScalarType<scalar_t>::value); ^~~~~~~~~~~~~~~~~~~ typeMetaToScalarType csrc/cpu/utils.h:24:70: error: expected primary-expression before ‘>’ token c10::CppTypeToScalarType<scalar_t>::value); ^ csrc/cpu/utils.h:24:73: error: ‘::value’ has not been declared c10::CppTypeToScalarType<scalar_t>::value); ^~~~~ csrc/cpu/utils.h:24:73: note: suggested alternative: In file included from /pfs/data5/home/ul/ul_student/ul_rpv49/contrastive-htc/hgclr_venv/lib64/python3.6/site-packages/torch/include/ATen/core/Dimname.h:3, from /pfs/data5/home/ul/ul_student/ul_rpv49/contrastive-htc/hgclr_venv/lib64/python3.6/site-packages/torch/include/ATen/core/NamedTensor.h:3, from /pfs/data5/home/ul/ul_student/ul_rpv49/contrastive-htc/hgclr_venv/lib64/python3.6/site-packages/torch/include/ATen/core/TensorBody.h:19, from /pfs/data5/home/ul/ul_student/ul_rpv49/contrastive-htc/hgclr_venv/lib64/python3.6/site-packages/torch/include/ATen/Tensor.h:3, from /pfs/data5/home/ul/ul_student/ul_rpv49/contrastive-htc/hgclr_venv/lib64/python3.6/site-packages/torch/include/ATen/Context.h:4, from /pfs/data5/home/ul/ul_student/ul_rpv49/contrastive-htc/hgclr_venv/lib64/python3.6/site-packages/torch/include/ATen/ATen.h:5, from /pfs/data5/home/ul/ul_student/ul_rpv49/contrastive-htc/hgclr_venv/lib64/python3.6/site-packages/torch/include/torch/csrc/api/include/torch/types.h:3, from /pfs/data5/home/ul/ul_student/ul_rpv49/contrastive-htc/hgclr_venv/lib64/python3.6/site-packages/torch/include/torch/csrc/api/include/torch/data/dataloader_options.h:4, from /pfs/data5/home/ul/ul_student/ul_rpv49/contrastive-htc/hgclr_venv/lib64/python3.6/site-packages/torch/include/torch/csrc/api/include/torch/data/dataloader/base.h:3, from /pfs/data5/home/ul/ul_student/ul_rpv49/contrastive-htc/hgclr_venv/lib64/python3.6/site-packages/torch/include/torch/csrc/api/include/torch/data/dataloader/stateful.h:3, from /pfs/data5/home/ul/ul_student/ul_rpv49/contrastive-htc/hgclr_venv/lib64/python3.6/site-packages/torch/include/torch/csrc/api/include/torch/data/dataloader.h:3, from /pfs/data5/home/ul/ul_student/ul_rpv49/contrastive-htc/hgclr_venv/lib64/python3.6/site-packages/torch/include/torch/csrc/api/include/torch/data.h:3, from /pfs/data5/home/ul/ul_student/ul_rpv49/contrastive-htc/hgclr_venv/lib64/python3.6/site-packages/torch/include/torch/csrc/api/include/torch/all.h:4, from /pfs/data5/home/ul/ul_student/ul_rpv49/contrastive-htc/hgclr_venv/lib64/python3.6/site-packages/torch/include/torch/extension.h:4, from csrc/cpu/convert_cpu.h:3, from csrc/cpu/convert_cpu.cpp:1: /pfs/data5/home/ul/ul_student/ul_rpv49/contrastive-htc/hgclr_venv/lib64/python3.6/site-packages/torch/include/ATen/core/aten_interned_strings.h:1024:9: note: ‘c10::attr::value’ _(attr, value) \ ^~~~~ /pfs/data5/home/ul/ul_student/ul_rpv49/contrastive-htc/hgclr_venv/lib64/python3.6/site-packages/torch/include/ATen/core/interned_strings.h:414:35: note: in definition of macro ‘DEFINE_SYMBOL’ namespace ns { constexpr Symbol s(static_cast<unique_t>(_keys::ns##_##s)); } ^ /pfs/data5/home/ul/ul_student/ul_rpv49/contrastive-htc/hgclr_venv/lib64/python3.6/site-packages/torch/include/ATen/core/interned_strings.h:242:3: note: in expansion of macro ‘FORALL_ATTR_BASE_SYMBOLS’ FORALL_ATTR_BASE_SYMBOLS(_) \ ^~~~~~~~~~~~~~~~~~~~~~~~ /pfs/data5/home/ul/ul_student/ul_rpv49/contrastive-htc/hgclr_venv/lib64/python3.6/site-packages/torch/include/ATen/core/interned_strings.h:415:1: note: in expansion of macro ‘FORALL_NS_SYMBOLS’ FORALL_NS_SYMBOLS(DEFINE_SYMBOL) ^~~~~~~~~~~~~~~~~ error: command 'gcc' failed with exit status 1 ---------------------------------------- ERROR: Command errored out with exit status 1: /pfs/data5/home/ul/ul_student/ul_rpv49/contrastive-htc/hgclr_venv/bin/python -u -c 'import io, os, sys, setuptools, tokenize; sys.argv[0] = '"'"'/scratch/pip-install-cju09brx/torch-sparse_0e0832cccd184eb19ed9a06356a54e91/setup.py'"'"'; __file__='"'"'/scratch/pip-install-cju09brx/torch-sparse_0e0832cccd184eb19ed9a06356a54e91/setup.py'"'"';f = getattr(tokenize, '"'"'open'"'"', open)(__file__) if os.path.exists(__file__) else io.StringIO('"'"'from setuptools import setup; setup()'"'"');code = f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record /scratch/pip-record-gxct63ib/install-record.txt --single-version-externally-managed --compile --install-headers /pfs/data5/home/ul/ul_student/ul_rpv49/contrastive-htc/hgclr_venv/include/site/python3.6/torch-sparse Check the logs for full command output. ```
command 'gcc' failed with exit status 1 when trying to install torch-sparse 0.6.12
|python-3.x|pytorch|
null
I have a method that fetchs customers ID from database and saves it to local storage when user select a customer. But after selection in example if I change something in my code and refresh my page, it doesnt fetch. How can I solve this? These my code snippets; export class AdminDashboardComponent implements OnInit{ widgets = [1, 2, 3, 4]; customers: Customer[] = []; selectedCustomerId!: string | null; constructor(private authService: AuthenticationService, private dbService: DbService, private customerSelectionService: CustomerSelectionService) { } ngOnInit() { this.selectedCustomerId = localStorage.getItem('selectedCustomerId'); if (this.selectedCustomerId) { this.customerSelectionService.setSelectedCustomerId(this.selectedCustomerId); } this.fetchCustomers(); } fetchCustomers() { this.dbService.selectCustomer().subscribe({ next: (data: Customer[]) => { console.log(data); this.customers = data; }, error: (error) => { console.error('Error fetching customers', error); }, complete: () => console.log('Customer fetch completed') }); } onCustomerSelected(event: any) { const customerId = event.value; if (customerId !== null && customerId !== undefined) { this.selectedCustomerId = customerId; localStorage.setItem('selectedCustomerId', customerId.toString()); this.customerSelectionService.setSelectedCustomerId(customerId.toString()); this.dbService.sendCustomerId(customerId).subscribe({ next: (response) => { localStorage.setItem('token', response.token); console.log('Customer ID sent to backend successfully:', response); }, error: (error) => { console.error('Error sending customer ID to backend:', error); } }); } else { console.error('Selected customer ID is null or undefined'); } } logout() { this.authService.logout(); } } > html code for selection ; <div class="selector"> <mat-form-field> <mat-label>Select Customer</mat-label> <mat-select [value]="selectedCustomerId" (selectionChange)="onCustomerSelected($event)"> <mat-option *ngFor="let customer of customers" [value]="customer.customer_id"> {{ customer.customer_name }} </mat-option> </mat-select> </mat-form-field> </div> > customer selection service export class CustomerSelectionService { private selectedCustomerIdSource = new BehaviorSubject<string | null>(null); selectedCustomerId$ = this.selectedCustomerIdSource.asObservable(); setSelectedCustomerId(customerId: string | null) { this.selectedCustomerIdSource.next(customerId); } } > service at backend selectCustomer(): Observable<any[]> { const httpOptions = { headers: new HttpHeaders({ 'Authorization': 'Bearer ' + localStorage.getItem('token') }) }; return this.http.get<any[]>(this.apiUrl + "/admin-dashboard", httpOptions); }
|javascript|angular|angularjs|
null
|javascript|angular|
Why does the first Plot require the '/.' replacement operator, but the second Plot does not? Both use InterpolatingFunctions. In the first block of code, 'sol' is an InterpolatingFunction. In the second block of code, iFun is an InterpolatingFunction. I'm still new to Mathematica. ``` ode1 = {y''[x] + Sin[y[x]] == 0, y[0] == 2, y'[0] == 1}; sol = NDSolve[ode1, y, {x, -10, 10}] Plot[y[x] /. sol, {x, -10, 10}] ``` ``` points = {{0, 0}, {1, 1} {2, 3}, {3, 4}, {4, 3}, {5, 0}}; ifun = Interpolation[points] Plot[ifun[x], {x, 0, 5}] ``` I've tried various syntactic choices without success. I believe I am missing some key conceptual piece of information about how these features work. Thank you.
I Do Not Know Why One of These Two Plots Requires the /. Replacement Operator
|wolfram-mathematica|wolframalpha|wolfram-language|
null
I'm Using Laravel 10 I'm trying to get Random Record Without Duplication using inRandomOrder But It Giving Duplicate Record Some Time. help me to Solve It My Controller Code $Question = Question::inRandomOrder()->limit(50)->get();
Laravel using inRandomOrder how to prevent duplicate record
|php|laravel|laravel-10|
The d.docx document only a table, across four pages, the last page is a blank page, there is no content. However, if the mouse cursor is located at the top of the blank page, it will become recognized to the state of the form, then right-click the mouse, open source to see the "Delete Cells" option, if you click to delete the cell, the dialog box will pop up, and then choose to delete the line, so three times in a row. This is the third consecutive time, the blank page will disappear. This should be the form of overflow, resulting in a blank page! I tried, Open XML, DocX, Microsoft.Office.Interop.Word, none of them can remove the last blank page. I put the document (d.docx) in the gitgub directory, see link below. [enter link description here][1] It's better not to use paid dlls, like aspose, etc. [enter image description here](https://i.stack.imgur.com/5wWB9.png) [1]: https://github.com/angmangm/test
{"OriginalQuestionIds":[10514576],"Voters":[{"Id":16217248,"DisplayName":"CPlus"},{"Id":1974224,"DisplayName":"Cristik"},{"Id":578411,"DisplayName":"rene","BindingReason":{"GoldTagBadge":"c#"}}]}
i want to write a code for a telegram bot, where i can connect and see a "dashboard" and "kpi" sheet on a google sheet, however i keep getting this error; "PS C:\Users\ASUS> & C:/Users/ASUS/AppData/Local/Microsoft/WindowsApps/python3.12.exe c:/Users/ASUS/Downloads/philbot.py Traceback (most recent call last): File "c:\Users\ASUS\Downloads\philbot.py", line 51, in <module> main() File "c:\Users\ASUS\Downloads\philbot.py", line 41, in main updater = Updater(TOKEN) ^^^^^^^^^^^^^^" Below is the code; ``` # CODE start import telegram from telegram import InlineKeyboardMarkup, InlineKeyboardButton from telegram.ext import Updater, CommandHandler, CallbackQueryHandler from google.oauth2 import service_account import gspread # Telegram bot token TOKEN = 'xxxxxyyyyyy' # Google Sheets credentials SCOPES = ['https://www.googleapis.com/auth/spreadsheets'] SERVICE_ACCOUNT_FILE = 'C:/Users/ASUS/Downloads/credentials.json' # Specify the path to your credentials JSON file spreadsheet_id = 'yyyyxxxxxxx' # Authenticate with Google Sheets API creds = service_account.Credentials.from_service_account_file(SERVICE_ACCOUNT_FILE, scopes=SCOPES) # Function to fetch data from Google Sheets def get_sheet_data(sheet_name): gc = gspread.authorize(creds) sheet = gc.open_by_key(spreadsheet_id) worksheet = sheet.worksheet(sheet_name) return worksheet.get_all_values() # Command handler for starting the bot def start(bot, update): keyboard = [[InlineKeyboardButton("Dashboard", callback_data='dashboard')], [InlineKeyboardButton("KPI", callback_data='kpi')]] reply_markup = InlineKeyboardMarkup(keyboard) update.message.reply_text('Please choose:', reply_markup=reply_markup) # Callback handler for button presses def button(bot, update): query = update.callback_query sheet_name = query.data data = get_sheet_data(sheet_name) message = '\n'.join(['\t'.join(row) for row in data]) query.edit_message_text(text=message) def main(): updater = Updater(TOKEN) dp = updater.dispatcher dp.add_handler(CommandHandler("start", start)) dp.add_handler(CallbackQueryHandler(button)) updater.start_polling() updater.idle() if __name__ == '__main__': main() ``` i was trying to have 2 buttons in my telegram bot, where if pushed connects to the sheets with the same name and show me the table there, however getting an error
Why when I changed something and reload page my service dont fetch in my angular project?
|node.js|angular|
Solution found by @Simon Couch ; however answering my own question as it could help others, awaiting for Simon to do his own: Installing the dev version of odbc indeed fixed the problem: it is required to restart R after installing the packages.
As I'm very new for using .NET MAUI, so I'm a bit confused about passing data from a page to another page.I'm trying to pass the data from the Signup Page to the Setting Page but I can't. This is the code for Signup Page: ``` <Entry x:Name="fullNameEntry" Text="{Binding FullName}" Placeholder="Alice Wong Li Li" PlaceholderColor="{StaticResource BlurTextColor}" TextColor="{StaticResource NormalTextColor}" FontFamily="WorkSansRegular" CharacterSpacing="-0.5" FontSize="16"/> <Entry x:Name="emailEntry" Placeholder="example@gmail.com" Text="{Binding Email}" PlaceholderColor="{StaticResource BlurTextColor}" TextColor="{StaticResource NormalTextColor}" FontFamily="WorkSansRegular" CharacterSpacing="-0.5" FontSize="16"/> <Entry x:Name="PasswordEntry" Text="{Binding Password}" TextColor="{StaticResource NormalTextColor}" FontFamily="WorkSansRegular" CharacterSpacing="-0.5" FontSize="16"/> <Entry x:Name="ConfirmPasswordEntry" Text="{Binding ConfirmPassword, Mode=TwoWay}" TextColor="{StaticResource NormalTextColor}" FontFamily="WorkSansRegular" CharacterSpacing="-0.5" FontSize="16"> </Entry> <editors:SfMaskedEntry x:Name="phoneNumberEntry" Placeholder="0123456789" MaskType="RegEx" Mask="" PlaceholderColor="{StaticResource BlurTextColor}" TextColor="{StaticResource NormalTextColor}" FontFamily="WorkSansRegular" FontSize="16"/> <Entry x:Name="homeAddressEntry" Text="{Binding HomeAddress}" Placeholder="" PlaceholderColor="{StaticResource BlurTextColor}" TextColor="{StaticResource NormalTextColor}" FontFamily="WorkSansRegular" CharacterSpacing="-0.5" FontSize="16"/> ``` And this is the code for SettingPage: ``` <listView:SfListView x:Name="PersonalInformationListView" Grid.Row="1" Orientation="Vertical" VerticalOptions="Start" ScrollBarVisibility="Always" BackgroundColor="Azure" ItemSize="{OnPlatform 350}" ItemSpacing="{OnPlatform '0,0,0,0'}" ItemsSource="{Binding PersonalInfo}"> <listView:SfListView.ItemTemplate> <DataTemplate> <Grid> <Grid.RowDefinitions> <RowDefinition Height="{OnPlatform Auto}"/> <RowDefinition Height="{OnPlatform 1}"/> <RowDefinition Height="{OnPlatform Auto}"/> <RowDefinition Height="{OnPlatform 1}"/> <RowDefinition Height="{OnPlatform Auto}"/> <RowDefinition Height="{OnPlatform 1}"/> <RowDefinition Height="{OnPlatform Auto}"/> <RowDefinition Height="{OnPlatform 1}"/> </Grid.RowDefinitions> <Frame Grid.Row="0" Padding="{OnPlatform 0}" CornerRadius="0" BorderColor="Transparent" BackgroundColor="{StaticResource FrameBackgroundColor}" HeightRequest="{OnPlatform 80}"> <Label Text="{Binding FullName}" Grid.Row="1" TextColor="{StaticResource ActiveButtonTextColor}" VerticalOptions="Center" LineBreakMode="WordWrap" FontFamily="WorkSansMedium" FontSize="{OnPlatform 18}" Padding="{OnPlatform 15}"/> </Frame> <BoxView Grid.Row="1" Color="{StaticResource Gray400}" HeightRequest="{OnPlatform 1}"/> <Frame Grid.Row="2" Padding="{OnPlatform 0}" CornerRadius="0" BorderColor="Transparent" BackgroundColor="{StaticResource FrameBackgroundColor}" HeightRequest="{OnPlatform 80}"> <Label Text="{Binding Email}" Grid.Row="1" TextColor="{StaticResource ActiveButtonTextColor}" VerticalOptions="Center" LineBreakMode="WordWrap" FontFamily="WorkSansMedium" FontSize="{OnPlatform 18}" Padding="{OnPlatform 15}"/> </Frame> <BoxView Grid.Row="3" Color="{StaticResource Gray400}" HeightRequest="{OnPlatform 1}"/> <Frame Grid.Row="4" Padding="{OnPlatform 0}" CornerRadius="0" BorderColor="Transparent" BackgroundColor="{StaticResource FrameBackgroundColor}" HeightRequest="{OnPlatform 80}"> <Label Text="{Binding PhoneNumber}" Grid.Row="1" TextColor="{StaticResource ActiveButtonTextColor}" VerticalOptions="Center" LineBreakMode="WordWrap" FontFamily="WorkSansMedium" FontSize="{OnPlatform 18}" Padding="{OnPlatform 15}"/> </Frame> <BoxView Grid.Row="5" Color="{StaticResource Gray400}" HeightRequest="{OnPlatform 1}"/> <Frame Grid.Row="6" Padding="{OnPlatform 0}" CornerRadius="0" BorderColor="Transparent" BackgroundColor="{StaticResource FrameBackgroundColor}" HeightRequest="{OnPlatform 80}"> <Label Text="{Binding HomeAddress}" Grid.Row="1" TextColor="{StaticResource ActiveButtonTextColor}" VerticalOptions="Center" LineBreakMode="WordWrap" FontFamily="WorkSansMedium" FontSize="{OnPlatform 18}" Padding="{OnPlatform 15}"/> </Frame> <BoxView Grid.Row="7" Color="{StaticResource Gray400}" HeightRequest="{OnPlatform 1}"/> </Grid> </DataTemplate> </listView:SfListView.ItemTemplate> </listView:SfListView> ``` This is the code for SignupPageViewModel: ``` namespace fitnessStudioMobileApp.ViewModels { public partial class SignupPageViewModel : ObservableObject, INotifyPropertyChanged { [ObservableProperty] private string fullName; [ObservableProperty] private string homeAddress; [ObservableProperty] private string phoneNumber; private string userName; private string userPassword; private string email; private string password; public string UserName { get => userName; set { userName = value; RaisePropertyChanged("UserName"); } } public string UserPassword { get => userPassword; set { userPassword = value; RaisePropertyChanged("UserPassword"); } } public string Email { get => email; set { email = value; RaisePropertyChanged("Email"); } } public string Password { get => password; set { password = value; RaisePropertyChanged("Password"); } } private PersonalInfo _personalInfo; public PersonalInfo PersonalInfo { get => _personalInfo; set => SetProperty(ref _personalInfo, value); } private void RaisePropertyChanged(string v) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(v)); } public SignupPageViewModel() { LoadUserProfile(); } public void LoadUserProfile() { var personalInfoJson = Preferences.Get("PersonalInfo", string.Empty); if (!string.IsNullOrEmpty(personalInfoJson)) { Debug.WriteLine("Loading user profile..."); PersonalInfo = JsonConvert.DeserializeObject<PersonalInfo>(personalInfoJson); // Update ViewModel properties with loaded data FullName = PersonalInfo.FullName; Email = PersonalInfo.Email; PhoneNumber = PersonalInfo.PhoneNumber; HomeAddress = PersonalInfo.HomeAddress; } } private async void RegisterUserCommandTappedAsync() { try { var authProvider = new FirebaseAuthProvider(new FirebaseConfig(webApiKey)); var auth = await authProvider.CreateUserWithEmailAndPasswordAsync(Email, Password); string token = auth.FirebaseToken; var personalInfo = new PersonalInfo { FullName = this.FullName, Email = this.Email, PhoneNumber = this.PhoneNumber, HomeAddress = this.HomeAddress }; if (token != null) { var personalInfoJson = JsonConvert.SerializeObject(personalInfo); Preferences.Set("PersonalInfo", personalInfoJson); await App.Current.MainPage.DisplayAlert("Congratulation!", "User Registered successfully", "OK"); await Shell.Current.GoToAsync("LoginPage"); } } catch (Exception ex) { await App.Current.MainPage.DisplayAlert("Alert", ex.Message, "OK"); } } } } ``` And this is the code for PersonalInfo.cs: ``` using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Microsoft.Maui.Controls; using System.ComponentModel; namespace fitnessStudioMobileApp.Model { public class PersonalInfo : INotifyPropertyChanged { #region Fields private string? fullName; private string? email; private string? phoneNumber; private string? homeAddress; #endregion #region Constructor public PersonalInfo() { } #endregion #region Properties public string? FullName { get { return fullName; } set { fullName = value; OnPropertyChanged("FullName"); } } public string? Email { get { return email; } set { email = value; OnPropertyChanged("Email"); } } public string? PhoneNumber { get { return phoneNumber; } set { phoneNumber = value; OnPropertyChanged("PhoneNumber"); } } public string? HomeAddress { get { return homeAddress; } set { homeAddress = value; OnPropertyChanged("HomeAddress"); } } #endregion #region Interface Member public event PropertyChangedEventHandler? PropertyChanged; public void OnPropertyChanged(string name) { if (this.PropertyChanged != null) this.PropertyChanged(this, new PropertyChangedEventArgs(name)); } #endregion } } ``` I'm trying to pass the data (what the user write their information in SignupPage) to the Setting Page.
How to pass the registered data from Signup Page to Setting Page, .NET MAUI
|c#|maui|
null
I am trying to define a common query for all repositories extending my base repository: ```java @NoRepositoryBean public interface DocumentRepository<T extends BaseDocument> extends JpaRepository<T, Long> { @Query(value = "FROM BaseDocument bd WHERE (bd.createdAt IS NULL OR :to IS NULL OR bd.createdAt < :to) AND (bd.deletedAt IS NULL OR :from IS NULL OR bd.deletedAt > :from)") Iterable<T> findAllActiveBetween(OffsetDateTime from, OffsetDateTime to); } @MappedSuperclass @Where(clause="deleted_at IS NULL") abstract public class BaseDocument { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; private OffsetDateTime createdAt; private OffsetDateTime deletedAt; } ``` The problematic part is using BaseDocument in @Query. Is it possible to define such a method without duplication in all sub-repositories?
null
|java|spring-data-jpa|spring-data|
Is there a way to type a nextjs endpoint, so when sending a request I directly know the returned type? **Example Endpoint** ```` const getHandler = async ( req: NextApiRequest, res: NextApiResponse, prisma: PrismaClient ) => { // query data and type it somehow? } ```` **Example Query** ```` const {data: myData} = useQuery(["myKey"], () => axios.get("/api/myEndpoint")) ```` No matter what I try, the type of myData is always ````AxiosResponse<any, any> | undefined```` I know that I just can create an interface and type type response again, but is there any other way? I appreciate every advice, thanks in advance!
How to type nextjs endpoint with TypeScript?
|typescript|next.js|axios|prisma|react-query|
For `Adapter<RecyclerView.ViewHolder> adapter`, using `adapter.notifyDataSetChanged()` may lead to undesired outcome. For instance https://stackoverflow.com/questions/33851370/applying-statelistanimator-in-recylerviews-item-will-cause-flickering-effect-wh I was wondering, can we use `adapter.notifyItemRangeChanged(0, itemCount)` to replace `adapter.notifyDataSetChanged()`? As I just tested, `adapter.notifyItemRangeChanged(0, itemCount)` will able to update all items properly, and cause no flickering. What might be some potential problem, if we use `adapter.notifyItemRangeChanged(0, itemCount)` to replace `adapter.notifyDataSetChanged()`?
null
Let's start by not bothering with rows vs. columns, because (and this is the nice thing about the game of life), it doesn't matter. The only thing that matters is what the eight values _around_ a cell are doing, so as long as we stick to one ordering, the code will simply do the right thing. Which means we can get rid of that `Cell` function (on that note, that's not how you name things in JS. Variables and functions use lowerCamelCase, classes/constructor functions use UpperCamelCase and constant values use UPPER_SNAKE_CASE). Then, let's fix `Nsum` because it's ignoring the edges right now, which is not how the game of life works: in order to count how many neighbours a cell has, we need to sum _up to_ eight values, but not every cell has eight neighbours. For instance, (0,0) has nothing to the left/above it. So let's rewrite that to a loop: ```lang-js function getNeighbourCount(i, j) { const cells = currentCells; let sum = 0; // run over a 3x3 block, centered on i,j: for (let u = -1; u <= 1; u++) { // ignore any illegal values, thanks to "continue"; if (i + u < 0 || i + u >= cellCount) continue; for (let v = -1; v <= 1; v++) { // again, ignore any illegal values: if (j + v < 0 || j + v >= cellCount) continue; // and skip over [i][j] itself: if (u === 0 && v === 0) continue; sum += cells[i + u][j + v]; } } return sum; } ``` We can also take advantage of the fact that we _know_ we're setting our update board to zeroes, so we don't need to set any cells that should be 0: they already are. We only need to set cells to 1: ```lang-js ... // by copying the empty cells array, we start with // all-zeroes, so we don't need to set anything to 0. const next = structuredClone(emptyCells); for (let i = 0; i < cellCount; i++) { for (let j = 0; j < cellCount; j++) { // is this cell alive? const alive = currentCells[i][j] === 1; // we only need to calculate this once, not three times =) const neighbourCount = getNeighbourCount(i, j); if (alive && (neighbourCount === 2 || neighbourCount === 3)) { next[i][j] = 1; } else if (neighbourCount === 3) { next[i][j] = 1; } } } ... ``` So if we put all that together, and instead of using a canvas we just use a preformatted HTML element that we print our grid into, we get: <!-- begin snippet: js hide: false console: true babel: false --> <!-- language: lang-js --> const cellCount = 10; // Let's define the same grid, but rather than harcoding it, // let's just generate it off of a single number: const emptyCells = [...new Array(cellCount)].map((_) => [...new Array(cellCount)].fill(0)); // Then, initialize the current cells from that empty grid. let currentCells = structuredClone(emptyCells); // To see things work, let's add a "glider" [[0, 1],[1, 2],[2, 0],[2, 1],[2, 2]].forEach(([i, j]) => (currentCells[i][j] = 1)); // Then, our control logic: we'll have the sim run // with a button to pause-resume the simulation. let nextRun; let paused = false; toggle.addEventListener(`click`, () => { paused = !paused; if (paused) clearTimeout(nextRun); else runSimulation(); }); updateBoard(); runSimulation(); // draw our board with □ and ■ for dead and live cells, respectively. function updateBoard() { board.textContent = currentCells .map((row) => row.join(`,`).replaceAll(`0`, `□`).replaceAll(`1`, `■`)) .join(`\n`); } // our simulation just runs through the grid, updating // an initially empty "next" grid based on the four // Game of Life rules. function runSimulation() { const next = structuredClone(emptyCells); for (let i = 0; i < cellCount; i++) { for (let j = 0; j < cellCount; j++) { const alive = currentCells[i][j] === 1; const neighbourCount = getNeighbourCount(i, j); if (alive && (neighbourCount === 2 || neighbourCount === 3)) { next[i][j] = 1; } else if (neighbourCount === 3) { next[i][j] = 1; } } } // update our grid, draw it, and then if we're not paused, // schedule the next call half a second into the future. currentCells = next; updateBoard(); if (!paused) { nextRun = setTimeout(runSimulation, 500); } } // In order to count how many neighbours we have, we need to // sum *up to* eight values. This requires making sure that // we check that a neighbour even exists, of course, because // (0,0), for instance, has nothing to the left/above it. function getNeighbourCount(i, j, cells = currentCells) { let sum = 0; for (let u = -1; u <= 1; u++) { if (i + u < 0 || i + u >= cellCount) continue; for (let v = -1; v <= 1; v++) { if (j + v < 0 || j + v >= cellCount) continue; if (u === 0 && v === 0) continue; sum += cells[i + u][j + v]; } } return sum; } <!-- language: lang-html --> <pre id="board"></pre> <button id="toggle">play/pause</button> <!-- end snippet -->
Since .Net 4.5, the preferred way to implement data validation is to implement [`INotifyDataErrorInfo`][1] (example from [Technet][2], example from [MSDN (Silverlight)][3]). Note: `INotifyDataErrorInfo` replaces the obsolete `IDataErrorInfo`. The new framework infrastructure related to the `INotifyDataErrorInfo` interface provides many advantages like - support of multiple errors per property - custom error objects and customization of visual error feedback (e.g. to adapt visual cues to the custom error object) - asynchronous validation using async/await ---------- How `INotifyDataErrorInfo` works ================================ When the `ValidatesOnNotifyDataErrors` property of `Binding` is set to `true`, the binding engine will search for an `INotifyDataErrorInfo` implementation on the binding source and subscribe to the [`INotifyDataErrorInfo.ErrorsChanged`][4] event. If the `ErrorsChanged` event of the binding source is raised and `INotifyDataErrorInfo.HasErrors` evaluates to `true`, the binding engine will invoke the [`INotifyDataErrorInfo.GetErrors(propertyName)`][5] method for the actual source property to retrieve the corresponding error message and then apply the customizable validation error template to the target control to visualize the validation error. By default a red border is drawn around the element that has failed to validate. In case of an error, which is when `INotifyDataErrorInfo.HasErrors` returns `true`, the binding engine will also set the attached [`Validation`][6] properties on the binding target, for example `Validation.HasError` and `Validation.ErrorTemplate`. To customize the visual error feedback, we can override the default template provided by the binding engine, by overriding the value of the attached `Validation.ErrorTemplate` property (see example below). The described validation procedure only executes when `Binding.ValidatesOnNotifyDataErrors` is set to `true` on the particular data binding and the `Binding.Mode` is set to either `BindingMode.TwoWay` or `BindingMode.OneWayToSource`. How to implement `INotifyDataErrorInfo` ======================================= The following examples show three variations of property validation using 1) `ValidationRule` (class to encapsulate the actual data validation implementation) 2) lambda expressions (or delegates) 3) validation attributes (used to decorate the validated property). Of course, you can combine all three variations to provide maximum flexibility. The code is not tested. The snippets should all work, but may not compile due to typing errors. This code is intended to provide a simple example on how the `INotifyDataErrorInfo` interface could be implemented. ---------- Preparing the view ------------------ **MainWindow.xaml** To enable the visual data validation feedback, the [`Binding.ValidatesOnNotifyDataErrors`][9] property must be set to `true` on each relevant `Binding` i.e. where the source of the `Binding` is a validated property. The WPF framework will then show the control's default error feedback. **Note:** to make this work, the **`Binding.Mode` must be either `OneWayToSource` or `TwoWay`** (which is the default for the `TextBox.Text` property): <Window> <Window.DataContext> <ViewModel /> </Window.DataContext> <!-- Important: set ValidatesOnNotifyDataErrors to true to enable visual feedback --> <TextBox Text="{Binding UserInput, ValidatesOnNotifyDataErrors=True}" Validation.ErrorTemplate="{DynamicResource ValidationErrorTemplate}" /> </Window> The following is an example of a custom validation error template. The default visual error feedback is a simple red border around the validated element. In case you like to customize the visual feedback e.g., to allow showing error messages to the user, you can define a custom `ControlTemplate` and assign it to the validated element (in this case the `TextBox`) via the attached property [`Validation.ErrorTemplate`][10] (see above). The following `ControlTemplate` enables showing a list of error messages that are associated with the validated property: [![enter image description here][11]][11] <ControlTemplate x:Key="ValidationErrorTemplate"> <StackPanel> <Border BorderBrush="Red" BorderThickness="1"> <!-- Placeholder for the TextBox itself --> <AdornedElementPlaceholder x:Name="AdornedElement" /> </Border> <Border Background="White" BorderBrush="Red" Padding="4" BorderThickness="1,0,1,1" HorizontalAlignment="Left"> <ItemsControl ItemsSource="{Binding}" HorizontalAlignment="Left"> <ItemsControl.ItemTemplate> <DataTemplate> <TextBlock Text="{Binding ErrorContent}" Foreground="Red"/> </DataTemplate> </ItemsControl.ItemTemplate> </ItemsControl> </Border> </StackPanel> </ControlTemplate> ---------- The view model is responsible for validating its own properties to ensure the data integrity of the model. I recommend moving the implementation of `INotifyDataErrorInfo` into a base class (e.g. an abstract `ViewModel` class) together with the `INotifyPropertyChanged` implementation and let all your view models inherit it. This makes the validation logic reusable and keeps your view model classes clean. You can change the example's implementation details of `INotifyDataErrorInfo` to meet requirements. 1 Data validation using `ValidationRule` ------------------------ **ViewModel.cs** When using [`ValidationRule`][7], the key is to have separate `ValidationRule` implementations for each property or rule. Extending `ValidationRule` is optional. I chose to extend `ValidationRule` because it already provides a complete validation API and because the implementations can be reused with binding validation if necessary. Basically, the result of the property validation should be a `bool` to indicate fail or success of the validation and a message that can be displayed to the user to help him to fix his input. All we have to do in case of a validation error is to generate an error message, add it to a private string collection to allow our `INotifyDataErrorInfo.GetErrors(propertyName)` implementation to return the proper error messages from this collection and raise the `INotifyDataErrorInfo.ErrorChanged` event to notify the WPF binding engine about the error: public class ViewModel : INotifyPropertyChanged, INotifyDataErrorInfo { // Example property, which validates its value before applying it private string userInput; public string UserInput { get => this.userInput; set { // Validate the value bool isValueValid = IsPropertyValid(value); // Optionally reject value if validation has failed if (isValueValid) { this.userInput = value; OnPropertyChanged(); } } } // Constructor public ViewModel() { this.Errors = new Dictionary<string, IList<object>>(); this.ValidationRules = new Dictionary<string, IList<ValidationRule>>(); // Create a Dictionary of validation rules for fast lookup. // Each property name of a validated property maps to one or more ValidationRule. this.ValidationRules.Add(nameof(this.UserInput), new List<ValidationRule>() { new UserInputValidationRule() }); } // Validation method. // Is called from each property which needs to validate its value. // Because the parameter 'propertyName' is decorated with the 'CallerMemberName' attribute. // this parameter is automatically generated by the compiler. // The caller only needs to pass in the 'propertyValue', if the caller is the target property's set method. public bool IsPropertyValid<TValue>(TValue propertyValue, [CallerMemberName] string propertyName = null) { // Clear previous errors of the current property to be validated _ = ClearErrors(propertyName); if (this.ValidationRules.TryGetValue(propertyName, out List<ValidationRule> propertyValidationRules)) { // Apply all the rules that are associated with the current property // and validate the property's value IEnumerable<object> errorMessages = propertyValidationRules .Select(validationRule => validationRule.Validate(propertyValue, CultureInfo.CurrentCulture)) .Where(result => !result.IsValid) .Select(invalidResult => invalidResult.ErrorContent); AddErrorRange(propertyName, errorMessages); return !errorMessages.Any(); } // No rules found for the current property return true; } // Adds the specified errors to the errors collection if it is not // already present, inserting it in the first position if 'isWarning' is // false. Raises the ErrorsChanged event if the Errors collection changes. // A property can have multiple errors. private void AddErrorRange(string propertyName, IEnumerable<object> newErrors, bool isWarning = false) { if (!newErrors.Any()) { return; } if (!this.Errors.TryGetValue(propertyName, out IList<object> propertyErrors)) { propertyErrors = new List<object>(); this.Errors.Add(propertyName, propertyErrors); } if (isWarning) { foreach (object error in newErrors) { propertyErrors.Add(error); } } else { foreach (object error in newErrors) { propertyErrors.Insert(0, error); } } OnErrorsChanged(propertyName); } // Removes all errors of the specified property. // Raises the ErrorsChanged event if the Errors collection changes. public bool ClearErrors(string propertyName) { if (this.Errors.Remove(propertyName)) { OnErrorsChanged(propertyName); return true; } return false; } // Optional method to check if a particular property has validation errors public bool PropertyHasErrors(string propertyName) => this.Errors.TryGetValue(propertyName, out IList<object> propertyErrors) && propertyErrors.Any(); #region INotifyDataErrorInfo implementation // The WPF binding engine will listen to this event public event EventHandler<DataErrorsChangedEventArgs> ErrorsChanged; // This implementation of GetErrors returns all errors of the specified property. // If the argument is 'null' instead of the property's name, // then the method will return all errors of all properties. // This method is called by the WPF binding engine when ErrorsChanged event was raised and HasErrors return true public System.Collections.IEnumerable GetErrors(string propertyName) => string.IsNullOrWhiteSpace(propertyName) ? this.Errors.SelectMany(entry => entry.Value) : this.Errors.TryGetValue(propertyName, out IList<object> errors) ? (IEnumerable<object>)errors : new List<object>(); // Returns 'true' if the view model has any invalid property public bool HasErrors => this.Errors.Any(); #endregion #region INotifyPropertyChanged implementation public event PropertyChangedEventHandler PropertyChanged; #endregion protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null) { this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } protected virtual void OnErrorsChanged(string propertyName) { this.ErrorsChanged?.Invoke(this, new DataErrorsChangedEventArgs(propertyName)); } // Maps a property name to a list of errors that belong to this property private Dictionary<string, IList<object>> Errors { get; } // Maps a property name to a list of ValidationRules that belong to this property private Dictionary<string, IList<ValidationRule>> ValidationRules { get; } } **UserInputValidationRule.cs** This example validation rule extends [`ValidationRule`][7] and checks if the input starts with the '@' character. If not, it returns an invalid [`ValidationResult`][8] with an error message that can be displayed to the user to help him to fix his input. public class UserInputValidationRule : ValidationRule { public override ValidationResult Validate(object value, CultureInfo cultureInfo) { if (!(value is string userInput)) { return new ValidationResult(false, "Value must be of type string."); } if (!userInput.StartsWith("@")) { return new ValidationResult(false, "Input must start with '@'."); } return ValidationResult.ValidResult; } } 2 Data validation using lambda expressions and delegates ---------------------------------------- As an alternative approach, the `ValidationRule` can be replaced (or combined) with delegates to enable the use of Lambda expressions or Method Groups. The validation expressions in this example return a tuple containing a boolean to indicate the validation state and a collection of `string` error objects for the actual messages. Since all error object related properties are of type `object`, the expressions can return any custom data type, in case you need more advanced error feedback and `string` is not a sufficient error object. In this case, we must also adjust the validation error template, to enable it to handle the data type. **ViewModel.cs** // Example uses System.ValueTuple public class ViewModel : INotifyPropertyChanged, INotifyDataErrorInfo { // This property is validated using a lambda expression private string userInput; public string UserInput { get => this.userInput; set { // Validate the new property value. bool isValueValid = IsPropertyValid(value, newValue => newValue.StartsWith("@") ? (true, Enumerable.Empty<object>()) : (false, new[] { "Value must start with '@'." })); // Optionally, reject value if validation has failed if (isValueValid) { // Accept the valid value this.userInput = value; OnPropertyChanged(); } } } // Alternative usage example property, which validates its value // before applying it, using a Method Group. private string userInputAlternative; public string UserInputAlternative { get => this.userInputAlternative; set { // Use Method Group if (IsPropertyValid(value, IsUserInputValid)) { this.userInputAlternative = value; OnPropertyChanged(); } } } // Constructor public ViewModel() { this.Errors = new Dictionary<string, IList<object>>(); } // The validation method for the UserInput property private (bool IsValid, IEnumerable<object> ErrorMessages) IsUserInputValid(string value) { return value.StartsWith("@") ? (true, Enumerable.Empty<object>()) : (false, new[] { "Value must start with '@'." }); } // Example uses System.ValueTuple public bool IsPropertyValid<TValue>( TValue value, Func<TValue, (bool IsValid, IEnumerable<object> ErrorMessages)> validationDelegate, [CallerMemberName] string propertyName = null) { // Clear previous errors of the current property to be validated _ = ClearErrors(propertyName); // Validate using the delegate (bool IsValid, IEnumerable<object> ErrorMessages) validationResult = validationDelegate?.Invoke(value) ?? (true, Enumerable.Empty<object>()); if (!validationResult.IsValid) { AddErrorRange(propertyName, validationResult.ErrorMessages); } return validationResult.IsValid; } // Adds the specified errors to the errors collection if it is not // already present, inserting it in the first position if 'isWarning' is // false. Raises the ErrorsChanged event if the Errors collection changes. // A property can have multiple errors. private void AddErrorRange(string propertyName, IEnumerable<object> newErrors, bool isWarning = false) { if (!newErrors.Any()) { return; } if (!this.Errors.TryGetValue(propertyName, out IList<object> propertyErrors)) { propertyErrors = new List<object>(); this.Errors.Add(propertyName, propertyErrors); } if (isWarning) { foreach (object error in newErrors) { propertyErrors.Add(error); } } else { foreach (object error in newErrors) { propertyErrors.Insert(0, error); } } OnErrorsChanged(propertyName); } // Removes all errors of the specified property. // Raises the ErrorsChanged event if the Errors collection changes. public bool ClearErrors(string propertyName) { if (this.Errors.Remove(propertyName)) { OnErrorsChanged(propertyName); return true; } return false; } // Optional method to check if a particular property has validation errors public bool PropertyHasErrors(string propertyName) => this.Errors.TryGetValue(propertyName, out IList<object> propertyErrors) && propertyErrors.Any(); #region INotifyDataErrorInfo implementation // The WPF binding engine will listen to this event public event EventHandler<DataErrorsChangedEventArgs> ErrorsChanged; // This implementation of GetErrors returns all errors of the specified property. // If the argument is 'null' instead of the property's name, // then the method will return all errors of all properties. // This method is called by the WPF binding engine when ErrorsChanged event was raised and HasErrors return true public System.Collections.IEnumerable GetErrors(string propertyName) => string.IsNullOrWhiteSpace(propertyName) ? this.Errors.SelectMany(entry => entry.Value) : this.Errors.TryGetValue(propertyName, out IList<object> errors) ? (IEnumerable<object>)errors : new List<object>(); // Returns 'true' if the view model has any invalid property public bool HasErrors => this.Errors.Any(); #endregion #region INotifyPropertyChanged implementation public event PropertyChangedEventHandler PropertyChanged; #endregion protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null) { this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } protected virtual void OnErrorsChanged(string propertyName) { this.ErrorsChanged?.Invoke(this, new DataErrorsChangedEventArgs(propertyName)); } // Maps a property name to a list of errors that belong to this property private Dictionary<string, IList<object>> Errors { get; } } ---------- 3 Data validation using `ValidationAttribute` ------------------------------------------- This is an example implementation of `INotifyDataErrorInfo` with [`ValidationAttribute`][12] support e.g., [`MaxLengthAttribute`][13]. This solution combines the previous Lambda version to additionally support validation using a Lambda expression/delegate simultaneously. While validation using a lambda expression or a delegate must be explicitly invoked by calling the `TryValidateProperty` method in the properties setter, the attribute validation is executed implicitly from the `OnPropertyChanged` event invocator (as soon the property was decorated with validation attributes): **ViewModel.cs** // Example uses System.ValueTuple public class ViewModel : INotifyPropertyChanged, INotifyDataErrorInfo { private string userInput; // Validate property using validation attributes [MaxLength(Length = 5, ErrorMessage = "Only five characters allowed.")] public string UserInput { get => this.userInput; set { // Optional call to 'IsPropertyValid' to combine attribute validation // with a delegate bool isValueValid = IsPropertyValid(value, newValue => newValue.StartsWith("@") ? (true, Enumerable.Empty<object>()) : (false, new[] { "Value must start with '@'." })); // Optionally, reject value if validation has failed if (isValueValid) { this.userInput = value; } // Triggers checking for validation attributes and their validation, // if any validation attributes were found (like 'MaxLength' in this example) OnPropertyChanged(); } } // Constructor public ViewModel() { this.Errors = new Dictionary<string, IList<object>>(); this.ValidatedAttributedProperties = new HashSet<string>(); } // Validate property using decorating attributes. // Is invoked by 'OnPropertyChanged' (see below). private bool IsAttributedPropertyValid<TValue>(TValue value, string propertyName) { this.ValidatedAttributedProperties.Add(propertyName); // The result flag bool isValueValid = true; // Check if property is decorated with validation attributes // using reflection IEnumerable<Attribute> validationAttributes = GetType() .GetProperty(propertyName, BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static) ?.GetCustomAttributes(typeof(ValidationAttribute)) ?? new List<Attribute>(); // Validate using attributes if present if (validationAttributes.Any()) { var validationContext = new ValidationContext(this, null, null) { MemberName = propertyName }; var validationResults = new List<ValidationResult>(); if (!Validator.TryValidateProperty(value, validationContext, validationResults)) { isValueValid = false; AddErrorRange(propertyName, validationResults.Select(attributeValidationResult => attributeValidationResult.ErrorMessage)); } } return isValueValid; } public bool IsPropertyValid<TValue>( TValue value, Func<TValue, (bool IsValid, IEnumerable<object> ErrorMessages)> validationDelegate = null, [CallerMemberName] string propertyName = null) { // Clear previous errors of the current property to be validated ClearErrors(propertyName); // Validate using the delegate (bool IsValid, IEnumerable<object> ErrorMessages) validationResult = validationDelegate?.Invoke(value) ?? (true, Enumerable.Empty<object>()); if (!validationResult.IsValid) { // Store the error messages of the failed validation AddErrorRange(propertyName, validationResult.ErrorMessages); } bool isAttributedPropertyValid = IsAttributedPropertyValid(value, propertyName); return isAttributedPropertyValid && validationResult.IsValid; } // Adds the specified errors to the errors collection if it is not // already present, inserting it in the first position if 'isWarning' is // false. Raises the ErrorsChanged event if the Errors collection changes. // A property can have multiple errors. private void AddErrorRange(string propertyName, IEnumerable<object> newErrors, bool isWarning = false) { if (!newErrors.Any()) { return; } if (!this.Errors.TryGetValue(propertyName, out IList<object> propertyErrors)) { propertyErrors = new List<object>(); this.Errors.Add(propertyName, propertyErrors); } if (isWarning) { foreach (object error in newErrors) { propertyErrors.Add(error); } } else { foreach (object error in newErrors) { propertyErrors.Insert(0, error); } } OnErrorsChanged(propertyName); } // Removes all errors of the specified property. // Raises the ErrorsChanged event if the Errors collection changes. public bool ClearErrors(string propertyName) { this.ValidatedAttributedProperties.Remove(propertyName); if (this.Errors.Remove(propertyName)) { OnErrorsChanged(propertyName); return true; } return false; } // Optional public bool PropertyHasErrors(string propertyName) => this.Errors.TryGetValue(propertyName, out IList<object> propertyErrors) && propertyErrors.Any(); #region INotifyDataErrorInfo implementation public event EventHandler<DataErrorsChangedEventArgs> ErrorsChanged; // Returns all errors of a property. If the argument is 'null' instead of the property's name, // then the method will return all errors of all properties. public System.Collections.IEnumerable GetErrors(string propertyName) => string.IsNullOrWhiteSpace(propertyName) ? this.Errors.SelectMany(entry => entry.Value) : this.Errors.TryGetValue(propertyName, out IList<object> errors) ? (IEnuemrable<object>)errors : new List<object>(); // Returns if the view model has any invalid property public bool HasErrors => this.Errors.Any(); #endregion #region INotifyPropertyChanged implementation public event PropertyChangedEventHandler PropertyChanged; #endregion protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null) { // Check if IsAttributedPropertyValid Property was already called by 'IsValueValid'. if (!this.ValidatedAttributedProperties.Contains(propertyName)) { _ = IsAttributedPropertyValid(value, propertyName); } this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } protected virtual void OnErrorsChanged(string propertyName) { this.ErrorsChanged?.Invoke(this, new DataErrorsChangedEventArgs(propertyName)); } // Maps a property name to a list of errors that belong to this property private Dictionary<string, IList<object>> Errors { get; } // Track attribute validation calls private HashSet<string> ValidatedAttributedProperties { get; } } [1]: https://learn.microsoft.com/en-us/dotnet/api/system.componentmodel.inotifydataerrorinfo?view=netframework-4.7.2 [2]: https://social.technet.microsoft.com/wiki/contents/articles/19490.wpf-4-5-validating-data-in-using-the-inotifydataerrorinfo-interface.aspx [3]: https://learn.microsoft.com/en-us/previous-versions/windows/silverlight/dotnet-windows-silverlight/ee652637(v=vs.95)#examples [4]: https://learn.microsoft.com/en-us/dotnet/api/system.componentmodel.inotifydataerrorinfo.errorschanged?view=net-5.0#remarks [5]: https://learn.microsoft.com/en-us/dotnet/api/system.componentmodel.inotifydataerrorinfo.geterrors?view=net-5.0#remarks [6]: https://learn.microsoft.com/en-us/dotnet/api/system.windows.controls.validation?view=windowsdesktop-6.0 [7]: https://learn.microsoft.com/en-us/dotnet/api/system.windows.controls.validationrule?view=netcore-3.1#examples [8]: https://learn.microsoft.com/en-us/dotnet/api/system.windows.controls.validationresult?view=netcore-3.1#examples [9]: https://learn.microsoft.com/en-us/dotnet/api/system.windows.data.binding.validatesonnotifydataerrors?view=net-5.0#remarks [10]: https://learn.microsoft.com/en-us/dotnet/api/system.windows.controls.validation.errortemplate?view=net-5.0#remarks [11]: https://i.stack.imgur.com/CjikQ.png [12]: https://learn.microsoft.com/en-us/dotnet/api/system.componentmodel.dataannotations.validationattribute?view=netcore-3.1 [13]: https://learn.microsoft.com/en-us/dotnet/api/system.componentmodel.dataannotations.maxlengthattribute?view=netcore-3.1
{"Voters":[{"Id":1453822,"DisplayName":"DeepSpace"},{"Id":16343464,"DisplayName":"mozway"},{"Id":12046409,"DisplayName":"JohanC"}],"SiteSpecificCloseReasonIds":[11]}
I often create HTML dashboards for SharePoint and intranets with JSON data arrays that exceed 100k rows. If you load your data into JavaScript function you can very efficiently aggregate (sum, count, max, min, avg etc) 100k rows in < 2 secs then pass this array to vega-lite. Here is a sample aggregate function: ``` function APBAggregate(data, columns, aggregateType = 'sum', topN = 20) { const numberOfColumns = columns.length; const aggFunc = { sum: (a, b) => a + b, count: (a) => a + 1, max: (a, b) => Math.max(a, b), min: (a, b) => Math.min(a, b), avg: (a, b, countObj, key) => { countObj[key] = (countObj[key] || 0) + 1; return (a * (countObj[key] - 1) + b) / countObj[key]; }, distinct: (a, value, set) => { set.add(value); return set.size; } }; const roundToTwoDecimal = (num) => Math.round(num * 100) / 100; if (numberOfColumns === 1) { const key = columns[0]; if (aggregateType === 'distinct') { const distinctValues = new Set(data.map(item => item[key])); return distinctValues.size; } return roundToTwoDecimal(data.reduce((acc, item) => aggFunc[aggregateType](acc, item[key]), 0)); } if (numberOfColumns === 2) { const [key1, key2] = columns; let countObj = {}; const grouped = data.reduce((acc, item) => { if (aggregateType === 'avg') { acc[item[key1]] = aggFunc[aggregateType](acc[item[key1]] || 0, item[key2], countObj, item[key1]); } else { acc[item[key1]] = aggFunc[aggregateType]((acc[item[key1]] || 0), item[key2]); } return acc; }, {}); return Object.entries(grouped) .sort(([, valA], [, valB]) => valB - valA) .slice(0, topN) .map(([value, total]) => ({ [key1]: value, value: roundToTwoDecimal(total) })); } if (numberOfColumns === 3) { const [key1, key2, key3] = columns; const grouped = data.reduce((acc, item) => { acc[item[key1]] = acc[item[key1]] || {}; acc[item[key1]][item[key2]] = (acc[item[key1]][item[key2]] || 0) + (aggregateType === 'count' ? 1 : item[key3]); return acc; }, {}); return Object.entries(grouped) .map(([value1, subGroup]) => ({ [key1]: value1, values: Object.entries(subGroup).map(([value2, total]) => ({ [key2]: value2, value: roundToTwoDecimal(total) })) })) .sort((a, b) => b.values.reduce((acc, item) => acc + item.value, 0) - a.values.reduce((acc, item) => acc + item.value, 0)) .slice(0, topN); } return []; }; ``` I would then use this function with the below code that would give me a top 25 rows based on VESSEL, TYPE and COUNT of EQUIPID. ``` var ChartData01Temp = apbAggregate(myDataSource,['VESSEL','TYPE','EQUIPID'],'count',25); const ChartData01 = ChartData01Temp.flatMap(entry => entry.values.map(subEntry => ({ G1: entry.VESSEL, G2: subEntry.TYPE, G3: subEntry.value })) ); ``` Vega lite: ``` var V1Spec = { "$schema": "https://vega.github.io/schema/vega-lite/v5.json", "data": {"values": ChartData01}, ``` I also use a Devextreme datagrid to view and filter my json data and then the charts are updated automatically. This is a very efficient way of handling many rows and is much, much faster than using the vega-lite transforms.
> What's the correct approach? Neither is more correct than the other. XML Document 1 --- The XML you posted with explicit namespace prefixes used for the `"urn:asw:erT"` namespace<sup>1</sup>... <ns0:Root xmlns:ns0="urn:asw:erT" xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:urn="urn:asw:erT"> <ns0:Ticket xmlns:urn="urn:asw:erT" Code="TEST" Key="1"> <ns0:client> <ns0:CardNumber>12345</ns0:CardNumber> <ns0:OpenPointsBalance>14352</ns0:OpenPointsBalance> <ns0:PointsEarnedValue>46</ns0:PointsEarnedValue> <ns0:PointsClosingBalance>14398</ns0:PointsClosingBalance> </ns0:client> </ns0:Ticket> </ns0:Root> XML Document 2 --- ...is fully equivalent to the following XML with the `"urn:asw:erT"` default namespace: <Root xmlns="urn:asw:erT" xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:urn="urn:asw:erT"> <Ticket Code="TEST" Key="1"> <client> <CardNumber>12345</CardNumber> <OpenPointsBalance>14352</OpenPointsBalance> <PointsEarnedValue>46</PointsEarnedValue> <PointsClosingBalance>14398</PointsClosingBalance> </client> </Ticket> </Root> No conformant XML processor or application should treat **XML Document 1** any differently than **XML Document 2**. > My colleague has given each element in a payload a namespace `ns0` for best practice It's fine to use a namespace prefix for each element, but there is no consensus that such is a "best practice". > ...and my parser stopped working If your parser is sensitive to the difference between **XML Document 1** and **XML Document 2**, then your parser is broken. --- **[1]** Note that the repeated declaration of `xmlns:urn="urn:asw:erT"` on `ns0:Ticket` is unnecessary but allowed.
The most straightforward option is to set the `MachineId` on the `MachineDashboardViewModel`s when you create them and put them in the `Machines` property. Taking a detour from the parent view model to the data template to the user control to to the child view model makes absolutely no sense when the child viewmodels are in a property of the parent view model from the beginning.
If you still want to take advantage of pnpm and avoid the node-linker=hoisted option, you can take a look at this [great article][1] that explains how to make it works. To summarize it, you need to 1- add a bunch of packages to make the react-native cli works with pnpm: pnpm install @react-native-community/cli-platform-ios @react-native-community/cli-platform-android 2- re-install your pods # in ios folder bundle exec pod install 3- allow metro to understand symlink (prior to RN72, it natively can't) with @rnx-kit pnpm install @rnx-kit/metro-config @rnx-kit/metro-resolver-symlinks change your metro.config.js file to this: const { makeMetroConfig } = require('@rnx-kit/metro-config') const MetroSymlinksResolver = require('@rnx-kit/metro-resolver-symlinks') module.exports = makeMetroConfig({ projectRoot: __dirname, resolver: { resolveRequest: MetroSymlinksResolver(), }, }) 4 - extra step to build on android pnpm install react-native-gradle-plugin jsc-android [1]: https://runreactnative.dev/posts/pnpm-react-native
For the given code, you should have the following time complexity: ``` T(n) = 1 + N/2 (1 + 2) + 1 + 1 + 1 + 100 (1 + 2) ≈ N/2 ``` This means that your overall complexity is `O(n)`. Because the second `for` loop (the first nested `for` loop) never executes, due to its condition, you don't have `O(n^3)` complexity. If the second `for` loop was written as `for(int j=0; j< N; j++)`, then you would have `O(n^3)` complexity.
I am making a form using next js 14, I made an actions.ts file there I built a generic method that shows a console log. [form component][1] [action.ts][2] In the form component, loginForm.tsx, in the form tag, I use the action property, and from there, I call the generic method that I made in action.ts [devtools/network tab/payload][3] What happened is that, when I clicked on the save button of the form, I observed that in the devtools, in the network tab, a request was reflected, but I saw that in the netowrk tab, in the payload option, all the information in the form fields is displayed. my doubts are: 1. Why does the user and password information appear in the devtools -> tab network -> in the payload? 2. Is that considered a security vulnerability? 3. Is there any idea on how to prevent it from displaying that information? I was investigating the topic, apparently it has to do with the html tag <form action={}></form>, but there was no mention of how to solve that detail [1]: https://i.stack.imgur.com/BX8D2.png [2]: https://i.stack.imgur.com/48uIs.png [3]: https://i.stack.imgur.com/FlBp2.png
So my project got successfully deployed to the vercel. The issue was a mistake that i made where i didn't properly linked the path to my views folder in index.js , however if someOne is having any issues with that make sure to look into the logs on vercel , it will show you what the issue is . also Mine worked fine with this vercel.json code { "version": 2, "rewrites": [{ "source": "/(.*)", "destination": "/api" }] }
I need to have one "General login database", with few columns (ID, Pass, User, IP). Users came to site, enter their data (they can change password\username, and their ip can be changed), all this changes goes to "General Login DB". And I have 2 another servers, with same database "Login Database 1" "Log.DB 2" and maybe few more (5 or 10)... they have exactly same columns name (id, pass, user, ip) and few more specific which must stay only on (log.db2, 3, 4, 5, etc. database) and they don't exist on General DB. So my questions is how to Link few database.table to another database.table, and keep it "Up-To-Date" online, or how to make automatic changes (Insert\Update\Delete) in them, after changes (ins, upd, del) came to General Login DB. Image only show direction that I want, and not perfect with structure. I am interested in 2 variants, if it works on One server, and second variant, if it works on 2-3-4-5 servers. UPDATE: I found some info, about "Replication" https://habrahabr.ru/post/56702/ (you can translate it, or google "Replication MySQL" but there only info about 2 identical Database, but my goal is only make identical few columns in one table. [![Pic.1][1]][1] [1]: https://i.stack.imgur.com/trDpq.png
I have a shared object where **file** indicates it is a shared object, and it is used and behaves as a shared object. % file libirc.so libirc.so: ELF 64-bit LSB shared object, x86-64, version 1 (SYSV), dynamically linked, BuildID[sha1]=9d54bda46b31ae048aae323dfd809f9ae6c8c55c, not stripped % But the **ldd** command indicates it is statically linked. % ldd libirc.so statically linked % When I run an executable, ./Solver, that uses this libirc.so it runs as expected. But when I run the same with LD_PRELOAD="io_functions.so" the run time linker, /lib64/ld-linux-x86-64.so.2, segfaults just after issuing the error message: ./Solver: Relink `./lib/libirc.so' with `/lib64/libc.so.6' for IFUNC symbol `memmove' I can make the run using LD_PRELOAD work by also including libirc.so on the LD_PRELOAD. I don't have source for libirc.so so I can't figure out much on that end. I suspect that the troubles are centered on libirc.so being statically linked. It should not matter what code is in io_functions.so because ld.so doesn't even get to the point of calling the init functions as ld.so is segfaulting while binding symbols. I have done a bit of investigating using **LD_DEBUG**. When I run with **LD_PRELOAD=irc/libirc.so** ld.so needs to find memmove for libstdc++ , and uses **memmove [GLIBC_2.2.5]** from /lib64/libc.so.6. Later ld.so needs to find memmove for libirc.so and also uses memmove from libc.so.6. LD_DEBUG output from successfull run with LD_PRELOAD=irc/libirc.so 3677171: binding file /lib64/libstdc++.so.6 [0] to /lib64/libc.so.6 [0]: normal symbol `memmove' [GLIBC_2.2.5] . . . 3677171: binding file irc/libirc.so [0] to /lib64/libc.so.6 [0]: normal symbol 'memmove' When I run the failing job (without **LD_PRELOAD=irc/libirc.so**), ld.so first needs to find memmove for libirc.so and finds it in libc.so.6. ld.so then prints out the Relink message, followed by a segfault. **Why does running this way cause the Relink message and segfault, even though its finding memmove for libirc.so in the same place ( libc.so.6 ) as the above successful run?** The last LD_DEBUG line for this process, followed by the print 3676728: binding file irc/libirc.so [0] to /lib64/libc.so.6 [0]: normal symbol `memmove' ./bin/SMAEqsDirSolverSymmetric: Relink `irc/libirc.so' with `/lib64/libc.so.6' for IFUNC symbol `memmove'
Here's a runnable example: With SrcTable as (SELECT 'product_id' as key, 'iphone_14' as value from dummy union all SELECT 'product_id' as key, 'iphone_14_pro' as value from dummy union all SELECT 'country_code' as key, 'USA' as value from dummy union all SELECT 'country_code' as key, 'CA' as value from dummy) SELECT * FROM JSON_TABLE('[ {"key": "product_id","value": "iphone_14"}, {"key": "product_id","value": "iphone_14_pro"}, {"key": "country_code","value": "INVALID_VALUE"}, {"key": "country_code","value": "USA"} ]', '$' COLUMNS ( KEY nvarchar(20) PATH '$.key', VALUE nvarchar(20) PATH '$.value' )) EXCEPT SELECT key, value FROM srcTable To make work for you: - Eliminate the srctable with statement and replace the srcTable with your validation table name following the "EXCEPT" - You'll also need to pass in the string in the JSON_TABLE as a input parameter with a string with the assumption it has the key/value format as an input parameter with the limits defined in COLUMNS of the JSON_TABLE table value function. Set based operators typically perform efficiently.
I have a LET & FILTER function used to use a drop down (green cell) and then it populates a report underneath based on data in sheet("Master") You can see it's bringing in all the ("Master") sheet columns B:M in order and I don't need columns C:K ![enter image description here][1] How can I change `fRng,Master!B3:INDEX(Master!M:M,lr)` to only index and populate columns B, L, M into the sheet with the green drop down (the sheet with my LET formula)? rest of formula: =LET( lr,COUNTA(Master!L:L), fRng,Master!B3:INDEX(Master!M:M,lr), criteriaRng1,Master!L3:INDEX(Master!L:L,lr), criteriaRng2,Master!M3:INDEX(Master!M:M,lr), FILTER(fRng,(criteriaRng1=Metrics!A1)* (criteriaRng2="Negotiating"))) Data that I am indexing and whatnot in formula: [enter image description here][2] [1]: https://i.stack.imgur.com/Fsn2b.png [2]: https://i.stack.imgur.com/0ctOr.png
## Do not install Mamba in Anaconda/Miniconda It is no longer recommended to install `mamba` in an Anaconda or Miniconda **base**. However, Conda now uses the `libmamba` solver, so just upgrade your **base** `conda` to v23.11.0 or greater and it will run as fast as `mamba`. ```bash ## v23.11+ uses libmamba solver conda install -n base -n defaults 'conda>=23.11' ``` The main problem currently is that `mamba` is only served from Conda Forge channel and Conda Forge packages require that channel to be prioritized. In practice that simply does not work with Anaconda **base**. The least painful resolution would be for Anaconda to build their own copy of `mamba` and serve it from the `anaconda` (`defaults`) channel. More generally, one should simply not be installing anything from Conda Forge in Anaconda **base**. ## Consider Micromamba A newer solution is [Micromamba](https://mamba.readthedocs.io/en/latest/installation/micromamba-installation.html) which is static and doesn't live in an environment. It is extremely useful for creating Conda environments without having to install a Conda **base** (such as provisioning in CI or containers). I expect more users will continue to adopt it since it properly separates the functionality of manipulating Conda environments from a Conda environment (**base**).
|oop|design-patterns|circular-dependency|
null
Delete the `package-lock.json` file and the `node_modules` directory in your project and then run `npm install` on your terminal. If you still have issues, you may refer the following link. Nextjs Docs: https://nextjs.org/docs/messages/failed-loading-swc
null
I have written my Golang HTML DOM parser with pure Golang and no dependency used in it. This project is still under development. But now it is usable, and I will develop it in the future. Project link: https://github.com/pejman-hkh/gdp/ ```go package main import ( "fmt" "github.com/pejman-hkh/gdp/gdp" ) func main() { document := gdp.Default(`<!DOCTYPE html> <html> <head> <title> Title of the document </title> </head> <body> body content <p>more content</p> </body> </html>`) body := document.Find("body").Eq(0) fmt.Print(body.Html()) } ```
I'm currently working implementing AES encryption in the backend using Python, but I'm encountering some issues in ensuring compatibility between frontend and backedn. I need help in integrating the frontend JavaScript code to work with it. My backend Python code: class Crypt(): def pad(self, data): BLOCK_SIZE = 16 length = BLOCK_SIZE - (len(data) % BLOCK_SIZE) return data + (chr(length)*length) def unpad(self, data): return data[:-(data[-1] if type(data[-1]) == int else ord(data[-1]))] def bytes_to_key(self, data, salt, output=48): assert len(salt) == 8, len(salt) data += salt key = sha256(data).digest() final_key = key while len(final_key) < output: key = sha256(key + data).digest() final_key += key return final_key[:output] def bytes_to_key_md5(self, data, salt, output=48): assert len(salt) == 8, len(salt) data += salt key = md5(data).digest() final_key = key while len(final_key) < output: key = md5(key + data).digest() final_key += key return final_key[:output] def encrypt(self, message): passphrase = "<secret passpharse value>".encode() salt = Random.new().read(8) key_iv = self.bytes_to_key_md5(passphrase, salt, 32+16) key = key_iv[:32] iv = key_iv[32:] aes = AES.new(key, AES.MODE_CBC, iv) return base64.b64encode(b"Salted__" + salt + aes.encrypt(self.pad(message).encode())) def decrypt(self, encrypted): passphrase ="<secret passpharse value>".encode() encrypted = base64.b64decode(encrypted) assert encrypted[0:8] == b"Salted__" salt = encrypted[8:16] key_iv = self.bytes_to_key_md5(passphrase, salt, 32+16) key = key_iv[:32] iv = key_iv[32:] aes = AES.new(key, AES.MODE_CBC, iv) return self.unpad(aes.decrypt(encrypted[16:])).decode().strip('"') def base64_decoding(self, encoded): base64decode = base64.b64decode(encoded) return base64decode.decode() crypt = Crypt() test = "secret message to be send over network" encrypted_message = crypt.encrypt(test) print("Encryp msg:", encrypted_message) decrypted_message = crypt.decrypt(encrypted_message) print("Decryp:", decrypted_message) here's what I've tried so far on the frontend with React and CryptoJS: import React from "react"; import CryptoJS from 'crypto-js'; const DecryptEncrypt = () => { function bytesToKey(passphrase, salt, output = 48) { if (salt.length !== 8) { throw new Error('Salt must be 8 characters long.'); } let data = CryptoJS.enc.Latin1.parse(passphrase + salt); let key = CryptoJS.SHA256(data).toString(CryptoJS.enc.Latin1); let finalKey = key; while (finalKey.length < output) { data = CryptoJS.enc.Latin1.parse(key + passphrase + salt); key = CryptoJS.SHA256(data).toString(CryptoJS.enc.Latin1); finalKey += key; } return finalKey.slice(0, output); } const decryptData = (encryptedData, key) => { const decodedEncryptedData = atob(encryptedData); const salt = CryptoJS.enc.Hex.parse(decodedEncryptedData.substring(8, 16)); const ciphertext = CryptoJS.enc.Hex.parse(decodedEncryptedData.substring(16)); const keyIv = bytesToKey(key, salt.toString(), 32 + 16); const keyBytes = CryptoJS.enc.Hex.parse(keyIv.substring(0, 32)); const iv = CryptoJS.enc.Hex.parse(keyIv.substring(32)); const decrypted = CryptoJS.AES.decrypt( { ciphertext: ciphertext }, keyBytes, { iv: iv, mode: CryptoJS.mode.CBC, padding: CryptoJS.pad.Pkcs7 } ); return decrypted.toString(CryptoJS.enc.Utf8); }; const encryptData = (data, key) => { const salt = CryptoJS.lib.WordArray.random(8); // Generate random salt const keyIv = bytesToKey(key, salt.toString(), 32 + 16); const keyBytes = CryptoJS.enc.Hex.parse(keyIv.substring(0, 32)); const iv = CryptoJS.enc.Hex.parse(keyIv.substring(32)); const encrypted = CryptoJS.AES.encrypt(data, keyBytes, { iv: iv, mode: CryptoJS.mode.CBC, padding: CryptoJS.pad.Pkcs7 }); const ciphertext = encrypted.ciphertext.toString(CryptoJS.enc.Hex); const saltedCiphertext = "Salted__" + salt.toString(CryptoJS.enc.Hex) + ciphertext; return btoa(saltedCiphertext); }; const dataToEncrypt = 'Data to be sent over network'; const encryptionKey = "<secret passpharse value>"; const encryptedData = encryptData(dataToEncrypt, encryptionKey); console.log("Encrypted data:", encryptedData); const decryptedData = decryptData(encryptedData, encryptionKey); console.log("Decrypted data:", decryptedData); return (<> Check </>); } export default DecryptEncrypt; I'm encountering some issues in ensuring compatibility between frontend and backedn. Specifically, I'm struggling with properly deriving the key and IV, and encrypting/decrypting the data in a way that matches the backend implementation. Getting error as below when i try to send encrypted text to backend where it throws following error while decrypting, packages\Crypto\Cipher\_mode_cbc.py", line 246, in decrypt raise ValueError("Data must be padded to %d byte boundary in CBC mode" % self.block_size) ValueError: Data must be padded to 16 byte boundary in CBC mode I m bit new to implementing AES in a fullstack app, so learning and trying but still stuck with this issue. Could someone who has encountered similar issue or implemented encryption/decryption in JavaScript offer some guidance or suggestions on how to modify my frontend code to achieve compatibility with the backend?
|javascript|python|encryption|aes|cryptojs|
I can't change volume of playing music with slider. I tried to change volume with audio_output, but it doesn't work. ``` import sys from PyQt6.QtCore import Qt, QUrl from PyQt6.QtMultimedia import QMediaPlayer, QAudioOutput from PyQt6.QtWidgets import QApplication, QWidget, QPushButton, QSlider, QVBoxLayout, QHBoxLayout, QLabel class MusicPlayer(QWidget): def __init__(self): super().__init__() self.setWindowTitle("Музыкальный плеер") self.setGeometry(100, 100, 400, 200) self.initUI() self.initPlayer() def initPlayer(self): self.player = QMediaPlayer() self.audio_output = QAudioOutput() self.player.setAudioOutput(self.audio_output) file_name = "song.mp3" self.player.setSource(QUrl.fromLocalFile(file_name)) self.audio_output.setVolume(50) self.player.play() def initUI(self): self.play_button = QPushButton("Play") self.play_button.clicked.connect(self.play_music) self.pause_button = QPushButton("Pause") self.pause_button.clicked.connect(self.pause_music) self.stop_button = QPushButton("Stop") self.stop_button.clicked.connect(self.stop_music) self.volume_slider = QSlider(Qt.Orientation.Horizontal) self.volume_slider.setValue(50) self.volume_slider.setMaximum(100) self.volume_slider.setToolTip("Volume") self.volume_slider.valueChanged.connect(self.set_volume) self.track_label = QLabel("Название трека") vbox = QVBoxLayout() hbox = QHBoxLayout() hbox.addWidget(self.play_button) hbox.addWidget(self.pause_button) hbox.addWidget(self.stop_button) hbox.addWidget(self.volume_slider) vbox.addWidget(self.track_label) vbox.addLayout(hbox) self.setLayout(vbox) def play_music(self): self.player.play() def pause_music(self): self.player.pause() def stop_music(self): self.player.stop() def set_volume(self): self.volume = self.volume_slider.value() print(self.volume) print(type(self.volume)) self.audio_output.setVolume(self.volume) app = QApplication(sys.argv) playerM = MusicPlayer() playerM.show() sys.exit(app.exec()) ```
|javascript|ruby-on-rails|tooltip|amcharts|
Whether a type is considered statically or dynamically sized type depends on whether we know its size at _compile_ time. For example, we know that an `i32` is 4 bytes in size, and we know this at compile time, so this is a statically sized type. We _do_ know the size of a slice when we produce it, but that happens at _run_ time. The exact same code can produce different sizes of slice, so we have to consider it dynamically sized, since we can't know how much space to allocate for it when we're compiling. Dynamically sized types are often allocated on the heap and are stored behind a pointer, which allows the compiler to allocate an appropriate amount of space at compile time (for the pointer). In such a case, the compiler allocates space for the pointer, and then the memory the pointer points to (the memory for the dynamically sized type) is allocated at runtime.
I am new to Kivymd. I have managed to create a testing mobile app with the help of online resources. However, when attempting to convert the main.py file to an APK file using Google Colab notebook, I encountered an error and was unable to generate the mobile app APK file. What is the correct process for converting the Kivymd main.py file to an APK file?
I have 3 tables: users, roles and user_role (link table) I need to get all the user’s roles in a readable form, that is, using the connection table, pull out everything I need from the roles table for a specific user For this I use: ``` public function roles() { return $this->belongsToMany(RolesModel::class, 'user_role', 'user_id', 'role_id'); } ``` At the output I get an empty array, although there is definitely data in the database I checked for data availability this way: ``` $user_role = UserRoleModel::where('user_id', $this->id)->first(); $role = RolesModel::where('_id', $user_role->role_id)->first(); ``` And the result was the role I needed What am I doing wrong in the belongsToMany() query?
belongsToMany and mongodb Laravel