instruction
stringlengths
0
30k
โŒ€
null
I found the answer. I have a list of of packages in CMake via vcpkg. In these packages Boost is installed (v1.82). I also have a local, system-wide installation (v1.74). The test had not linked to the project boost (v1.82), and instead linked to the system version. Adding the vcpkg boost install path in CMake fixed the problem.
This procedure proposed by **@Spectral Instance** can be shortened a bit, but it is important whether both the source and destination ranges are non-continuous or only the target. I give two proposals suitable for each of these cases. Sub filteredCopyPaste2() ' single loop, source range is continuous Dim source As Range, destination As Range Dim cell As Range, i As Long, width As Integer On Error Resume Next Set source = Application.InputBox("Select the range* to be copied" + vbNewLine _ & "* include the header(s)", "Source data...", , , , , , 8) If source Is Nothing Then Exit Sub width = source.Columns.Count tryAgain: Set destination = Application.InputBox("Select the range* to be pasted" & vbNewLine _ & "* include the header(s)", "Destination data...", , , , , , 8) If destination Is Nothing Then Exit Sub If destination.Columns.Count <> width Then MsgBox "The area to be pasted must be of the same width" & vbNewLine & _ " as the area from which data are being copied", vbOKOnly + vbExclamation, "Wrong size!" GoTo tryAgain End If On Error GoTo 0 Set source = source.Offset(1, 0).Resize(source.Rows.Count - 1, width) ' continuous range Set destination = destination.Offset(1, 0).Resize(destination.Rows.Count - 1, width).SpecialCells(xlCellTypeVisible) If source.Cells.Count <> destination.Cells.Count Then MsgBox "The number of filtered cells in the source range differs from" & vbNewLine & _ " the number of filtered cells in the destination range.", vbOKOnly + vbCritical, "Unequal ranges selected!" Exit Sub End If i = 1 ' it is strange, however it works For Each cell In destination.Rows cell.Value = source.Rows(i).Value i = i + 1 Next cell End Sub Sub filteredCopyPaste3() ' two loops, both ranges filtered Dim source As Range, destination As Range Dim addresses() As String Dim cell As Range, i As Long, width As Integer On Error Resume Next Set source = Application.InputBox("Select the range* to be copied" + vbNewLine _ & "* include the header(s)", "Source data...", , , , , , 8) If source Is Nothing Then Exit Sub width = source.Columns.Count tryAgain: Set destination = Application.InputBox("Select the range* to be pasted" & vbNewLine _ & "* include the header(s)", "Destination data...", , , , , , 8) If destination Is Nothing Then Exit Sub If destination.Columns.Count <> width Then MsgBox "The area to be pasted must be of the same width" & vbNewLine & _ " as the area from which data are being copied", vbOKOnly + vbExclamation, "Wrong size!" GoTo tryAgain End If On Error GoTo 0 Set source = source.Offset(1, 0).Resize(source.Rows.Count - 1, width).SpecialCells(xlCellTypeVisible) Set destination = destination.Offset(1, 0).Resize(destination.Rows.Count - 1, width).SpecialCells(xlCellTypeVisible) If source.Cells.Count <> destination.Cells.Count Then MsgBox "The number of filtered cells in the source range differs from" & vbNewLine & _ " the number of filtered cells in the destination range.", vbOKOnly + vbCritical, "Unequal ranges selected!" Exit Sub End If ReDim addresses(1 To source.Count / width) ' total rows count i = 1 ' it is strange, however it works For Each cell In source.Rows addresses(i) = cell.Address(External:=True) i = i + 1 Next cell i = 1 For Each cell In destination.Rows Range(addresses(i)).Copy cell i = i + 1 Next cell End Sub
It is not possible to use PXTransactionScope in Acumatica test SDK. Reason for that is that PXTransactionScope is executed inside of Acumatica xRP framework, and wasn't build with Test SDK in mind.
Swiss-sched. help! please I am working on scheduling 8 showcases for the year. I have dataframes for each showcase that have rank and conference from where each player is from. Each showcase has a different number of players registered but it is always a different number of players. Ex. 48, 20 players. There can be some players that participate in multiple showcases or all 8. The ranks never change. They are set at the beginning of the year. In each showcase there are 3 rounds and all players have to play one game in each round. Players cannot play each other more than once throughout the entire year and cannot play another player from the same conference. The matches for players are to be determined by similar rankings. I've been trying to use a swiss system to schedule the games in python and I am able to generate out but it is not consistent as not all opponents are matched up in each round. I believe it is because we have an extra constraint that being 'conferences' where in a regular swiss system it is only constrained by 'rank'. The system has to be constrained by both 'rank' and 'conference'. Does anyone have any suggestions on any packages or types of algorithms that I could use? Or if you think there is a better way to tackle this problem. Thanks!!!
The below seems to provide a viable alternative version. Two parts: 1. Simplify code 2. Discuss, but not resolve, occasional occurrence of the specific error mentioned The simplified code below seems to provide expected response for the 'hotel' tag; and for the 'motel' tag only a future warning -- "osmnx/features.py:1030: FutureWarning: <class 'geopandas.array.GeometryArray'>._reduce will require a `keepdims` parameter in the future gdf.dropna(axis="columns", how="all", inplace=True)". ```Python def fetch_tourism_features(tag): cities = ['Aarau', 'Acquarossa'] tags = {"tourism" :f'{tag}'} gdf = ox.features_from_place([{"city": city, "country": "Switzerland", "countrycodes": "ch"} for city in cities], tags) return gdf hotels = fetch_tourism_features('hotel') motels = fetch_tourism_features('motel') ``` 1. Simplify code: As shown in the OSMnx example notebook: ['Download Any OSM Geospatial Features with OSMnx']( https://github.com/gboeing/osmnx-examples/blob/main/notebooks/16-download-osm-geospatial-features.ipynb) one can use directly 'ox.features_from_place()' to fetch OSM features as in its example: ```Python # get everything tagged amenity, # and everything tagged landuse = retail or commercial, # and everything tagged highway = bus_stop tags = {"amenity": True, "landuse": ["retail", "commercial"], "highway": "bus_stop"} gdf = ox.features_from_place("Piedmont, California, USA", tags) gdf.shape ``` 2. As for the error message, it's listed in the OSMnx (1.9.1 Internals Reference' [osmnx._errors module](https://osmnx.readthedocs.io/en/stable/internals-reference.html#osmnx-errors-module) -- and does occur in some queries (just a few ad hoc ones tested; not enough to look for any pattern): ``` exception osmnx._errors.InsufficientResponseError Exception for empty or too few results in server response. ``` Note: Initial inspiration for using list comprehensions directly in OSMnx queries: https://stackoverflow.com/a/71278021 Anyway hope this is of some help
I'm following [this][1] article to create a Power BI report from Fabric enabled workspace. I've tried this in both Free trial and have one premium fabric capacity. I believe after Lakehouse is created it should add default SQL Analytics endpoint and Semantic model after I upload a csv file with **New Dataflow Gen2**. But this doesn't happen. Also, the button to add *New Semantic Model* manually is disabled for me. See below image for reference. [![New Semantic Model disabled and Retry not working][2]][2] Appreciate any help. [1]: https://learn.microsoft.com/en-us/fabric/data-engineering/tutorial-build-lakehouse [2]: https://i.stack.imgur.com/8Tagl.png
SQL analytics endpoint and Semantic model not being created in MS Fabric Lakehouse
|powerbi|microsoft-fabric|data-lakehouse|
pd.crosstab(index=df1.Grp,columns=df1.Category,values=df1.X,aggfunc='sum',normalize="index").stack().rename("X_ratio").reset_index() Grp Category X_ratio 0 1 A 0.125 1 1 B 0.625 2 1 C 0.250 3 2 A 0.600 4 2 B 0.400 5 2 C 0.000 6 3 A 0.300 7 3 B 0.000 8 3 C 0.700
I am learning programming and I just started to create a simple google chrome extension. I am trying to call a function from another function, but I get this error from chrome console. Uncaught ReferenceError: check is not defined at alertMessage (<anonymous>:2:5) at <anonymous>:5:5 My program starts by clicking my tab on context menu. Here is my code ``` chrome.runtime.onInstalled.addListener(function (details) { const parent = chrome.contextMenus.create({ id: "alert", title: "alertChrome", contexts: ["all"], }); }); /* ใ‚ณใƒณใƒ†ใ‚ญใ‚นใƒˆใƒกใƒ‹ใƒฅใƒผใŒใ‚ฏใƒชใƒƒใ‚ฏใ•ใ‚ŒใŸๆ™‚ใฎๅ‡ฆ็† */ chrome.contextMenus.onClicked.addListener((info, tab) => { switch (info.menuItemId) { case "alert": chrome.scripting.executeScript({ target: { tabId: tab.id }, function: alertMessage, }); break; } }); function alertMessage() { if(check){ alert('Hello World'); } } function check(){ return true; } ``` Why function check() cannot be called from alertMessage? Is there a way to make this work? I tried running on google chrome console (pasting the code above on console) and it worked, so I believe it is a problem caused by chrome. I did a lot of research, but I could not find any article that mentions about this simple problem, so I think I am missing something basic.
How to call a function in javascript for google chrome extension?
|javascript|google-chrome-extension|
null
{"Voters":[{"Id":380384,"DisplayName":"John Alexiou"}],"DeleteType":1}
I am learning programming and I just started to create a simple google chrome extension. I am trying to call a function from another function, but I get this error from chrome console. Uncaught ReferenceError: check is not defined at alertMessage (<anonymous>:2:5) at <anonymous>:5:5 My program starts by clicking my tab on context menu. Here is my code ``` chrome.runtime.onInstalled.addListener(function (details) { const parent = chrome.contextMenus.create({ id: "alert", title: "alertChrome", contexts: ["all"], }); }); chrome.contextMenus.onClicked.addListener((info, tab) => { switch (info.menuItemId) { case "alert": chrome.scripting.executeScript({ target: { tabId: tab.id }, function: alertMessage, }); break; } }); function alertMessage() { if(check){ alert('Hello World'); } } function check(){ return true; } ``` Why function check() cannot be called from alertMessage? Is there a way to make this work? I tried running on google chrome console (pasting the code above on console) and it worked, so I believe it is a problem caused by chrome. I did a lot of research, but I could not find any article that mentions about this simple problem, so I think I am missing something basic.
The following command will display the current proces that is has an active media session. a.k.a. is playing music/video adb shell dumpsys media_session | perl -0777 -ne 'print "$1\n" if /sessions:\s+(\w+)(?=.*state=3)/s' It will display for example: spotify or netflix
I am trying to integrate vscode settings.json into webstrom. I have a settings.json into vscode, When I save files, its automatically formatted code into vscode, How can I interrogate this formatting into webstorm? For example, here is a settings.json in vscode? ``` { "eslint.validate": [ "javascript" ], "eslint.format.enable": true, "eslint.alwaysShowStatus": true, "editor.formatOnSave": false, "editor.tabSize": 2, "stylelint.validate": [ "scss", "css", "less" ], "css.validate": false, "scss.validate": false, "stylelint.config": null, "editor.codeActionsOnSave": { "source.fixAll.eslint": "explicit", "source.fixAll": "explicit" } } ```
How to integrate vscode settings.json into webstrom?
|javascript|reactjs|visual-studio-code|webstorm|
Let assume I have two parquet file aka main and updates with some data as shown below. I need to implement upsert kind of operation in duck db. parquet file main: id, name, city data: id name city 1 a p 2 b q 3 c r parquet file updates: id, name, city data: id name city 1 a m 4 b q desired output:- id name city 1 a m <----update city 2 b q 3 c r 4 b q <----insert currently I am doing the same using below queries:- create table main as select * from '/tmp/main.parquet'; create table stage as select * from '/tmp/updates.parquet'; delete from main using stage where main.id=stage.id; insert into main select * from stage; COPY main TO '/tmp/final.parquet' (FORMAT 'PARQUET', CODEC 'ZSTD'); but only thing is create table will load and keep all the data in memory what I don't want as the main file may contain 8-10 million records, is there any way where I can achive the same using joins only and avoid creating main and stage tables.
Upsert using DuckDB
|mysql|apache-spark|data-analysis|duckdb|
|mysql|mysql-workbench|
I have written a program that intends to add songs to my own spotify playlist. The below is the auth code: <!-- begin snippet: js hide: false console: true babel: false --> <!-- language: lang-js --> const { SpotifyWebApi } = require('spotify-web-api-node'); module.exports = async (req, res) => { const spotifyApi = new SpotifyWebApi({ clientId: process.env.SPOTIFY_CLIENT_ID, clientSecret: process.env.SPOTIFY_CLIENT_SECRET, redirectUri: `${process.env.VERCEL_URL}/api/callback`, }); const scopes = ['playlist-read-private', 'playlist-read-collaborative', 'playlist-modify-public', 'playlist-modify-private', 'user-read-playback-state', 'user-modify-playback-state', 'user-read-currently-playing', 'playlist-read-collaborative', 'user-read-playback-position', 'user-library-modify']; const authorizeURL = spotifyApi.createAuthorizeURL(scopes, null); res.writeHead(302, { Location: authorizeURL }); res.end(); }; <!-- end snippet --> While you'd think I'd only need playlist-modify-public and private, I included them all after testing to make sure. The /callback function returns the refresh token which I include in my code. Yet, when I try ```await spotifyApi.addTracksToPlaylist(playlistId, [`spotify:track:${songId}`]);```, I get the following error: ```"An error occurred while communicating with Spotify's Web API.\nDetails: Insufficient client scope."``` I don't see how I can have the incorrect client scope?? I've made sure the tokens are correct. I don't know what to do.
* What went wrong: A problem occurred configuring project ':cloud_firestore'. > Could not resolve all files for configuration ':cloud_firestore:classpath'. > Could not download builder-7.0.2.jar (com.android.tools.build:builder:7.0.2) > Could not get resource 'https://dl.google.com/dl/android/maven2/com/android/tools/build/builder/7.0.2/builder-7.0.2.jar'. > Could not GET 'https://dl.google.com/dl/android/maven2/com/android/tools/build/builder/7.0.2/builder-7.0.2.jar'. > The server may not support the client's requested TLS protocol versions: (TLSv1.2, TLSv1.3). You may need to configure the client to allow other protocols to be used. See: https://docs.gradle.org/7.4/userguide/build_environment.html#gradle_system_properties > Remote host terminated the handshake > Failed to notify project evaluation listener. > Could not get unknown property 'android' for project ':cloud_firestore' of type org.gradle.api.Project. > Could not find method implementation() for arguments [project ':firebase_core'] on object of type org.gradle.api.internal.artifacts.dsl.dependencies.DefaultDependencyHandler. > Could not get unknown property 'android' for project ':cloud_firestore' of type org.gradle.api.Project. I try to upgrade the dependencies flutter pub upgrade
Hi, there is an error happened when I build my flutter app, after I'm installing firebase packages occurs that error
|android|ios|flutter|firebase|dart|
null
You've used `struct Square` where you should have used `struct square` in the `Box` definition. Corrected: ```c typedef struct box { struct square** squares; /* array of Squares */ // ^ int numbers; int possible[9]; int solvable; struct box* next; // box, not Box } Box; ``` Another option is to `typedef` `Square` before `Box` and use `Square` in `Box`: ```c typedef struct square Square; typedef struct box Box; struct box { Square** squares; /* array of Squares */ int numbers; int possible[9]; int solvable; Box* next; }; ``` Note that there is nothing called `struct Square` after these definitions. There is `struct square` and `Square`.
**Problem** * Merge `fr` and `events` based on a match between `fr['Date']` and the exact or *next* date in `events['Earnings_Date']` (i.e. looking forward), grouped by column 'Symbol'. Keep only the first match. **Setup** Let's add 2 symbols (one expecting a match, one expecting zero). Also, it is perhaps easier to use [`pl.Expr.str.to_date`](https://docs.pola.rs/py-polars/html/reference/expressions/api/polars.Expr.str.to_date.html) instead of your [`pl.Expr.str.strptime`](https://docs.pola.rs/py-polars/html/reference/expressions/api/polars.Expr.str.strptime.html). * `fr` ```python import polars as pl fr = ( pl.DataFrame( { 'Symbol': ['A', 'A', 'A', 'B', 'B', 'C'], 'Date': ['2010-08-29', '2010-09-01', '2010-11-30', '2010-09-05', '2010-12-01', '2010-09-01'], } ) .with_columns(pl.col('Date').str.to_date('%Y-%m-%d')) .set_sorted(('Symbol', 'Date')) ) fr shape: (6, 2) โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” โ”‚ Symbol โ”† Date โ”‚ โ”‚ --- โ”† --- โ”‚ โ”‚ str โ”† date โ”‚ โ•žโ•โ•โ•โ•โ•โ•โ•โ•โ•ชโ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•ก โ”‚ A โ”† 2010-08-29 โ”‚ โ”‚ A โ”† 2010-09-01 โ”‚ โ”‚ A โ”† 2010-11-30 โ”‚ โ”‚ B โ”† 2010-09-05 โ”‚ โ”‚ B โ”† 2010-12-01 โ”‚ โ”‚ C โ”† 2010-09-01 โ”‚ โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ ``` * `events` ```python events = ( pl.DataFrame( { 'Symbol': ['A', 'A', 'B'], 'Earnings_Date': ['2010-06-01', '2010-09-01', '2010-12-01'], 'Event': [1, 4, 7], } ) .with_columns(pl.col('Earnings_Date').str.to_date('%Y-%m-%d')) .set_sorted(('Symbol', 'Earnings_Date')) ) events shape: (3, 3) โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” โ”‚ Symbol โ”† Earnings_Date โ”† Event โ”‚ โ”‚ --- โ”† --- โ”† --- โ”‚ โ”‚ str โ”† date โ”† i64 โ”‚ โ•žโ•โ•โ•โ•โ•โ•โ•โ•โ•ชโ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•ชโ•โ•โ•โ•โ•โ•โ•โ•ก โ”‚ A โ”† 2010-06-01 โ”† 1 โ”‚ โ”‚ A โ”† 2010-09-01 โ”† 4 โ”‚ โ”‚ B โ”† 2010-12-01 โ”† 7 โ”‚ โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ ``` **Code** ```python fr = ( fr.join_asof( events, left_on='Date', right_on='Earnings_Date', strategy='forward', by='Symbol' ) .with_columns( pl.when(pl.struct('Symbol', 'Earnings_Date').is_first_distinct()) .then(pl.col('Earnings_Date', 'Event')) ) ) shape: (6, 4) โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” โ”‚ Symbol โ”† Date โ”† Earnings_Date โ”† Event โ”‚ โ”‚ --- โ”† --- โ”† --- โ”† --- โ”‚ โ”‚ str โ”† date โ”† date โ”† i64 โ”‚ โ•žโ•โ•โ•โ•โ•โ•โ•โ•โ•ชโ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•ชโ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•ชโ•โ•โ•โ•โ•โ•โ•โ•ก โ”‚ A โ”† 2010-08-29 โ”† 2010-09-01 โ”† 4 โ”‚ โ”‚ A โ”† 2010-09-01 โ”† null โ”† null โ”‚ โ”‚ A โ”† 2010-11-30 โ”† null โ”† null โ”‚ โ”‚ B โ”† 2010-09-05 โ”† 2010-12-01 โ”† 7 โ”‚ โ”‚ B โ”† 2010-12-01 โ”† null โ”† null โ”‚ โ”‚ C โ”† 2010-09-01 โ”† null โ”† null โ”‚ โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ ``` **Explanation** * Use [`pl.DataFrame.join_asof`](https://docs.pola.rs/py-polars/html/reference/dataframe/api/polars.DataFrame.join_asof.html) with `strategy='forward'`. * Next, inside [`ppl.with_columns`](https://docs.pola.rs/py-polars/html/reference/dataframe/api/polars.DataFrame.with_columns.html) apply [`pl.when`](https://docs.pola.rs/py-polars/html/reference/expressions/api/polars.when.html) to set duplicates to `None` (`null`): * Use [`pl.struct`](https://docs.pola.rs/py-polars/html/reference/expressions/api/polars.struct.html) to create a single 'key' for the combination `['Symbol', 'Earnings_Date']` and check [`pl.Expr.is_first_distinct`](https://docs.pola.rs/py-polars/html/reference/expressions/api/polars.Expr.is_first_distinct.html). * Where `True` we want to keep the values for `['Earnings_Date', 'Event']`, so we can pass [`pl.col`](https://docs.pola.rs/py-polars/html/reference/expressions/col.html) to `.then`. Where `False`, we will get `None`.
Receiving Notifications for Individual Task Completion OmniThreadLibrary Parallel.ForEach
|multithreading|delphi|omnithreadlibrary|
null
Use web.find_element(By.XPATH, "xpath") Instead of web.find_element_by_xpath("xpath") Don't forget to add from selenium.webdriver.common.by import By For more reference refer to [this][1]. [1]: https://www.geeksforgeeks.org/find_element_by_xpath-driver-method-selenium-python/
I was trying to replicate this [repository](https://github.com/sangminkim-99/Sketch-Guided-Text-To-Image/tree/main) based on a Google Research Paper. I am facing issues with Training the Latent Edge Predictor for `batch_size > 1`. There are some changes which I made to the code and some issues. I shall be helpful if the community could help me clear them. **Issue 1:** File: `commands/train_LEP.py` Line 81 Why is `torch.cat([latent_image] * 2` passed as a parameter instead of simply passing `latent_image`? **Issue 2** File: `commands/train_LEP.py` Lines 78 and 93 Why is `batch_size*2` passed as a parameter instead of just `batch_size`? **Issue 3** I always get some dimensionality issue (mismatch of tensor dimensions) when I try to train the LEP with `batch_size>1`. As a result I made some changes to the code, observing the inaccuracy in tensor dimensions of `noise_level`, `pred_edge_map`. This now matches the size of tensors wherever required, but the batch size issue is still not resolved. Please find below the updated code: **UPDATED `train_LEP.py`** ``` import os import math from diffusers import StableDiffusionPipeline from einops import rearrange import numpy as np import torch from tqdm import tqdm from transformers import CLIPTokenizer import typer from typing import List from typing_extensions import Annotated from internals.diffusion_utils import encode_img, encode_text, hook_unet, noisy_latent from internals.latent_edge_predictor import LatentEdgePredictor from internals.LEP_dataset import LEPDataset def train_LEP( model_id: Annotated[str, typer.Option()] = "CompVis/stable-diffusion-v1-4", device: Annotated[str, typer.Option()] = "cuda:1", dataset_dir: Annotated[str, typer.Option(help="path to the parent directory of image data")] = "./data/imagenet/imagenet_images", edge_map_dir: Annotated[str, typer.Option(help="path to the parent directory of edge map data")] = "./data/imagenet/edge_maps", save_path: Annotated[str, typer.Option(help="path to save LEP model")] = "./output/LEP.pt", batch_size: Annotated[int, typer.Option(help="batch size for training LEP. Decrease this if OOM occurs.")] = 1, training_step: Annotated[int, typer.Option()] = 4633, lr: Annotated[float, typer.Option()] = 1e-4, # not specified in the paper num_train_timestep: Annotated[int, typer.Option(help="maximum diffusion timestep")] = 250, # not specified in the paper ): ''' Train the Latent Edge Predictor. ''' # create output folder os.makedirs(os.path.dirname(save_path), exist_ok=True) # create dataset & loader dataset = LEPDataset(dataset_dir, edge_map_dir) dataloader = torch.utils.data.DataLoader(dataset, batch_size=batch_size, shuffle=True) # initialize stable diffusion pipeline. # the paper use stable-diffusion-v1.4 pipe = StableDiffusionPipeline.from_pretrained(model_id, safety_checker=None, requires_safety_checker = False).to(device) unet = pipe.unet unet.enable_xformers_memory_efficient_attention() # hook the feature_blocks of unet feature_blocks = hook_unet(pipe.unet) # initialize LEP LEP = LatentEdgePredictor(input_dim=9324, output_dim=4, num_layers=10).to(device) pipe.unet.eval() pipe.vae.eval() pipe.text_encoder.eval() # need this lines? pipe.unet.requires_grad_(False) pipe.text_encoder.requires_grad_(False) LEP.requires_grad_(True) # load clip tokenizer tokenizer = CLIPTokenizer.from_pretrained("openai/clip-vit-large-patch14") optimizer = torch.optim.Adam(LEP.parameters(), lr=lr) criterion = torch.nn.MSELoss() train_epochs = 10 max_train_steps = train_epochs * len(dataloader) num_update_steps_per_epoch = len(dataloader) num_train_epochs = math.ceil(max_train_steps / num_update_steps_per_epoch) progress_bar = tqdm( range(1, max_train_steps), smoothing=0, desc="steps", position=0, leave=True ) for epoch in range(num_train_epochs): progress_bar.set_description_str(f"Epoch {epoch+1}/{num_train_epochs}") loss_total = 0 for step, batch in enumerate(dataloader): image, edge_map, caption = batch[0], batch[1], batch[2] optimizer.zero_grad() # image to latent latent_image = encode_img(pipe.vae, image) latent_edge = encode_img(pipe.vae, edge_map) latent_edge = latent_edge.transpose(1,3) caption_embedding = torch.cat([encode_text(pipe.text_encoder, tokenizer, c) for c in caption]) noisy_image, noise_level, timesteps = noisy_latent(latent_image, pipe.scheduler, batch_size , num_train_timestep) # one reverse step to get the feature blocks pipe.unet(torch.cat([latent_image] * 2), timesteps, encoder_hidden_states=caption_embedding) activations = [] for block in feature_blocks: activations.append(block.output) block.output = None features = activations assert all([isinstance(acts, torch.Tensor) for acts in features]) size = latent_image.shape[2:] resized_activations = [] for acts in features: acts = torch.nn.functional.interpolate(acts, size=size, mode="bilinear") acts = acts[:1] acts = acts.transpose(1,3) resized_activations.append(acts) intermediate_result = torch.cat(resized_activations, dim=3) intermediate_result = intermediate_result.transpose(1,3) pred_edge_map = LEP(intermediate_result, noise_level) pred_edge_map = rearrange(pred_edge_map, "(b w h) c -> b h w c", b=batch_size, h=latent_edge.shape[1], w=latent_edge.shape[2]) # calculate MSE loss loss = criterion(pred_edge_map, latent_edge) loss.backward() optimizer.step() current_loss = loss.detach().item() loss_total += current_loss avr_loss = loss_total / (step + 1) if step % 10 == 0: progress_bar.set_description(f"Loss: {avr_loss:.3f}") if step >= max_train_steps: break step += 1 if step >= training_step: print(f'Finish to optimize. Save file to {save_path}, Epoch = {epoch+1}') path = "./output/LEP-" + str(epoch+1) + ".pt" torch.save(LEP.state_dict(), path) ``` **Updated `internals/diffusion_utils.py`** ``` from diffusers import AutoencoderKL, UNet2DConditionModel import torch from transformers.models.clip import CLIPTextModel, CLIPTokenizer def encode_img(vae: AutoencoderKL, image: torch.Tensor): generator = torch.Generator(vae.device).manual_seed(0) latents = vae.encode(image.to(device=vae.device, dtype=vae.dtype)).latent_dist.sample(generator=generator) latents = latents * 0.18215 return latents def encode_text(text_encoder: CLIPTextModel, tokenizer: CLIPTokenizer, text): text_input = tokenizer([text], padding="max_length", max_length=tokenizer.model_max_length, truncation=True, return_tensors="pt") with torch.no_grad(): text_embeddings = text_encoder(text_input.input_ids.to(text_encoder.device))[0] max_length = text_input.input_ids.shape[-1] uncond_input = tokenizer([""], padding="max_length", max_length=max_length, return_tensors="pt") with torch.no_grad(): uncond_embeddings = text_encoder(uncond_input.input_ids.to(text_encoder.device))[0] # return torch.cat([uncond_embeddings, text_embeddings]).unsqueeze(0) return torch.cat([uncond_embeddings, text_embeddings]) def noisy_latent(image, noise_scheduler, batch_size, num_train_timestep): timesteps = torch.randint(0, num_train_timestep, (batch_size,), dtype=torch.int64, device=image.device).long() noise = torch.randn_like(image, device=image.device) alphas_cumprod = noise_scheduler.alphas_cumprod[timesteps.cpu()].to(image.device) # print("alpha_prod = ", alphas_cumprod) sqrt_alpha_prod = alphas_cumprod ** 0.5 sqrt_alpha_prod = sqrt_alpha_prod.flatten() while len(sqrt_alpha_prod.shape) < len(image.shape): sqrt_alpha_prod = sqrt_alpha_prod.unsqueeze(-1) sqrt_one_minus_alpha_prod = (1 - alphas_cumprod) ** 0.5 sqrt_one_minus_alpha_prod = sqrt_one_minus_alpha_prod.flatten() while len(sqrt_one_minus_alpha_prod.shape) < len(image.shape): sqrt_one_minus_alpha_prod = sqrt_one_minus_alpha_prod.unsqueeze(-1) noisy_samples = sqrt_alpha_prod * image + sqrt_one_minus_alpha_prod * noise noise_level = noisy_samples - (sqrt_alpha_prod * image) return noisy_samples, noise_level, timesteps def hook_unet(unet: UNet2DConditionModel): blocks_idx = [0, 1, 2] feature_blocks = [] def hook(module, input, output): if isinstance(output, tuple): output = output[0] if isinstance(output, torch.TensorType): feature = output.float() setattr(module, "output", feature) elif isinstance(output, dict): feature = output.sample.float() setattr(module, "output", feature) else: feature = output.float() setattr(module, "output", feature) # TODO: Check below lines are correct # 0, 1, 2 -> (ldm-down) 2, 4, 8 for idx, block in enumerate(unet.down_blocks): if idx in blocks_idx: block.register_forward_hook(hook) feature_blocks.append(block) # ldm-mid 0, 1, 2 for block in unet.mid_block.attentions + unet.mid_block.resnets: block.register_forward_hook(hook) feature_blocks.append(block) # 0, 1, 2 -> (ldm-up) 2, 4, 8 for idx, block in enumerate(unet.up_blocks): if idx in blocks_idx: block.register_forward_hook(hook) feature_blocks.append(block) return feature_blocks ```
Sketch Guided Text to Image Generation
|deep-learning|stable-diffusion|image-generation|
null
{"Voters":[{"Id":1431750,"DisplayName":"aneroid"},{"Id":9214357,"DisplayName":"Zephyr"},{"Id":14732669,"DisplayName":"ray"}],"SiteSpecificCloseReasonIds":[13]}
``` mpg['grade'] = np.where(mpg['total'] >= 30, 'A', np.where(mpg['total'] >= 20, 'B', 'C')) ``` code 1) ``` count_grade = mpg['grade'].value_counts() count_grade.plot.bar(rot=0) plt.show() ``` code 2) ``` count_grade = mpg['grade'].value_counts().sort_index() # method chaining count_grade.plot.bar(rot=0) plt.show() ``` reference) count_grade -> 'A' : 10, 'B' : 118, 'C' : 106 **(in VSCode)** The execution result is different with and without the code 1). When I only run code 2) without code 1), A is more than 120 instead of 10 (in graph) [enter image description here](https://i.stack.imgur.com/JRHEp.png) However, when the two codes are executed together, the result is normally output as a result of only 'A', 'B', and 'C' being sorted. [enter image description here](https://i.stack.imgur.com/sxG6B.png) **(in Colab)** ``` mpg['grade'] = np.where(mpg['total'] >= 30, 'A', np.where(mpg['total'] >=20, 'B', 'C')) count_grade = mpg['grade'].value_counts().sort_index() print(count_grade) count_grade.plot.bar(rot=0) ``` When I put this code in one block and run it, the results are output strangely. [enter image description here](https://i.stack.imgur.com/KLC1Z.png) However, running the last line separately solves the problem [enter image description here](https://i.stack.imgur.com/IMFDI.png) I'd like to know what the problem is. please help me expecting : ![enter image description here](https://i.stack.imgur.com/7u58B.png) but my result : ![enter image description here](https://i.stack.imgur.com/V2bK7.png) **mpg.head().to_dict()** ```Python model': {0: 'a4', 1: 'a4', 2: 'a4', 3: 'a4', 4: 'a4'}, 'displ': {0: 1.8, 1: 1.8, 2: 2.0, 3: 2.0, 4: 2.8}, 'year': {0: 1999, 1: 1999, 2: 2008, 3: 2008, 4: 1999}, 'cyl': {0: 4, 1: 4, 2: 4, 3: 4, 4: 6}, 'trans': {0: 'auto(l5)', 1: 'manual(m5)', 2: 'manual(m6)', 3: 'auto(av)', 4: 'auto(l5)'}, 'drv': {0: 'f', 1: 'f', 2: 'f', 3: 'f', 4: 'f'}, 'cty': {0: 18, 1: 21, 2: 20, 3: 21, 4: 16}, 'hwy': {0: 29, 1: 29, 2: 31, 3: 30, 4: 26}, 'fl': {0: 'p', 1: 'p', 2: 'p', 3: 'p', 4: 'p'}, 'category': {0: 'compact', 1: 'compact', 2: 'compact', 3: 'compact', 4: 'compact'}, 'total': {0: 23.5, 1: 25.0, 2: 25.5, 3: 25.5, 4: 21.0}, 'grade': {0: 'B', 1: 'B', 2: 'B', 3: 'B', 4: 'B'}} ``` ** my full code ** ```python import pandas as pd import matplotlib.pyplot as plt import numpy as np mpg = pd.read_csv('mpg.csv') mpg['total'] = (mpg['cty'] + mpg['hwy']) / 2 mpg['grade'] = np.where(mpg['total'] >= 30, 'A', np.where(mpg['total'] >= 20, 'B', 'C')) count_grade = mpg['grade'].value_counts() count_grade.plot.bar(rot=0) plt.show() count_grade = mpg['grade'].value_counts().sort_index() count_grade.plot.bar(rot=0) print(count_grade) plt.show() ```
i am trying designing a neural network to classify signals by a pytorch model. after training the model i save the model and load it for inference phase. i am trying designing a neural network to classify signals by a pytorch model. after training the model i save the model by the fllowing code: ``` torch.save(model.state_dict(), ".pth") ``` afterward i want to load the model for inference phase. i use the following code : ``` model_test = spectrogram_model(X_Test) model_test.load_state_dict(torch.load(".pth")) ``` but i got an error as follows: ``` AttributeError: 'Tensor' object has no attribute 'load_state_dict' ``` the content of spectrogram_model is as follows: ``` class Spectrogram(nn.Module): def __init__(self): super().__init__() self.dropout = nn.Dropout(0.04) self.hidden1 = nn.Linear(16, 12) self.act1 = nn.ReLU() self.hidden2 = nn.Linear(12, 8) self.act2 = nn.ReLU() self.hidden3 = nn.Linear(8, 4) def forward(self, x): x = self.dropout(x) x = self.act1(self.hidden1(x)) x = self.act2(self.hidden2(x)) x = self.hidden3(x) return x ``` do you have any solution?
|python|python-3.x|websocket|tornado|torchaudio|
So this is no easy barcode scanner I want it to recognize which country it is from. can someone explain to me how can I do this?? I made a barcode scanner I only need to know how to get it to recognize the country, all other things are done I have already tried making a whole list of items that tell which country they come from but it doesn't work heck the app doesn't even launch now
How To Make A Barcode Scanner In Flutter?
|flutter|helper|flutterflow|
null
Docker for Windows often uses WSL and there are some issues relating to how parts of the filesystem monitor and report changes. I found a solution to the problem and I've written an article on how to fix it here: https://dev.to/simplifycomplexity/solving-hot-reload-issues-in-vs-code-dev-containers-on-windows-with-wsl2-16d5 It might be caused by the way WSL2 monitors mounted drives for changes. There's an issue where it will not do this from within a mounted drive (I don't mean a docker volume). So my article describes the steps needed to fix the issue. I hope my work helps anyone else facing the problem.
As of pg8000 1.31.0, by default an [SSL connection will be attempted][1] using lenient settings, so it should work in the same way as psycopg. [1]: https://github.com/tlocke/pg8000#connect-to-postgresql-over-ssl
null
null
null
null
Since the below given advice works only for a specific class @Before("staticinitialization(org.mazouz.aop.Main1)") I tried to make the advice generic such that it can work for any package @Before("staticinitialization(*.*.*(..))") Im getting the below error Syntax error on token "staticinitialization(*.*.*(..))", ")" expected
Spotify Web API returning 'Insufficient client scope.' despite full client scopes
|javascript|node.js|spotify|vercel|
{"Voters":[{"Id":1534822,"DisplayName":"asdf"}]}
I'm pretty sure I have a memory leak. When I perform certain actions (e.g. opening a menu) repeatedly, then use the 3 heap snapshots trick, there's always leaked memory. The retainers are different each time. I spent 2 days trying to interpret the results, but I still have no idea what it means. E.g. here's an example of a memory leak: [![enter image description here][1]][1] It'll be great if someone knew the answers to any of these questions: 1. Is it correct to interpret this as: an `HTMLInputElement` is somehow referencing a function that calls `useContext`? 2. What do "instruction_stream", "previous", and "context" in the retainers mean? 3. I know "(compiled code)" means it's V8 creating optimized versions of functions. However, it seems like Chrome is producing new optimized versions of "useContext" multiple times? I repeated the 3 heaps trick many times and "useContext" is in there every time. 4. Where can I find more about what "(code relocation info)", "(code deopt data)", "(source position table)", etc mean? [1]: https://i.stack.imgur.com/2hAcI.png
Interpreting Chrome memory tool's results for a memory leak?
|javascript|reactjs|memory-leaks|google-chrome-devtools|
I had created html template its look good in browser and mobile. But While checking on Outlook New (Mail Outlook) Anchor Text is displayed with Anchar Url Text. My Code ``` <table class="" align="left" border="0" cellpadding="0" cellspacing="0" style="max-width:230px;" width="100%"> <tr> <td class="" valign="top" style="padding: 10px; display: block;"> <a target="_blank" href='*|ARCHIVE|*' style="display: block;" >View email in your browser</a> </td> </tr> </table> ``` Result in OutLook is : [![OutLook Screenshot][1]][1] Well in old out look its look good. [![Old OutLook Screenshot][2]][2] Any one can help me in this ? [1]: https://i.stack.imgur.com/SuN4v.png [2]: https://i.stack.imgur.com/z83DO.png
Anchor Tag href url is diplayed as [href url text]Anchor Text in Outlook
|html|
I created some code in Rust that should allow me to set recursive Ports, Port having a source, that could have a source, etc. However, due to borrow issues the only way for me to implement this structure is through RefCell, and i actually do not want to use RefCell (it allows me to compile code that will potentially panic at runtime) or any other libraries from std. The trouble is that it seems that i am unable to set a value to my Port due to borrow issues. ```rust struct Port<'a> { value: i32, source: Option<&'a Port<'a>>, } impl<'a> Port<'a> { fn new(value: i32) -> Port<'a> { Port { value, source: None } } fn link(&mut self, source: &'a Port<'a>) { self.source = Some(source); } fn get_source_value(&self) -> Option<i32> { match self.source { Some(port) => { let inner_source_value = port.get_source_value(); match inner_source_value { Some(value) => Some(value), None => Some(port.value), } } None => None, } } } fn main() { let mut top_port = Port::new(10); let mut sub_port = Port::new(20); let mut sub_sub_port = Port::new(30); sub_port.link(&top_port); sub_sub_port.link(&sub_port); top_port.value = 400; // can't do this because top_port is borrowed println!("Value of sub_sub_port's source's source's source: {:?}", sub_sub_port.get_source_value()); } ``` The trouble occurs because top_port is borrowed when sub_port and sub_sub_port are linked to it. The fact that this happens is no surprise to me and i could use RefCell and RC to go around this issue. ```rust use std::cell::RefCell; struct Port<'a> { value: i32, source: Option<&'a RefCell<Port<'a>>>, } impl<'a> Port<'a> { fn new(value: i32) -> RefCell<Port<'a>> { RefCell::new(Port { value, source: None }) } fn link(&mut self, source: &'a RefCell<Port<'a>>) { self.source = Some(source); } fn get_source_value(&self) -> Option<i32> { match self.source { Some(port_ref) => { let port = port_ref.borrow(); let inner_source_value = port.get_source_value(); match inner_source_value { Some(value) => Some(value), None => Some(port.value), } } None => None, } } } fn main() { let top_port = Port::new(10); let sub_port = Port::new(20); let sub_sub_port = Port::new(30); sub_sub_port.borrow_mut().link(&sub_port); sub_port.borrow_mut().link(&top_port); top_port.borrow_mut().value = 400; println!("Value of sub_sub_port's source's source's source: {:?}", sub_sub_port.borrow().get_source_value()); } ``` However, my goal is to not use any standard library functionality and to only use Rust in a safe way. In what way could i restructure my code to avoid having to use RefCell or any other std libraries? Or even better, could i use more lifetimes to fix my original code? Thank you in advance!
|jquery|datatables|bootstrap-5|
Handling newlines and escape sequences in web app text is like managing a mixed bag of goodies. You've got your regular text, code bits, and instructions, each needing different treatment. Think of it like sorting your laundry โ€“ regular clothes go in the washer, delicate stuff gets hand-washed, and funky fabrics need special care. So, for text, slap those <br /> tags on newlines but keep the \n's intact in code blocks. And don't forget to watch out for XSS gremlins by HTML-encoding special characters!
Next.js 14.1.4. There is a page on which a service is selected and then a form is created for this service with certain fields. For the form, I use useFormik and Yup validation. To process the submit form, I need to make requests to the CRM system on the server and create a lead there. I created a server function for this (with the use server directive). In handleSubmit on the client, I call this function with the arguments that the user has selected. The server function is not called with arguments, everything goes without them. But the task is precisely to throw arguments. I had a similar case, but the form was rendered there in advance, so to speak. Now the logic is as follows - the service selection block is displayed - when you click on the service, a form is rendered on the client. In the submit of this form, I cannot call the server function with arguments, it is called without arguments. IndexPage ``` import Manager from "@/components/manager" import Header from "@/components/header" import { getTypes } from "@/utils/requests" export default async function Home() { const types = await getTypes() return ( <> <Header/> <main> <Manager types={types}/> </main> </> ) } ``` Manager.jsx ``` 'use client' import { useContext } from 'react' import DataContext from '@/components/context/data-context' import ServiceChoice from '@/components/organisms/service-choice' import Form from '@/components/form' import InlineSVG from 'react-inlinesvg' import createFieldObject from '@/utils/create-fields-object' import createYupSchema from '@/utils/create-yup-schema' import Link from 'next/link' export default function Manager ({types}) { const { service, setService } = useContext(DataContext) if (service) { const validationSchema = createYupSchema(service?.inputs) const { fields, filesKey } = createFieldObject(service?.inputs) return ( <> <div className="instruction-container flex flex-col"> <div className="flex justify-end"> <button type='button' className='flex flex-row items-center cursor-pointer inherit-a-font' onClick={() => {setService(null)}}> ะš ะฒั‹ะฑะพั€ัƒ ัƒัะปัƒะณ <InlineSVG src='/icons/arrow-left.svg' width={35} height={25} strokeWidth={2}/> </button> </div> <p className='inherit-a-font'>ะœั‹ ั†ะตะฝะธะผ ะฒะฐัˆะต ะฒั€ะตะผั ะธ&nbsp;ัั‚ั€ะตะผะธะผัั ะพะฑะตัะฟะตั‡ะธั‚ัŒ ะฑั‹ัั‚ั€ัƒัŽ ะธ&nbsp;ัั„ั„ะตะบั‚ะธะฒะฝัƒัŽ ะพะฑั€ะฐะฑะพั‚ะบัƒ ะทะฐัะฒะพะบ. ะŸะพะถะฐะปัƒะนัั‚ะฐ, ะทะฐะฟะพะปะฝัะนั‚ะต ะฒัะต&nbsp;ะฟะพะปั ะฒ&nbsp;ั„ะพั€ะผะต ะผะฐะบัะธะผะฐะปัŒะฝะพ ะบะพั€ั€ะตะบั‚ะฝะพ ะธ&nbsp;ะฟะพะปะฝะพ. ะญั‚ะพ ะฟะพะทะฒะพะปะธั‚ ะ’ะฐะผ&nbsp;ะธะทะฑะตะถะฐั‚ัŒ ะดะพะฟะพะปะฝะธั‚ะตะปัŒะฝั‹ั… ัƒั‚ะพั‡ะฝะตะฝะธะน ะธ&nbsp;ัะพะบั€ะฐั‚ะธั‚ัŒ ะฒั€ะตะผั ะฝะฐ&nbsp;ะพะฑั€ะฐะฑะพั‚ะบัƒ ะฒะฐัˆะตะน ะทะฐัะฒะบะธ.</p> <p className='inherit-a-font'>ะ’ั‹ ะฒัะตะณะดะฐ ะผะพะถะตั‚ะต ะทะฐะดะฐั‚ัŒ ะฒะพะฟั€ะพั ะฟะพ ะทะฐะฟะพะปะฝะตะฝะธัŽ, ัะฒัะทะฐะฒัˆะธััŒ ั ะฝะฐะผะธ ะฟะพ ะฝะพะผะตั€ัƒ ั‚ะตะปะตั„ะพะฝัƒ: <Link href='tel:88005502707'>{"8-(800)-550-27-07"}</Link></p> <p style={{color: 'red'}} className='inherit-a-font'>ะŸะพะปั,&nbsp;ะฟะพะผะตั‡ะตะฝะฝั‹ะต&nbsp;{'"*"'},&nbsp;ัะฒะปััŽั‚ัั ะพะฑัะทะฐั‚ะตะปัŒะฝั‹ะผะธ ะบ&nbsp;ะทะฐะฟะพะปะฝะตะฝะธัŽ</p> </div> <Form inputs={service?.inputs} validationSchema={validationSchema} fields={fields} filesKey={filesKey}/> </> ) } return (<ServiceChoice types={types}/>) } ``` Form.jsx ``` /* eslint-disable react-hooks/rules-of-hooks */ 'use client' import { useFormik } from 'formik' import InputManager from '@/components/inputs/input-manager' import { motion } from 'framer-motion' import { getOriginalImageUrl } from '@/utils/get-image-url' import Link from 'next/link' import InlineSVG from 'react-inlinesvg' import { useContext, useState } from 'react' import DataContext from '@/components/context/data-context' import CircleLoader from '@/components/atoms/circle-loader' import { createLead } from '@/utils/bx-requests' const submitFunction = async (values, filesKey, serviceName) => { // try { console.log(values, filesKey, serviceName) const status = await createLead(values) // console.log(status) // } // catch (error) { // console.log(error) // } } export default function Form ({inputs, validationSchema, fields, filesKey}) { if (!Array.isArray(inputs)) return (<></>) const { service } = useContext(DataContext) const [isLoading, setIsLoading] = useState(false) const [isSuccess, setIsSuccess] = useState(false) const formik = useFormik({ initialValues: fields, validationSchema: validationSchema, onSubmit: (values) => {submitFunction(values, filesKey, service.name)} }) return ( <form onSubmit={formik.handleSubmit} className='flex flex-col'> <div className={`inputs-container flex flex-col ${isLoading || isSuccess ? 'disabled' : ''}`}> {inputs.map((item) => ( <div className="input-container flex flex-col" key={item.label}> <label className='flex flex-row items-center flex-wrap' style={{gap: '5px'}}> {item.label}{item.isRequired ? <span style={{fontSize: 'inherit', fontWeight: 'inherit', color: 'red'}}> * </span> : <></>} {item?.file?.data && <Link href={getOriginalImageUrl(item.file)} target='_blank' alt='ะกัั‹ะปะบะฐ ะฝะฐ ั„ะฐะนะป' className='inherit-label-font'>{`(${item.filename || "ะกัั‹ะปะบะฐ"})`}</Link>} {formik.errors[item.bitrixKey] && formik.touched[item.bitrixKey] && <motion.span initial={{opacity: 0}} animate={{opacity: 1}} className='inherit-p-font' style={{ color: 'red'}}> {formik.errors[item.bitrixKey].toLowerCase()} </motion.span> } </label> <InputManager input={item} formik={formik}/> </div> ))} </div> <button className="flex flex-row items-center" style={{alignSelf: 'flex-end'}} disabled={isSuccess || isLoading} type='submit'> <p className='inherit-input-font'>{isSuccess ? "ะฃัะฟะตัˆะฝะพ" : "ะžั‚ะฟั€ะฐะฒะธั‚ัŒ ะทะฐัะฒะบัƒ"}</p> {isLoading ? <CircleLoader/> : <InlineSVG src='/icons/upload.svg' width={30} height={20}/>} </button> </form> ) } ``` bx-requests.jsx ``` "use server" // Lead creating export async function createLead (values) { console.log('in lead creating', values) return true // requests logic } ``` I tried to pull out the form so that it is rendered on the server by creating a testPage TESTPAGE ``` import Form from "@/components/formTest"; import { getTypes } from "@/utils/requests"; export default async function Page () { const types = await getTypes() const service = types[2].attributes return ( <Form inputs={service.inputs} service={service}/> ) } ``` TESTFORM ``` /* eslint-disable react-hooks/rules-of-hooks */ 'use client' import { useFormik } from 'formik' import InputManager from '@/components/inputs/input-manager' import { motion } from 'framer-motion' import { getOriginalImageUrl } from '@/utils/get-image-url' import Link from 'next/link' import InlineSVG from 'react-inlinesvg' import { useContext, useState } from 'react' import DataContext from '@/components/context/data-context' import CircleLoader from '@/components/atoms/circle-loader' import { createLead } from '@/utils/bx-requests' import createFieldObject from '@/utils/create-fields-object' import createYupSchema from '@/utils/create-yup-schema' const submitFunction = async (values, filesKey, serviceName) => { // try { console.log(values, filesKey, serviceName) const status = await createLead(values) // console.log(status) // } // catch (error) { // console.log(error) // } } export default function Form ({inputs, service}) { const validationSchema = createYupSchema(service?.inputs) const { fields, filesKey } = createFieldObject(service?.inputs) if (!Array.isArray(inputs)) return (<></>) const [isLoading, setIsLoading] = useState(false) const [isSuccess, setIsSuccess] = useState(false) const formik = useFormik({ initialValues: fields, validationSchema: validationSchema, onSubmit: (values) => {submitFunction(values, filesKey, service.name)} }) return ( <form onSubmit={formik.handleSubmit} className='flex flex-col'> <div className={`inputs-container flex flex-col ${isLoading || isSuccess ? 'disabled' : ''}`}> {inputs.map((item) => ( <div className="input-container flex flex-col" key={item.label}> <label className='flex flex-row items-center flex-wrap' style={{gap: '5px'}}> {item.label}{item.isRequired ? <span style={{fontSize: 'inherit', fontWeight: 'inherit', color: 'red'}}> * </span> : <></>} {item?.file?.data && <Link href={getOriginalImageUrl(item.file)} target='_blank' alt='ะกัั‹ะปะบะฐ ะฝะฐ ั„ะฐะนะป' className='inherit-label-font'>{`(${item.filename || "ะกัั‹ะปะบะฐ"})`}</Link>} {formik.errors[item.bitrixKey] && formik.touched[item.bitrixKey] && <motion.span initial={{opacity: 0}} animate={{opacity: 1}} className='inherit-p-font' style={{ color: 'red'}}> {formik.errors[item.bitrixKey].toLowerCase()} </motion.span> } </label> <InputManager input={item} formik={formik}/> </div> ))} </div> <button className="flex flex-row items-center" style={{alignSelf: 'flex-end'}} disabled={isSuccess || isLoading} type='submit'> <p className='inherit-input-font'>{isSuccess ? "ะฃัะฟะตัˆะฝะพ" : "ะžั‚ะฟั€ะฐะฒะธั‚ัŒ ะทะฐัะฒะบัƒ"}</p> {isLoading ? <CircleLoader/> : <InlineSVG src='/icons/upload.svg' width={30} height={20}/>} </button> </form> ) } ``` still not working
Next.js. Server actions in form using formik. Action with arguments didnt work
|reactjs|next.js|formik|
null
You'd have to edit file `gradle/libs.versions.toml` and add in TOML format: [versions] androidx_compose_bom = '2024.03.00' androidx_compose_uitest = '1.6.4' androidx_media3 = '1.3.0' # ... [libraries] androidx_compose_bom = { module = "androidx.compose:compose-bom", version.ref = "androidx_compose_bom" } androidx_compose_uitest = { module = "androidx.compose.ui:ui-test-junit4", version.ref = "androidx_compose_uitest" } androidx_media3_exoplayer = { module = "androidx.media3:media3-exoplayer", version.ref = "androidx_media3" } androidx_media3_exoplayer_dash = { module = "androidx.media3:media3-exoplayer-dash", version.ref = "androidx_media3" } androidx_media3_ui = { module = "androidx.media3:media3-ui", version.ref = "androidx_media3" } # ... And one can even bundle these (optional): [bundles] androidx_media3 = ["androidx_media3_exoplayer", "androidx_media3_exoplayer_dash", "androidx_media3_ui"] Which means, you can't just copy & paste, but have to convert to TOML.<br/> Be aware that for BOM dependencies, this only works for the BOM itself.<br/> When there's no version number, one can use: `//noinspection UseTomlInstead`. The names of the definitions of the default empty activity app are kind of ambiguous, since they're not explicit enough. There `androidx` should better be called `androidx_compose`, where applicable... because eg. `libs.androidx.ui` does not provide any understandable meaning (low readability), compared to `libs.androidx.compose.ui`. Proper and consistent labeling is important there. --- Once added there, one can use them in `build.gradle` or `build.gradle.kts`: implementation(libs.androidx.media3.exoplayer) implementation(libs.androidx.media3.exoplayer.dash) implementation(libs.androidx.media3.ui) Or by the bundle: implementation(libs.bundles.androidx.media3) Further reading: - [Sharing dependency versions between projects](https://docs.gradle.org/current/userguide/platforms.html) - [Migrate your build to version catalogs](https://developer.android.com/build/migrate-to-catalogs)
Troubleshooting Airflow Task Failures: Slack Notification Timeout
I want to know if it's safe to store data received from $\_POST, $\_GET without cleaning them before inserting into the database, only performing some validation to check if the content is in the expected format. For example, I have a comment system, and these comments cannot exceed 3000 characters, so I validate to ensure the comment is not empty or longer than 3000 characters. When needed, I also validate to see if it's an integer, email, or URL, but I never filter the input using filters like 'FILTER_SANITIZE_STRING' because they erase part of the content. I directly insert the values from $\_POST or $\_GET into the database using PDO. **An example of how I'm doing it, I'd like to know if it's safe.** ``` <? include_once('connection.php'); //Pre validation $comment = isset($_POST['comment']) ? $_POST['comment'] : null; if(empty($comment)){ echo json_encode( ['error' => 'This is empty']); die(); } if(mb_strlen($comment, 'UTF-8') > 3000){ echo json_encode( ['error' => 'Very big']); die(); } // Insert $insert = sql($db, "INSERT INTO comments(comment) VALUES (?)", array($comment), "lastid"); // Select $query = sql($db, "SELECT * FROM comments WHERE id = ?", array($insert), "rows"); echo htmlspecialchars($query['comment'], ENT_QUOTES, 'UTF-8'); ``` **connection.php** ``` <? define("HOST", 'localhost'); define("USER", 'root'); define("PASS", '32Tx89,ccclkt80@'); define("NAME", 'mydb'); //try connect try { $db = new PDO("mysql:host=".HOST.";dbname=".NAME.";charset=utf8mb4", "".USER."", "".PASS.""); $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC); $db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false); }catch(PDOException $e) { die("Error connecting to database"); } function sql($db, $q, $params, $return) { try { //prepare the query $stmt = $db->prepare($q); //execute $stmt->execute($params); // returns in the format requested by the variable "$return" if ($return == "rows") { return $stmt->fetch(); }elseif ($return == "rowsall") { return $stmt->fetchAll(); }elseif ($return == "count") { return $stmt->rowCount(); }elseif( $return == "lastid"){ return $db->lastInsertId(); } }catch(PDOException $e) { echo "DataBase Error: ".$e->getMessage(); error_log($e->getMessage()); die(); }catch(Exception $e) { echo "Error: ".$e->getMessage(); error_log($e->getMessage()); die(); } } ```
I'm developing a Python script using the requests library for HTTP requests. I need guidance on handling potential exceptions gracefully and ensuring that I receive a response from the server. Currently, I'm encountering issues with exceptions or no response in terminal. [Here's the current code snippet I'm using](https://i.stack.imgur.com/4bYal.png) I've implemented a code snippet that sends a GET request to a specific URL with headers and payload. I've tried using a try-except block to catch any exceptions, but I'm still facing problems with handling exceptions and empty terminal
Python Requests: Handling Exceptions and Ensuring Server Response
|python|exception|python-requests|timeout|httprequest|
null
```none ValueError: The shape of the target variable and the shape of the target value in `variable.assign(value)` must match. variable.shape=(1, 1, 3, 3), Received: value.shape=(1, 1, 32, 3). Target variable: <KerasVariable shape=(1, 1, 3, 3), dtype=float32, path=conv2d_13/kernel> Model: "functional_52" โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”ณโ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”ณโ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”ณโ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”“ โ”ƒ Layer (type) โ”ƒ Output Shape โ”ƒ Param # โ”ƒ Connected to โ”ƒ โ”กโ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ•‡โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ•‡โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ•‡โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”ฉ โ”‚ input_layer (InputLayer) โ”‚ (None, 32, 32, 3) โ”‚ 0 โ”‚ - โ”‚ โ”œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ผโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ผโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ผโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ค โ”‚ conv2d (Conv2D) โ”‚ (None, 30, 30, 32) โ”‚ 896 โ”‚ input_layer[0][0] โ”‚ โ”œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ผโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ผโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ผโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ค โ”‚ flatten (Flatten) โ”‚ (None, 28800) โ”‚ 0 โ”‚ conv2d[0][0] โ”‚ โ”œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ผโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ผโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ผโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ค โ”‚ dense (Dense) โ”‚ (None, 32) โ”‚ 921,632 โ”‚ flatten[0][0] โ”‚ โ”œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ผโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ผโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ผโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ค โ”‚ dense_1 (Dense) โ”‚ (None, 6) โ”‚ 198 โ”‚ dense[0][0] โ”‚ โ”œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ผโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ผโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ผโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ค โ”‚ spatial_transformer โ”‚ (None, 32, 32, 3) โ”‚ 0 โ”‚ conv2d[0][0], โ”‚ โ”‚ (SpatialTransformer) โ”‚ โ”‚ โ”‚ dense_1[0][0] โ”‚ โ”œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ผโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ผโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ผโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ค โ”‚ conv2d_1 (Conv2D) โ”‚ (None, 32, 32, 3) โ”‚ 12 โ”‚ spatial_transformer[0][0] โ”‚ โ”œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ผโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ผโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ผโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ค โ”‚ sequential (Sequential) โ”‚ (None, 3) โ”‚ 8,963,395 โ”‚ conv2d_1[0][0] โ”‚ โ”œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ผโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ผโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ผโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ค โ”‚ dense_5 (Dense) โ”‚ (None, 3) โ”‚ 12 โ”‚ sequential[0][0] โ”‚ โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ Total params: 9,886,145 (37.71 MB) Trainable params: 9,878,721 (37.68 MB) Non-trainable params: 7,424 (29.00 KB) ``` I'm not able to load the model. I don't understand which layer is causing the trouble. I tried debugging not understanding what is causing the trouble.
I use Acrobat 2020 (pro) to edit a large document. When I insert a "Header" I can use the tool to edit "headers and footers" like in a Word Document. https://www.adobe.com/au/acrobat/hub/how-to/how-to-use-headers-footers-in-pdfs.html I have to do this because the document is puzzled of 100 different documents and is printed at the end. The header contains a Page-Number and when I update the header, Acrobat will find the pagenumbers in all this textboxes and update the numbers (or text). Now, I will find this pagenumbers in the document and a textbox nearby. Is there anybody who knows how to do this? Acrobat will find it, then eg VBA or Java Script will find it too. But how?
Acrobat 2020 editing the Header or Footer in a PDF Document
|javascript|excel|vba|adobe|acrobat|
In the absolute, Yes you can. But it will be a very, very hard task. Look at the dependencies in the [pom.xml](https://github.com/spotify-web-api-java/spotify-web-api-java/blob/master/pom.xml) file: ```xml [...] <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.17.0</version> </dependency> <dependency> <groupId>com.google.code.gson</groupId> <artifactId>gson</artifactId> <version>2.10.1</version> </dependency> <dependency> <groupId>com.neovisionaries</groupId> <artifactId>nv-i18n</artifactId> <version>1.29</version> </dependency> [...] ``` It means: to succeed, download: `2.17.0` version of `jackson-databind` project, where you can find it, `2.10.1` version of `gson`, `1.29` version of `nv-i18n` [...] and the dependencies of these projects too, if they have any (and surely they have plenty). Maven and Gradle aren't something a program implements, they are tools to download and setup correctly all `jar` that are part of an application together. You need one of these tools to build your program. You cannot, I think, escape learning and using Maven. More than 90% of existing Java projects use it.
Currently working through some trouble with Advanced Custom Fields and wpkses filters. So far, I've been able to pass iframe, script, style, and noscript tags through. This google tag manager is <noscript><iframe></iframe></noscript> and the iframe is being caught in wpkses and put in quotes. This is what I have so far: ``` function allow_iframe_script_tags( $allowedposttags ) { $allowedposttags['script'] = array( 'type' => true, 'src' => true, ); $allowedposttags['noscript'] = array(); // Also allow iframe directly $allowedposttags['iframe'] = array( 'src' => true, 'height' => true, 'width' => true, ); $allowedposttags['style'] = array(); return $allowedposttags; } add_filter( 'wp_kses_allowed_html', 'allow_iframe_script_tags', 10, 1 ); ``` I thought that maybe the order in which they were written would end up passing the iframe just fine, and it doesn't. I've tried a few variations: ``` $allowedposttags['noscript']['iframe'] = true; ``` and ``` $allowedposttags['noscript'] = array( 'iframe' => array( 'src' => true, 'height' => true, 'width' => true, ), ); ``` Super thankful for any help. ``` $allowedposttags['noscript']['iframe'] = true; ``` and ``` $allowedposttags['noscript'] = array( 'iframe' => array( 'src' => true, 'height' => true, 'width' => true, ), ); ``` Both ended up still passing the nested iframe in quotes.
here's a slightly cleaner code, ``` // choosing is based on the assumption // that the head is the last element in the body array // if not, you can simply reverse the conditions if (next == /*last in body*/) { spriteName == "head_sprite"; } else if (next == /*first in body*/) { spriteName = "tail_sprite"; } else if (next.x == prev.x || next.y == prev.y) { spriteName == "body_sprite"; } else { spriteName = "curved_sprite"; } // now rotate and reverse if (prev.x == next.x) { // rotate 90deg } else if (prev.x > next.x) { // reverse horizontally } if (prev.y > next.y) { // reverse vertically } ``` it's much more convenient to rotate/reverse the sprite than choosing individual sprites based on each case. i have selected from the snake_graphics.zip you attached those sprites > ["head_down", "tail_down", "body_vertical", "body_bottomright"] and renamed them to > ["head", "tail", "body", "tail" ] respectively. i possibly might have mistaken in rotating/reversing the sprite as i don't know for sure whether prev or next is the current ("assumed prev is"), but that's the basic idea
"listen and reimplement ctrl+z" is a bad approach. there are other ways to trigger the built-in undo/redo in browser uis, which you can not intercept or reimplement, such as the context menu the correct approach is to not change the value property, but use `document.execCommand()` with `"insertText"` or `"delete"` command as appropriate
Your approach of organizing the data in classes is good. But you're defining the classes in a rather complex way. A better option would be to use `inheritence`. If you are unfamiliar with the concepts of `inheritence` or `subclasses`, you can check out this excellent video by [Corey Schafer][1]. You may want to do something like this: ```python class Item: def __init__(self, name, description): self.name = name self.description = description class Weapon(Item): def __init__(self, name, description, damage): super().__init__(name, description) self.damage = damage class Armor(Item): def __init__(self, name, description, defense): super().__init__(name, description) self.defense = defense ``` Then you can create as many `objects` (your items) you want from these classes like this: ```python iron_sword = Weapon("Iron Sword", "A basic iron sword.", damage=10) machine_gun = Weapon("Machine Gun", "An automatic assault rifle.", damage=90) leather_armor = Armor("Leather Armor", "Light armor made of leather.", defense=5) ``` [1]: https://www.youtube.com/watch?v=RSl87lqOXDE
I am creating a web app, and using a mysql database, when i ty to use the bcryptjs library to compare a hash password with the data gathered from a login form, i get that the bcrypt.compare function is receiving string,undefined this is in my controller, this handles the post login, some parts are in spanish, contrasena = password, ``` exports.post_login = (request, response, next) => { const {email, password} = request.body; if(!email || !password){ return response.render("login", {error: "Llena todos los campos"}) } Usuarios.findByEmail(email) .then(user => { if (user) { // Use bcrypt.compare to check if passwords match console.log(user); bcrypt.compare(password, user.contrasena) .then(doMatch => { if (doMatch) { request.session.isLoggedIn = true; request.session.user = user; return request.session.save(err => { response.redirect('/'); }); } else { response.redirect('/users/login'); } }) .catch(err => { console.error('Error during login', err); response.redirect('/users/login'); }); } else { response.redirect('/users/login'); } }) .catch(err => { console.error('Error during login', err); response.redirect('/users/login'); }); }; ``` here is my code from the model.js file, which saves the user info that is received from a signup form ``` save() { const userData = { idUsuario: this.idUsuario, IdRol: this.idRol, Nombre: this.nombre, Contrasena: this.contrasena, Correo: this.email, } return bcrypt.hash(userData.Contrasena, 12) .then((hashedPassword) => { userData.Contrasena = hashedPassword; const values = Object.values(userData); return db.execute('INSERT INTO usuario (idUsuario,IdRol,Nombre,Contrasena,Correo) VALUES (?,?,?,?,?)',values); }) .then(([result]) => { console.log('Usuario Guardado:', result); return result; // Return the ResultSetHeader }) .catch(err => { console.log('Error guardando usuario:', err); throw err; }); } static findByEmail(email) { return db.execute('SELECT * FROM usuario WHERE Correo = ?', [email]) .then(([rows]) => { if (rows.length > 0) { const userData = rows[0]; console.log('Esto es lo que esta recuperando de la base de datos: ', userData) const user = new Usuarios(userData.Nombre, userData.Correo, userData.Contrasena, userData.idUsuario, userData.IDRol); console.log('Esto es lo que se va a retornar: ',user); return { user: user, passwordMatch: true }; // Return user data with passwordMatch true } return { user: null, passwordMatch: false }; // Return null user and passwordMatch false if user not found }) .catch(err => { console.error('Error fetching user by email from database:', err); throw err; }); } ``` i have tried printing the users that are retrieved from the database, the info given from the login form, and they all appear to be in order, the database is in fact saving the user info correctly
In Rust: what structure can be made to avoid having to use RefCell?
|recursion|rust|borrow-checker|refcell|
null
|python|flask|flask-sqlalchemy|flask-migrate|
I am currently using this setup and it is working fine for me: AppiumLibrary.Open Application http://localhost:4723 ... platformName=Android ... appium:automationName=UiAutomator2 ... deviceName=Pixel_6_Pro_API_34 ... appPackage=com.name.ofMyApp ... appActivity=com.name.ofMyApp.MainActivity ... appium:noReset=false I am using `robotframework-appiumlibrary 2.0.0`
I have JSON Rows which can change key and type of values changing keys in examples are `015913d2e43d41ef98e6e5c8dc90cd09_2_1` and `e8c93befe4a34bcabbf604e352a41a2d_2_1` changing types of values are list: ``` "answer": [ "<i>GET</i>\n", "<i>PUT</i>\n", "<i>POST</i>\n", "<i>TRACE</i>\n", "<i>HEAD</i>\n", "<i>DELETE</i>\n" ], ``` text: ``` "answer": "ะœะพะถะตั‚ ะฑั‹ั‚ัŒ ะฒะพ ะฒัะตั…", ``` Examples of rows: row 1 ``` { "event": { "submission": { "015913d2e43d41ef98e6e5c8dc90cd09_2_1": { "question": "ะšะฐะบะธะต ะฒะธะดั‹ <i>HTTP</i> ะทะฐะฟั€ะพัะพะฒ ะผะพะณัƒั‚ ะฒะฝะตัั‚ะธ ะธะทะผะตะฝะตะฝะธั ะฝะฐ ัะตั€ะฒะตั€ะต (ะฒ ะพะฑั‰ะตะผ ัะปัƒั‡ะฐะต)?", "answer": [ "<i>GET</i>\n", "<i>PUT</i>\n", "<i>POST</i>\n", "<i>TRACE</i>\n", "<i>HEAD</i>\n", "<i>DELETE</i>\n" ], "response_type": "choiceresponse", "input_type": "checkboxgroup", "correct": false, "variant": "", "group_label": "" } } } } ``` row 2 ``` { "event": { "submission": { "e8c93befe4a34bcabbf604e352a41a2d_2_1": { "question": "ะ’ ะทะฐะฟั€ะพัะฐั… ะบะฐะบะพะณะพ ั‚ะธะฟะฐ ะผะพะถะตั‚ ะฑั‹ั‚ัŒ ะธัะฟะพะปัŒะทะพะฒะฐะฝะฐ <i>RCE</i>?", "answer": "ะœะพะถะตั‚ ะฑั‹ั‚ัŒ ะฒะพ ะฒัะตั…", "response_type": "multiplechoiceresponse", "input_type": "choicegroup", "correct": true, "variant": "", "group_label": "" } } } } ``` [Here is the Image in Power Query](https://i.stack.imgur.com/cKe3i.jpg) How can extract data from the List in Direct Power Query? If I write this `= Table.AddColumn(#"Duplicated Column", "answer_s", each Record.Field([raw_event][event][submission],[question_id])[answer]{0})` I get error with text types answers [image, error with text types](https://i.stack.imgur.com/Lg3rS.jpg) If i write this: `= Table.AddColumn(#"Duplicated Column", "answer_s", each Record.Field([raw_event][event][submission],[question_id])[answer])` [i get Lists:](https://i.stack.imgur.com/5ByC8.jpg) I have already asked the question with parsing JSON https://stackoverflow.com/questions/78205099/json-parsing-with-changing-keys/78206024#78206024 This is the next problem I need to solve)
{"OriginalQuestionIds":[54989343],"Voters":[{"Id":285587,"DisplayName":"Your Common Sense","BindingReason":{"GoldTagBadge":"mysql"}}]}
I'm really sorry if this is the wrong place but I'm a beginner and I've been trying to find this answer for a long time and can't. I use Shopify and also the Shopify bundles app, for bundling products. When the items within the bundle have variants, the name of the item and then the name of the variant option is displayed in the store front. [For example in this image](https://i.stack.imgur.com/ZdMpJ.png) the items in the bundle are are "test item 1" and "test item 2" and the variant options for both are "size". I want this just just display as "Size" without showing the name of the item. In other words I just want the variant option name to show and not the product name. I did speak with Shopify who referred me to their community but I didn't get an answer, the post is here: https://community.shopify.com/c/shopify-apps/change-variant-copy-when-using-shopify-bundles-app/td-p/2499063 I don't even know where to start so if anyone knows or has any ideas I'd love to hear. thank you :)
|linux|docker|gitlab-ci-runner|
I'm trying to convert a MariaDB do MySQL using Schema Conversion within DMS. But after creating the Migration Project I don't see a Schema Conversion tab. I was following the tutorial mentioned below. At 10:22 there is a Schema Conversion Tab but I'm not able to see it. https://www.youtube.com/watch?v=u7yKzYpbiLk
AWS - Tab Schema Conversion don't show up after creating a Migration Project
|amazon-web-services|aws-dms|
null