instruction
stringlengths
0
30k
I am curious how really lambda function in set algorithms works or the algorithm behaves for the given lambda function in C++ . In below example I am using std::set_difference algorithm for two map. ``` std::map<std::string, int> map1{ {"test1",1}, {"test2",2}, {"test3",3}, {"test4",4},{"wxyz5",10}}; std::map<std::string, int> map2{ {"test1",2}, {"test2",3} }; std::map<std::string, int> difference; std::set_difference(map1.begin(), map1.end(), map2.begin(), map2.end(), std::inserter(difference, difference.begin()), [](const auto& one, const auto& two) { return one.first < two.first; }); ``` below is the definition of comparison function from cppreference , *comp - comparison function object (i.e. an object that satisfies the requirements of Compare) which returns ​true if the first argument is less than (i.e. is ordered before) the second.* So , I am assuming if this returns true , then the first element is less than the second one , and if it is less than the second one , it will be added to the output container. based on my research over the internet the comparison function checks whether the first element is lexicographically lesser than the second element. So , "wxyz5" should be lexicographically greater than all the string in map2. it should return false and it should not be added to output container right ? but I am getting these three elements in the `difference` map `{"test3",3}, {"test4",4},{"wxyz5",10}`. how ? and I tried this in lambda return, `return two.first < one.first;` and it breaks . why ? I just don't want to blindly return `first < second ` in lambda expression . If I understand it correctly , I can make sure it will work in my all future scenarios. If I am comparing two pointers what is the correct way to write lambda here ? thanks.
Thank you GSerg, this got me thinking. After testing all controls for focus it turned up that when the form is initializing the focus is being set to the image control in the third frame. Printing the list of controls to the immediate window, looking at the creation sequence, tab index, and tab stop nothing shows why VBA chose this control to put focus on. I setfocus in the initialize sub now and have adjusted the keydown to it and everything is working. Again Thank you GSerg.
I'm currently working on an Express.js application where I'm trying to handle file uploads using Multer. However, I'm encountering an issue with the error message "MulterError: Unexpected field" when I attempt to upload files. Interestingly, when I tested file uploads using Postman, I successfully received image data without encountering any errors. Here's the code snippet from my Express route: ``` const route = express.Router() const upload = multer() route.post('/add-product', upload.array('image', 4), async (req, res) => { const imageFiles = req.files console.log(' ~ imageFiles:', imageFiles) const productData = req.body console.log(' ~ productData:', productData) const imageUrls = [] // Handle the files and product data as needed }) ``` handler ``` const [uploadedImages, setUploadedImages] = useState<File[]>([]); const handleUpload = (file: File) => { setUploadedImages((prevImages) => [...prevImages, file]); }; async function onSubmit(values: z.infer<typeof productValidation>) { try { values.category = await extractIdsFromArray(values?.category); const response = await addProduct({ ...values, image: uploadedImages, }).unwrap(); console.log(" ~ onSubmit ~ response:", response); if (response?.success) { toast.success(response?.message); // refetch(); } else { toast.error(response?.message); } } catch (error) { console.log(" ~ onSubmit ~ error:", error); // @ts-ignore toast.error("An unexpected error occurred!", error?.data?.message); } } ``` some sinipade of image upload code ``` <FormField control={form.control} name="image" render={({ field }) => ( <FormItem> <FormLabel> Product Images </FormLabel> <FormControl> <MultipleImageUpload onUpload={handleUpload} setUploadedImages={ setUploadedImages } /> </FormControl> <FormMessage /> <FormMessage /> </FormItem> )} /> ``` multiple image uploader ``` import React, { useCallback, useState } from "react"; import { AlertCircle, ImageIcon, ImageMinus, XIcon } from "lucide-react"; import Image from "next/image"; import { useDropzone } from "react-dropzone"; import * as z from "zod"; import { Alert, AlertDescription, AlertTitle } from "./alert"; import { toast } from "sonner"; const MultipleImageUpload = ({ onUpload, setUploadedImages, }: { onUpload: any; setUploadedImages: any; }) => { const [previewUrls, setPreviewUrls] = useState<string[]>([]); const imageValidation = z.string().refine( (value) => { const extension = value.split(".").pop()?.toLowerCase(); return ( extension === "jpg" || extension === "jpeg" || extension === "png" ); }, { message: "Invalid image format. Only JPG, JPEG, or PNG allowed.", } ); const maxFileSize = 5 * 1024 * 1024; // 5 MB in bytes const maxImages = 4; const onDrop = useCallback( (acceptedFiles: any) => { const newPreviewUrls: string[] = []; acceptedFiles.slice(0, maxImages).forEach((file: File) => { const validationResult = imageValidation.safeParse(file.name); if (!validationResult.success) { const errorMessage = validationResult.error.errors[0].message; toast.error(errorMessage); return; } if (file.size > maxFileSize) { toast.error( "Image size exceeds 5 MB. Please choose a smaller image." ); return; } const fileUrl = URL.createObjectURL(file); newPreviewUrls.push(fileUrl); onUpload(file); }); setPreviewUrls((prev) => [...prev, ...newPreviewUrls]); }, [onUpload, imageValidation] ); const handleRemove = (index: number) => { // Remove the removed image from uploadedImages state setUploadedImages((prevImages: File[]) => { const updatedImages = [...prevImages]; updatedImages.splice(index, 1); return updatedImages; }); const updatedPreviewUrls = [...previewUrls]; updatedPreviewUrls.splice(index, 1); setPreviewUrls(updatedPreviewUrls); }; const { getRootProps, getInputProps, isDragActive } = useDropzone({ onDrop, }); return ( <div {...getRootProps()} className="border border-dashed border-input p-4 rounded-md" > <input accept=".jpg, .jpeg, .png" {...getInputProps()} /> {isDragActive ? ( <p>Drop the images here...</p> ) : ( <p>Drag 'n' drop images here, or click to select images</p> )} <div className="grid grid-cols-2 gap-4 mt-4"> {previewUrls.map((url, index) => ( <div key={index} className="relative"> <button onClick={() => handleRemove(index)} className="absolute top-2 right-2 bg-white rounded-full p-1 z-50" > <XIcon className="h-6 w-6 text-red-500" /> </button> <Image key={url} src={url} alt="Image" className="rounded-md object-cover w-full h-full" width={200} height={200} /> </div> ))} </div> </div> ); }; export default MultipleImageUpload; ``` redux end point ``` addProduct: build.mutation({ query: (product) => ({ url: "/product/add-product/", method: "POST", data: product, contentType: "multipart/form-data", }), invalidatesTags: ["product"], }),``` error images: [![enter image description here](https://i.stack.imgur.com/U3QDF.png)](https://i.stack.imgur.com/U3QDF.png) I've ensured that the field name 'image' matches between the front-end form and the Multer configuration. I'm also using the correct enctype attribute in my form (multipart/form-data). Despite these checks, I'm still encountering the "MulterError: Unexpected field" error. Can anyone help me identify what might be causing this issue and how I can resolve it? Any insights or suggestions would be greatly appreciated. Thanks in advance! I've double-checked the field names, verified the form's encoding type, and reviewed the Multer documentation, but I haven't been able to identify the root cause of the error.
MulterError: Unexpected field in Express.js with multer
|express|next.js|multer|react-hook-form|shadcnui|
null
I use Apache2 to intervene between my site and the User with an Authentication Login dialogue. I've added a hashed password to the Apache2 .htaccess file. The Site has a registered subdomain, and the web server has a set of SSL certs and keys. However, when a User tries to access the site and they are presented with the Username & Password box, the username and password are not accepted. I would appreciate some help. I create a Username and Password for the site authentication using: sudo htpasswd -c /etc/apache2/.htpasswd I can see a hashed version of the password in that file. Then, these are my Apache2 server configuration files: **/etc/apache2/sites-available/my-site.conf** <IfModule mod_ssl.c> <VirtualHost *:443> ServerName my-site.com ServerAlias subdomain.my-site.com DocumentRoot /var/www/my-site/public_html <Directory /var/www/my-site/public_html> Options Indexes FollowSymLinks AllowOverride All Require all granted </Directory> <Location "/"> AuthType Digest AuthName "Restricted Area" AuthDigestDomain / AuthDigestProvider file AuthUserFile /etc/apache2/.htpasswd Require valid-user </Location> SSLCertificateFile /etc/letsencrypt/live/subdomain.my-site.com/fullchain.pem SSLCertificateKeyFile /etc/letsencrypt/live/subdomain.my-site.com/privkey.pem Include /etc/letsencrypt/options-ssl-apache.conf </VirtualHost> </IfModule> And the main apache config file **/etc/apache2/apache.conf** DefaultRuntimeDir ${APACHE_RUN_DIR} PidFile ${APACHE_PID_FILE} Timeout 300 KeepAlive On MaxKeepAliveRequests 100 KeepAliveTimeout 5 User ${APACHE_RUN_USER} Group ${APACHE_RUN_GROUP} HostnameLookups Off ErrorLog ${APACHE_LOG_DIR}/error.log LogLevel warn IncludeOptional mods-enabled/*.load IncludeOptional mods-enabled/*.conf Include ports.conf <Directory /> Options FollowSymLinks AllowOverride None Require all denied </Directory> <Directory /usr/share> AllowOverride None Require all granted </Directory> <Directory /var/www/> Options Indexes FollowSymLinks AllowOverride None Require all granted </Directory> <Directory /usr/share> AllowOverride None Require all granted </Directory> <Directory /var/www/> Options Indexes FollowSymLinks AllowOverride None Require all granted </Directory> AccessFileName .htaccess #<FilesMatch "^\.ht"> # Require all denied #</FilesMatch> LogFormat "%v:%p %h %l %u %t \"%r\" %>s %O \"%{Referer}i\" \"%{User-Agent}i\"" vhost_combined LogFormat "%h %l %u %t \"%r\" %>s %O \"%{Referer}i\" \"%{User-Agent}i\"" combined LogFormat "%h %l %u %t \"%r\" %>s %O" common LogFormat "%{Referer}i -> %U" referer LogFormat "%{User-agent}i" agent IncludeOptional conf-enabled/*.conf IncludeOptional sites-enabled/*.conf Include /etc/apache2/httpd.conf My **/etc/apache/httpd.conf** file is empty. I've cleared the cache, used private browsers, and I've asked others to try, but ultimately the password and username I set don't work. Please tell me if I'm missing data for you to help. I'm happy to edit the question. Thanks Edit I noticed the following: <FilesMatch "^\.ht"> Require all denied </FilesMatch> I commented it out, restarted the server, and tried again in a fresh private browser. No luck.
EDIT: On a side note, I personally would not modify the array while iterating over it, some data structures implementations are not prepared for that. Other have said correctly the your are removing the item first, which is wrong. --- --- But for the solutions, I would give you 2. For one, you could sort the array, using the sort criteria as the value from the map, as a custom comparator. This answer shows it with an integers array: https://stackoverflow.com/questions/3699141/how-to-sort-an-array-of-ints-using-a-custom-comparator. And this one with a java 8 stream which I like more: https://stackoverflow.com/questions/58612318/how-to-define-custom-sorted-comparator-in-java-8-stream-to-compare-on-the-key-an. For a java stream of `Map<String, Object>` ``` import java.util.HashMap; import java.util.List; import java.util.ArrayList; import java.util.Map; import java.util.Comparator; import java.util.Arrays; import java.util.stream.Collectors; public class MyClass { public static void main(String args[]) { List<Map<String, Object>> unique = new ArrayList<>(); Map<String, Object> m1 = new HashMap<>(); m1.put("name", "NUMBER ONE"); m1.put("isCorrect", false); Map<String, Object> m2 = new HashMap<>(); m2.put("name", "MOVE THIS ONE TO i0"); m2.put("isCorrect", true); Map<String, Object> m3 = new HashMap<>(); m3.put("name", "NUMBER TWO"); m3.put("isCorrect", false); unique.add(m1); unique.add(m2); unique.add(m3); System.out.println(unique); final var size = unique.size(); unique = unique.stream().sorted(new Comparator<Map<String, Object>>() { public int compare(Map<String, Object> m1, Map<String, Object> m2) { return ((Boolean)m1.getOrDefault("isCorrect", false)) ? -1 : (((Boolean)m2.getOrDefault("isCorrect", false)) ? 1 : 0); } }).collect(Collectors.toCollection(() -> new ArrayList<>(size))); System.out.println(unique); } } ``` Note that: * Sorting an array can be overkill, compares too much stuff * Can be used for trivial, non critical code that will run The ideal thing would be finding the one you want, then moving it to the first position: ``` System.out.println(unique); var foundIndex = -1; // TODO: Is it possible not to find it ? will there only be one of it ? for (int i = 0; i < unique.size(); i++) { if ((boolean) unique.get(i).get("isCorrect")) { foundIndex = i; break; } } unique.add(0, unique.get(foundIndex)); unique.remove(foundIndex+1); System.out.println(unique); ``` [![Test run][1]][1] Things to think: * Could there be more than one match ? * Could the value not exist ? * `ArrayList is not performant to insert at the head`, if this is not a critical code, its ok. But removing is O(1), things to consider: https://www.baeldung.com/java-collections-complexity. Some code adjusments would need to be made. [1]: https://i.stack.imgur.com/oIGi5.png
For me, I was serving up drupal via PHP CLI and had to be running it in the web folder, not send web/index.php as a param
Here is a full working solution that I think is neat. I used the idea (thanks @matswecja) of using a custom `replace` function. ```python3 def myreplace(self,kwargs_= {}, **kwargs): kwargs = kwargs_ | kwargs current_data = self.__dict__ updated_data = {} sig = self.__annotations__ for var, arg in kwargs.items(): if var not in sig: raise TypeError(type(self),var) typ = sig[var] if isinstance(arg, typ): updated_data[var] = arg elif is_dataclass(typ): updated_data[var] = current_data[var](**arg) elif callable(arg): updated_data[var] = arg(current_data[var]) else: raise TypeError(var, typ, arg, type(arg)) return replace(self, **updated_data) @dataclass(frozen=True) class Money: __call__ = myreplace currency: str amount: int unit:str = field(default='k') @dataclass(frozen=True) class Role: __call__ = myreplace title: str salary: Money @dataclass(frozen=True) class Person: __call__ = myreplace name: str age: int role: Role a0 = Person('jhon smith', 26, Role('Jnr',Money('£',20))) a1 = a0(name=str.title) a2 = a1( {'role': { 'title' : 'Snr', 'salary': { 'amount': lambda a: a + 10 }} }) print(a0) print(a1) print(a2) ``` Printing: ``` python3 Person(name='jhon smith', age=26, role=Role(title='Jnr', salary=Money(currency='£', amount=20, unit='k'))) Person(name='Jhon Smith', age=26, role=Role(title='Jnr', salary=Money(currency='£', amount=20, unit='k'))) Person(name='Jhon Smith', age=26, role=Role(title='Snr', salary=Money(currency='£', amount=30, unit='k'))) ```
I'm working on two projects simultaneously: one in Laravel 8 and the other in Express.js. In the Laravel project, I generate a token and want to use it to retrieve an element in my Express.js application. How can I pass this token securely from Laravel to Express.js and then use it to fetch the corresponding element? Here's what I have in mind: 1. I generate a token in Laravel. 2. I send this token to my Express.js application. 3. In Express.js, I create a route to receive the token and use it to fetch the corresponding element. Could someone guide me on how to implement this securely and efficiently in both Laravel and Express.js? Any help or pointers would be greatly appreciated! Thanks in advance!
How to Retrieve an Element in Express.js by Passing a Token Generated by Laravel 8?
|javascript|php|node.js|laravel|express|
null
Running a shell script file marked as executable results in creating a system process executing it. It appears to me that it is not possible to determine from within the script if the executable of the interpreter used to run the script is the executable ASSUMED to be used as interpreter. There are ways to query some data from within the script, but if an alien executable also provides them knowing that they should be there available for queries, there is no way to know if the script is run by the assumed executable or by the alien one which somehow found a way to become executed instead. Is there a way in Linux to determine FOR SURE which shell executable file is running a shell script? Or is it necessary to modify the source code of the interpreter in a way which makes it then possible by the scripts to be sure they are run by the interpreter executable they were designed to be run with? I would like to gain some deeper understanding of how a Linux system works under the hood - this is the reason why do I want to get an answer to this question in hope it would help me on the way to better understanding of the system I am using.
I have multiple pipelines running on Airflow and these pipelines dump data to Snowflake. When I used basic authentication(username and password), I didn't get any error. However, when I switched to using Key-Pair authentication, the pipelines failed WARNING - Retrying (Retry(total=0, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ConnectTimeoutError(<snowflake.connector.vendored.urllib3.connection.HTTPSConnection object at 0x7fee180c32b0>, 'Connection to 1 timed out. (connect timeout=60)')': /%5Cxf0%60%5Cx9bO4%5D%5Cn~%5Cxdfw%5Cxf4%5Cr%5B%5Cx9a%5Cx00%5Cx1eok?%5Cxbf2%5Cxd3%7DZ%5Cx02%5Cx9fg%5Cx13R%5Cxe1%25%5Cxda%5Cx99%5Cxa5R%5Cxa0%5Cxf0%5Cr%5Cxe7K%5Cx1b?-%5Cxe5$6%5Cxa3%5CxccGBv%5Cxa4%5Cxa1n%5Cx0e%5Cx82P%5Cxa9%5Cx07$%5Cx1bh%5Cx11%5Cxac%5Cx03%5Cx80i%5Cx9b%5Cxbe%5Cx8d%5Cxc5%5Cxbd%5CxddD%5Cx8c%5Cx14%5Cxca%5Cxb6%5Cx9b%3C%5Cxb6%5Cxe6%5Cxb8%5Cx9e%5Cx9e.%5Cxa2y(%5Cxb2%5Cxb8%60%5Cx11%5Cx01%5Cxc8Z%5Cx04U9%5Cx84%5Cxe3%5Cxf0%5Cxe0%5Cxca%5Cx9b%5Cxacv%5Cxd5EB%5Cx13U%5C'%5Cx13M'&warehouse=LOAD_WH.snowflakecomputing.com:443/session/v1/login-request?request_id=d3096edc-10f9-49ee-b8cb-79566f11b012 [2024-02-20 12:34:33,528] {network.py:940} ERROR - HTTPSConnectionPool(host='1', port=443): Max retries exceeded with url: /%5Cxf0%60%5Cx9bO4%5D%5Cn~%5Cxdfw%5Cxf4%5Cr%5B%5Cx9a%5Cx00%5Cx1eok?%5Cxbf2%5Cxd3%7DZ%5Cx02%5Cx9fg%5Cx13R%5Cxe1%25%5Cxda%5Cx99%5Cxa5R%5Cxa0%5Cxf0%5Cr%5Cxe7K%5Cx1b?-%5Cxe5$6%5Cxa3%5CxccGBv%5Cxa4%5Cxa1n%5Cx0e%5Cx82P%5Cxa9%5Cx07$%5Cx1bh%5Cx11%5Cxac%5Cx03%5Cx80i%5Cx9b%5Cxbe%5Cx8d%5Cxc5%5Cxbd%5CxddD%5Cx8c%5Cx14%5Cxca%5Cxb6%5Cx9b%3C%5Cxb6%5Cxe6%5Cxb8%5Cx9e%5Cx9e.%5Cxa2y(%5Cxb2%5Cxb8%60%5Cx11%5Cx01%5Cxc8Z%5Cx04U9%5Cx84%5Cxe3%5Cxf0%5Cxe0%5Cxca%5Cx9b%5Cxacv%5Cxd5EB%5Cx13U%5C'%5Cx13M'&warehouse=LOAD_WH.snowflakecomputing.com:443/session/v1/login-request?request_id=d3096edc-10f9-49ee-b8cb-79566f11b012 (Caused by ConnectTimeoutError(<snowflake.connector.vendored.urllib3.connection.HTTPSConnection object at 0x7fee18385550>, 'Connection to 1 timed out. (connect timeout=60)')) Traceback (most recent call last): File "/home/airflow/gcs/dags/test/snowflake_test.py", line 120, in write_from_gcs if not conn: File "/opt/python3.8/lib/python3.8/site-packages/snowflake/connector/pandas_tools.py", line 164, in write_pandas cursor = conn.cursor() File "/opt/python3.8/lib/python3.8/site-packages/snowflake/connector/connection.py", line 650, in cursor Error.errorhandler_wrapper( File "/opt/python3.8/lib/python3.8/site-packages/snowflake/connector/errors.py", line 275, in errorhandler_wrapper handed_over = Error.hand_to_other_handler( File "/opt/python3.8/lib/python3.8/site-packages/snowflake/connector/errors.py", line 333, in hand_to_other_handler connection.errorhandler(connection, cursor, error_class, error_value) File "/opt/python3.8/lib/python3.8/site-packages/snowflake/connector/errors.py", line 209, in default_errorhandler raise error_class( snowflake.connector.errors.DatabaseError: 250002 (08003): None: Connection is closed During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/opt/python3.8/lib/python3.8/site-packages/snowflake/connector/vendored/urllib3/connection.py", line 174, in _new_conn conn = connection.create_connection( File "/opt/python3.8/lib/python3.8/site-packages/snowflake/connector/vendored/urllib3/util/connection.py", line 95, in create_connection raise err File "/opt/python3.8/lib/python3.8/site-packages/snowflake/connector/vendored/urllib3/util/connection.py", line 85, in create_connection sock.connect(sa) socket.timeout: timed out During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/opt/python3.8/lib/python3.8/site-packages/snowflake/connector/vendored/urllib3/connectionpool.py", line 703, in urlopen httplib_response = self._make_request( File "/opt/python3.8/lib/python3.8/site-packages/snowflake/connector/vendored/urllib3/connectionpool.py", line 386, in _make_request self._validate_conn(conn) File "/opt/python3.8/lib/python3.8/site-packages/snowflake/connector/vendored/urllib3/connectionpool.py", line 1042, in _validate_conn conn.connect() File "/opt/python3.8/lib/python3.8/site-packages/snowflake/connector/vendored/urllib3/connection.py", line 358, in connect self.sock = conn = self._new_conn() File "/opt/python3.8/lib/python3.8/site-packages/snowflake/connector/vendored/urllib3/connection.py", line 179, in _new_conn raise ConnectTimeoutError( snowflake.connector.vendored.urllib3.exceptions.ConnectTimeoutError: (<snowflake.connector.vendored.urllib3.connection.HTTPSConnection object at 0x7fee18385550>, 'Connection to 1 timed out. (connect timeout=60)') During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/opt/python3.8/lib/python3.8/site-packages/snowflake/connector/vendored/requests/adapters.py", line 489, in send resp = conn.urlopen( File "/opt/python3.8/lib/python3.8/site-packages/snowflake/connector/vendored/urllib3/connectionpool.py", line 815, in urlopen return self.urlopen( File "/opt/python3.8/lib/python3.8/site-packages/snowflake/connector/vendored/urllib3/connectionpool.py", line 787, in urlopen retries = retries.increment( File "/opt/python3.8/lib/python3.8/site-packages/snowflake/connector/vendored/urllib3/util/retry.py", line 592, in increment raise MaxRetryError(_pool, url, error or ResponseError(cause)) snowflake.connector.vendored.urllib3.exceptions.MaxRetryError: HTTPSConnectionPool(host='1', port=443): Max retries exceeded with url: /%5Cxf0%60%5Cx9bO4%5D%5Cn~%5Cxdfw%5Cxf4%5Cr%5B%5Cx9a%5Cx00%5Cx1eok?%5Cxbf2%5Cxd3%7DZ%5Cx02%5Cx9fg%5Cx13R%5Cxe1%25%5Cxda%5Cx99%5Cxa5R%5Cxa0%5Cxf0%5Cr%5Cxe7K%5Cx1b?-%5Cxe5$6%5Cxa3%5CxccGBv%5Cxa4%5Cxa1n%5Cx0e%5Cx82P%5Cxa9%5Cx07$%5Cx1bh%5Cx11%5Cxac%5Cx03%5Cx80i%5Cx9b%5Cxbe%5Cx8d%5Cxc5%5Cxbd%5CxddD%5Cx8c%5Cx14%5Cxca%5Cxb6%5Cx9b%3C%5Cxb6%5Cxe6%5Cxb8%5Cx9e%5Cx9e.%5Cxa2y(%5Cxb2%5Cxb8%60%5Cx11%5Cx01%5Cxc8Z%5Cx04U9%5Cx84%5Cxe3%5Cxf0%5Cxe0%5Cxca%5Cx9b%5Cxacv%5Cxd5EB%5Cx13U%5C'%5Cx13M'&warehouse=LOAD_WH.snowflakecomputing.com:443/session/v1/login-request?request_id=d3096edc-10f9-49ee-b8cb-79566f11b012 (Caused by ConnectTimeoutError(<snowflake.connector.vendored.urllib3.connection.HTTPSConnection object at 0x7fee18385550>, 'Connection to 1 timed out. (connect timeout=60)')) During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/opt/python3.8/lib/python3.8/site-packages/snowflake/connector/network.py", line 1026, in _request_exec raw_ret = session.request( File "/opt/python3.8/lib/python3.8/site-packages/snowflake/connector/vendored/requests/sessions.py", line 587, in request resp = self.send(prep, **send_kwargs) File "/opt/python3.8/lib/python3.8/site-packages/snowflake/connector/vendored/requests/sessions.py", line 701, in send r = adapter.send(request, **kwargs) File "/opt/python3.8/lib/python3.8/site-packages/snowflake/connector/vendored/requests/adapters.py", line 553, in send raise ConnectTimeout(e, request=request) snowflake.connector.vendored.requests.exceptions.ConnectTimeout: HTTPSConnectionPool(host='1', port=443): Max retries exceeded with url: /%5Cxf0%60%5Cx9bO4%5D%5Cn~%5Cxdfw%5Cxf4%5Cr%5B%5Cx9a%5Cx00%5Cx1eok?%5Cxbf2%5Cxd3%7DZ%5Cx02%5Cx9fg%5Cx13R%5Cxe1%25%5Cxda%5Cx99%5Cxa5R%5Cxa0%5Cxf0%5Cr%5Cxe7K%5Cx1b?-%5Cxe5$6%5Cxa3%5CxccGBv%5Cxa4%5Cxa1n%5Cx0e%5Cx82P%5Cxa9%5Cx07$%5Cx1bh%5Cx11%5Cxac%5Cx03%5Cx80i%5Cx9b%5Cxbe%5Cx8d%5Cxc5%5Cxbd%5CxddD%5Cx8c%5Cx14%5Cxca%5Cxb6%5Cx9b%3C%5Cxb6%5Cxe6%5Cxb8%5Cx9e%5Cx9e.%5Cxa2y(%5Cxb2%5Cxb8%60%5Cx11%5Cx01%5Cxc8Z%5Cx04U9%5Cx84%5Cxe3%5Cxf0%5Cxe0%5Cxca%5Cx9b%5Cxacv%5Cxd5EB%5Cx13U%5C'%5Cx13M'&warehouse=LOAD_WH.snowflakecomputing.com:443/session/v1/login-request?request_id=d3096edc-10f9-49ee-b8cb-79566f11b012 (Caused by ConnectTimeoutError(<snowflake.connector.vendored.urllib3.connection.HTTPSConnection object at 0x7fee18385550>, 'Connection to 1 timed out. (connect timeout=60)')) During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/opt/python3.8/lib/python3.8/site-packages/snowflake/connector/network.py", line 845, in _request_exec_wrapper return_object = self._request_exec( File "/opt/python3.8/lib/python3.8/site-packages/snowflake/connector/network.py", line 1113, in _request_exec raise RetryRequest(err) snowflake.connector.network.RetryRequest: HTTPSConnectionPool(host='1', port=443): Max retries exceeded with url: /%5Cxf0%60%5Cx9bO4%5D%5Cn~%5Cxdfw%5Cxf4%5Cr%5B%5Cx9a%5Cx00%5Cx1eok?%5Cxbf2%5Cxd3%7DZ%5Cx02%5Cx9fg%5Cx13R%5Cxe1%25%5Cxda%5Cx99%5Cxa5R%5Cxa0%5Cxf0%5Cr%5Cxe7K%5Cx1b?-%5Cxe5$6%5Cxa3%5CxccGBv%5Cxa4%5Cxa1n%5Cx0e%5Cx82P%5Cxa9%5Cx07$%5Cx1bh%5Cx11%5Cxac%5Cx03%5Cx80i%5Cx9b%5Cxbe%5Cx8d%5Cxc5%5Cxbd%5CxddD%5Cx8c%5Cx14%5Cxca%5Cxb6%5Cx9b%3C%5Cxb6%5Cxe6%5Cxb8%5Cx9e%5Cx9e.%5Cxa2y(%5Cxb2%5Cxb8%60%5Cx11%5Cx01%5Cxc8Z%5Cx04U9%5Cx84%5Cxe3%5Cxf0%5Cxe0%5Cxca%5Cx9b%5Cxacv%5Cxd5EB%5Cx13U%5C'%5Cx13M'&warehouse=LOAD_WH.snowflakecomputing.com:443/session/v1/login-request?request_id=d3096edc-10f9-49ee-b8cb-79566f11b012 (Caused by ConnectTimeoutError(<snowflake.connector.vendored.urllib3.connection.HTTPSConnection object at 0x7fee18385550>, 'Connection to 1 timed out. (connect timeout=60)')) write_from_gcs function does the following activities: - Read a file from a GCS bucket - Get a Snowflake connection (create a new connection, if a connection does not already exist) - Write to Snowflake Earlier, I thought this was due to some timeout issue, so explicitly set socket_timeout while creating a snowflake connection, still got the same error. I reverted to using username and password to authenticate to Snowflake, and the code works as expected. It is clear, that the issue is because of changing the auth method, not sure though where exactly to check **Basic Auth** import snowflake.connector as snow snow.connect( username='abc', password='xyz', account='123', warehouse='test', database='test_db', schema='schema', ) **Key-Pair** import snowflake.connector as snow from cryptography.hazmat.backends import default_backend from cryptography.hazmat.primitives.asymmetric import rsa from cryptography.hazmat.primitives.asymmetric import dsa from cryptography.hazmat.primitives import serialization def get_private_key(private_key, passphrase): p_key= serialization.load_pem_private_key( private_key, password=passphrase, backend=default_backend() ) pkb = p_key.private_bytes( encoding=serialization.Encoding.DER, format=serialization.PrivateFormat.PKCS8, encryption_algorithm=serialization.NoEncryption()) return pkb snow.connect( username='abc', private_key=get_private_key(pkb, passphrase) account='123', warehouse='test', database='test_db', schema='schema', ) [1]: https://drive.google.com/file/d/11QY5ndfUQXZl9Pjmfn7dAPGmHy-N2w9a/view?usp=sharing
You can delete a endpoint using the python azure ml sdk service = Webservice(workspace=ws, name='your-service-name') service.delete() Then if you want to re create you can re deploy the model from azureml.core.model import InferenceConfig from azureml.core.webservice import AciWebservice from azureml.core.model import Model service_name = 'my-custom-env-service' inference_config = InferenceConfig(entry_script='score.py', environment=environment) aci_config = AciWebservice.deploy_configuration(cpu_cores=1, memory_gb=1) service = Model.deploy(workspace=ws, name=service_name, models=[model], inference_config=inference_config, deployment_config=aci_config, overwrite=True) service.wait_for_deployment(show_output=True)
I have a Redis cluster v7.x with 3 masters each having 1 slave. A function `myFunc` written in Lua is loaded in all the 3 master nodes. I am calling this function from my node.js code (caller.js) using ioredis client library as: let redis = require('ioredis'); const cluster = new redis.Cluster( [ { port: 5000, host: "localhost" }, { port: 5001, host: "localhost" }, { port: 5002, host: "localhost" } ] ); cluster.on('error', function (err) { console.log('Redis error ' + err); }); cluster.fcall("myFunc", "0", "arg1", "arg2", "arg3").then((elements) => { console.log(elements); }); When I run the program as following: `nodejs caller.js` then sometimes it runs and logs the return value, and sometimes it throws the following error: (node:2809539) UnhandledPromiseRejectionWarning: ReplyError: ERR Script attempted to access a non local key in a cluster node script: myFunc, on @user_function:66. at parseError (/home/user/node_modules/redis-parser/lib/parser.js:179:12) at parseType (/home/user/node_modules/redis-parser/lib/parser.js:302:14) What could be wrong here? How to make the function call work?
To use sealed classes with Freezed in Dart, you don't need to create separate classes for each variant. Instead, you can define all variants within the same sealed class and handle them using pattern matching. Here's how you can modify your code: import 'package:freezed_annotation/freezed_annotation.dart'; part 'example.freezed.dart'; part 'example.g.dart'; @freezed abstract class Example with _$Example { const factory Example.text({ required String text, }) = _Text; const factory Example.nameLocation({ required String name, required String location, }) = _NameLocation; factory Example.fromJson(Map<String, dynamic> json) => _$ExampleFromJson(json); } void main() { final example1 = Example.fromJson({'runtimeType': 'text', 'text': 'Hello'}); final example2 = Example.fromJson({ 'runtimeType': 'nameLocation', 'name': 'John', 'location': 'Amsterdam' }); example1.when( text: (String text) => print('Text: $text'), nameLocation: (String name, String location) => print('Name: $name, Location: $location'), ); example2.when( text: (String text) => print('Text: $text'), nameLocation: (String name, String location) => print('Name: $name, Location: $location'), ); }
I am trying to hide every product in my shop that is in the "Testing" category. I have tried the following 3 sets of code that I have found on these forums, to no avail. ```add_filter( 'get_terms', 'ts_get_subcategory_terms', 10, 3 ); function ts_get_subcategory_terms( $terms, $taxonomies, $args ) { $new_terms = array(); // if it is a product category and on the shop page if ( in_array( 'product_cat', $taxonomies ) && ! is_admin() &&is_shop() || is_product_category()) { foreach( $terms as $key => $term ) { if ( !in_array( $term->slug, array( 'testing' ) ) ) { //pass the slug name here $new_terms[] = $term; }} $terms = $new_terms; } return $terms; } ``` ```add_action( 'pre_get_posts', 'custom_pre_get_posts_query' ); function custom_pre_get_posts_query( $q ) { if ( ! $q->is_main_query() ) return; if ( ! $q->is_post_type_archive() ) return; if ( ! is_admin() && is_shop() ) { $q->set( 'tax_query', array(array( 'taxonomy' => 'product_cat', 'field' => 'slug', 'terms' => array( 'testing' ), // Don't display products in the testing category on the shop page 'operator' => 'NOT IN' ))); } remove_action( 'pre_get_posts', 'custom_pre_get_posts_query' ); } ``` ```add_filter( 'get_terms', 'hide_category', 10, 1 ); function hide_category( $terms ) { $new_terms = array(); foreach ( $terms as $term ) { if ( $term->slug !== 'testing' ) { $new_terms[] = $term; } else if ( $term->taxonomy !== 'product_cat' || is_admin() ) { $new_terms[] = $term; } } return $new_terms; } ``` The products still show up in my shop. Any suggestions? And to make it a bit more complicated, I would love it if the products could have other categories, but still not show up if 'testing' is one of the categories. I currently have my product only in the 'testing' category to try and make this work, but would like it to be in multiple categories and still not show.
Hiding a specific category in WooCommerce shop
|php|wordpress|woocommerce|
I have created a workflow which captures the data sent by a request in a variable, lets call it `data`. I am using Python to hit the endpoint. The JSON structure is as follows: ``` slack_data = { "userEmail": f"{email}", "blocks": [ { "type": "section", "text": { "type": "mrkdwn", "text": f"Hello <@{user_id}>, blah blah" } }, { "type": "divider" } ] } ``` I then compile my JSON and send it as data to my request: ``` response = requests.post( webhook_url, data=json.dumps(slack_data), headers={'Content-Type': 'application/json'} ) ``` I then get 400 errors. The URL is correct, as if I remove the slack blocks, the request goes through as expected. Are blocks not viable when sending through a workflow, or is it only via the incoming-webhook app?
Adding Slack Blocks into a workflow using the UI
|slack|slack-block-kit|
``` import React from "react"; import ReactLogo from "./image/react.svg"; import TypeScript from "./image/typescript.svg"; import MongoDB from "./image/logo_mongodb_icon.svg"; import JavaScript from "./image/logo-javascript.svg"; import NodeJS from "./image/logo_nodejs_icon.svg"; import Express from "./image/expressjs-icon.svg"; import Python from "./image/python-4.svg"; function Main() { const images = [ { src: "ReactLogo", alt: "react" }, { src: "Typescript", alt: "typescript" }, { src: "MongoDB", alt: "mngodb" }, { src: "Javascript", alt: "javascript" }, { src: "NodeJS", alt: "nodejs" }, { src: "Express", alt: "express" }, { src: "Python", alt: "python" }, ]; return ( <div> <div> {images.map((image, index) => ( <img key={index} src={image.src} alt={image.alt} /> ))} </div> </div> ); } export default Main; ``` i am trying to add svg icons of various programming languages to my site but they are NOT displaying and just showing the alt text. the svgs were downloaded online and are imported correctly i tried uploading svgs but they are not displaying. this is a jsx file
svg image is not displaying
|reactjs|vite|
null
I am facing this when i go to localhost > Your PHP installation appears to be missing the MySQL extension which is required by WordPress. > >Please check that the mysqli PHP extension is installed and enabled. > >If you are unsure what these terms mean you should probably contact your host. If you still need help you can always visit the WordPress support forums. I have followed and each and every step [from here][1] Kindly tell me the appropriate solution i could not find any [1]: https://ubuntu.com/tutorials/install-and-configure-wordpress
I am suddenly getting a CS1002 error on an aspx page when it was working fine. The code: <ItemTemplate> <div class="swatchBox" > <%#Eval("SwatchName") %><br /> <%#Eval("RGB") %> </div> </ItemTemplate> The compiler expects a semicolon on the Eval("RGB") line, but no documentation I find specifies a semicolon when using Eval(). Any ideas? If I remove this line, it just reports the same error on the preceeding line.
How can I change the arrange of correlation, it is setting ordinal alpha for me How can I change the arrange of correlation, it is setting ordinal alpha for me How can I change the arrange of correlation, it is setting ordinal alpha for me
How can I change the sort of corelation, it is setting auto for me
|pandas-profiling|
null
I have an energy counter (kWh) recorded in a MySQL database every 15 minutes. Sometimes the recording fails for several reasons (power outage, computer reboot for updates...) and values are missing. The table looks as followed: ``` id Time Energy 27800 13.02.2024 23:30:01 651720048 27801 13.02.2024 23:45:00 651720672 (missing) 27802 14.02.2024 00:15:02 651721917 27803 14.02.2024 00:30:00 651722540 27804 14.02.2024 00:45:00 651723129 27805 14.02.2024 01:00:02 651723769 27806 14.02.2024 01:15:01 651724405 27807 14.02.2024 01:30:01 651725030 (missing) 27808 14.02.2024 02:00:01 651726275 27809 14.02.2024 02:15:02 651726880 27810 14.02.2024 02:30:01 651727519 27811 14.02.2024 02:45:00 651728130 27812 14.02.2024 03:00:02 651728751 27813 14.02.2024 03:15:02 651729381 ``` I am looking for a SQL query which returns the consumption (spread/difference between energy counter values) in a certain (variable) time span (eg. 15 minutes, 60 minutes, 24 hours, 1 month...) which also considers missing values by interpolation. The result should look as showed there in the columns `Consumption 15m` and `Consumption 1h`: ``` id Time Energy Consumption 15m Consumption 1h 27800 13.02.2024 23:30:01 651720048 - 27801 13.02.2024 23:45:00 651720672 624 (missing) 651721294.5 622.5 - 27802 14.02.2024 00:15:02 651721917 622.5 27803 14.02.2024 00:30:00 651722540 623 27804 14.02.2024 00:45:00 651723129 589 27805 14.02.2024 01:00:02 651723769 640 2474,5 27806 14.02.2024 01:15:01 651724405 636 27807 14.02.2024 01:30:01 651725030 625 (missing) 651725652.5 622.5 27808 14.02.2024 02:00:01 651726275 622.5 2506 27809 14.02.2024 02:15:02 651726880 605 27810 14.02.2024 02:30:01 651727519 639 27811 14.02.2024 02:45:00 651728130 611 27812 14.02.2024 03:00:02 651728751 621 2476 27813 14.02.2024 03:15:02 651729381 630 ``` I guess it is somewhow required to find the closest two values of two given time points (e.g. 14.02.2024 00:00:00 and 14.02.2024 01:00:00) and create an interpolated value of the energy counter to build then the difference of it. Which query could achieve that desired result?
`mov eax, num` eax = address of num, my debugger shows value 00402000. `mov ebx, [array+8]` ebx = 00050004. `cmp eax,ebx` eax >= ebx so code jumps to `skip` label. Write function prints `0x0A` which is `new line` code. If You change to `0x35` You will see `5`. `printdigit` code is never executed.
i ran brew reinstall libvmaf to reinstall libvmaf, as my own error was Library not loaded: /usr/local/opt/libvmaf/lib/libvmaf.1.dylib and also i got this error too '/usr/local/opt/libvmaf/lib/libvmaf.1.dylib' (no such file), but after running brew reinstall libvmaf it fixed my issue if this does not work for kindly use another answer, there is no need to drop a minus point, thanks
I need to extract info from a professional experience section like the following and store the result in a dataframe. https://www.linkedin.com/in/maxlvsq/details/experience/ [example][1] I have been reading about how to do it, including this stack overflow thread: https://stackoverflow.com/questions/75539164/get-the-experience-section-of-a-linkedin-profile-with-selenium-and-python, which proposes this solution: jobs = driver.find_elements(By.CSS_SELECTOR, 'section:has(#experience)>div>ul>li') for job in jobs: exp['job'] += [job.find_element(By.CSS_SELECTOR, 'span[class="mr1 t-bold"] span').text] exp['company'] += [job.find_element(By.CSS_SELECTOR, 'span[class="t-14 t-normal"] span').text] exp['date'] += [job.find_element(By.CSS_SELECTOR, 'span[class="t-14 t-normal t-black--light"] span').text] try: exp['location'] += [job.find_element(By.CSS_SELECTOR, 'span[class="t-14 t-normal t-black--light"]:nth-child(4) span').text] except NoSuchElementException: exp['location'] += ['*missing value*'] try: exp['description'] += [job.find_element(By.CSS_SELECTOR, 'ul li ul span[aria-hidden=true]').text] except NoSuchElementException: exp['description'] += ['*missing value*'] This solution however does not work for me, because the elements do not exist anymore under those names. Here is what I tried. I can get out the description and timeframes (but I face the issue that the lists have different length). For the position, company name, and location I have not been able to find the class or id names. # description descriptions = driver.find_elements(By.CLASS_NAME, 'pvs-list__outer-container') # timeframes timeframes = driver.find_elements(By.CLASS_NAME, 'pvs-entity__caption-wrapper') Is there anyone who knows how to fix that? Thanks :) [1]: https://i.stack.imgur.com/j8asV.png
I am making a UI with Swing, and I made a `JPopupMenu` to add to a `JMenu` for my top bar, but the `paintComponent()` function never get called. I saw online i couldn't have a size of `0,0` this was default and when I changed it still didn't call paintComponent. I am using `java 17`. ```java public class PopUpMenu extends JPopupMenu { public PopUpMenu() { setBackground(UI.tertiaryColor); setForeground(UI.tertiaryColor); } @Override protected void paintComponent(Graphics g) { System.out.println("painting"); super.paintComponent(g); g.setColor(UI.tertiaryColor); Graphics2D g2 = (Graphics2D) g; g2.setColor(UI.tertiaryColor); g2.fillRect(0, 0, (int) getPreferredSize().getWidth(), (int) getPreferredSize().getHeight()); } } ``` ```java public class Menu extends JMenu { Color highlite = new Color(0x3e90ff); int xOffSetText = 5; public Menu(String text) { super(text); init(); } public Menu(String text, int xOffSetText) { super(text); this.xOffSetText = xOffSetText; init(); } private void init() { setFont(UI.getFont(16)); setBackground(UI.mainColor); setForeground(UI.textColor); setPreferredSize(new Dimension((int) getPreferredSize().getWidth(), 25)); setContentAreaFilled(false); setBorderPainted(false); setSelected(false); PopUpMenu popUpMenu = new PopUpMenu(); setComponentPopupMenu(popUpMenu); } @Override protected void paintComponent(Graphics g) { g.setColor(UI.mainColor); Graphics2D g2 = (Graphics2D) g; if (getModel().isSelected()) { g2.setColor(highlite); } else { g2.setColor(UI.mainColor); } g2.fillRect(0, 0, getWidth(), getHeight()); if (getModel().isSelected()) { g2.setColor(UI.mainColor); } else { g2.setColor(UI.textColor); } g2.drawString(getText(), xOffSetText, 20); } } ``` edit: I implemented all the functions related to the `popupMenu` from `JMenu` into my own `Menu` class. It does call the `paintComponent` function, but doesn't draw anything. These are my new classes: ```java package org.example.uiComponents; import org.example.UI; import javax.swing.*; import java.awt.*; public class PopUpMenu extends JPopupMenu { public PopUpMenu() { setBackground(Color.white); setForeground(Color.white); System.out.println("popup"); } @Override protected void paintComponent(Graphics g) { System.out.println("painting123...."); g.setColor(UI.tertiaryColor); super.paintComponent(g); Graphics2D g2 = (Graphics2D) g; g2.setColor(UI.tertiaryColor); g2.fillRect((int) getAlignmentX(), (int) getAlignmentY(), (int) getPreferredSize().getWidth(), (int) getPreferredSize().getHeight()); } } ``` ```java public class Menu extends JMenu { Color highlite = new Color(0x3e90ff); int xOffSetText = 5; PopUpMenu popupMenu = null; public Menu(String text) { super(text); init(); } public Menu(String text, int xOffSetText) { super(text); this.xOffSetText = xOffSetText; init(); } private void init() { setFont(UI.getFont(16)); setBackground(UI.mainColor); setForeground(UI.textColor); setPreferredSize(new Dimension((int) getPreferredSize().getWidth(), 25)); setContentAreaFilled(false); setBorderPainted(false); setSelected(false); PopUpMenu popUpMenu = new PopUpMenu(); //setComponentPopupMenu(popUpMenu); } private void ensurePopupMenuCreated() { if (popupMenu == null) { this.popupMenu = new PopUpMenu(); popupMenu.setInvoker(this); popupListener = createWinListener(popupMenu); } } @Override public void updateUI() { setUI((MenuItemUI)UIManager.getUI(this)); if ( popupMenu != null ) { popupMenu.setUI((PopupMenuUI)UIManager.getUI(popupMenu)); } } /** * Returns true if the menu's popup window is visible. * * @return true if the menu is visible, else false */ @Override public boolean isPopupMenuVisible() { ensurePopupMenuCreated(); return popupMenu.isVisible(); } /** * The window-closing listener for the popup. * * @see JMenu.WinListener */ protected JMenu.WinListener popupListener; /** * Sets the location of the popup component. * * @param x the x coordinate of the popup's new position * @param y the y coordinate of the popup's new position */ @Override public void setMenuLocation(int x, int y) { setMenuLocation(x, y); if (popupMenu != null) popupMenu.setLocation(x, y); } /** * Appends a menu item to the end of this menu. * Returns the menu item added. * * @param menuItem the <code>JMenuitem</code> to be added * @return the <code>JMenuItem</code> added */ @Override public JMenuItem add(JMenuItem menuItem) { ensurePopupMenuCreated(); return popupMenu.add(menuItem); } /** * Appends a component to the end of this menu. * Returns the component added. * * @param c the <code>Component</code> to add * @return the <code>Component</code> added */ @Override public Component add(Component c) { ensurePopupMenuCreated(); popupMenu.add(c); return c; } /** * Adds the specified component to this container at the given * position. If <code>index</code> equals -1, the component will * be appended to the end. * @param c the <code>Component</code> to add * @param index the position at which to insert the component * @return the <code>Component</code> added * @see #remove * @see java.awt.Container#add(Component, int) */ @Override public Component add(Component c, int index) { ensurePopupMenuCreated(); popupMenu.add(c, index); return c; } /** * Appends a new separator to the end of the menu. */ @Override public void addSeparator() { ensurePopupMenuCreated(); popupMenu.addSeparator(); } /** * Inserts a new menu item with the specified text at a * given position. * * @param s the text for the menu item to add * @param pos an integer specifying the position at which to add the * new menu item * @exception IllegalArgumentException when the value of * <code>pos</code> &lt; 0 */ @Override public void insert(String s, int pos) { if (pos < 0) { throw new IllegalArgumentException("index less than zero."); } ensurePopupMenuCreated(); popupMenu.insert(new JMenuItem(s), pos); } /** * Inserts the specified <code>JMenuitem</code> at a given position. * * @param mi the <code>JMenuitem</code> to add * @param pos an integer specifying the position at which to add the * new <code>JMenuitem</code> * @return the new menu item * @exception IllegalArgumentException if the value of * <code>pos</code> &lt; 0 */ @Override public JMenuItem insert(JMenuItem mi, int pos) { if (pos < 0) { throw new IllegalArgumentException("index less than zero."); } ensurePopupMenuCreated(); popupMenu.insert(mi, pos); return mi; } /** * Inserts a new menu item attached to the specified <code>Action</code> * object at a given position. * * @param a the <code>Action</code> object for the menu item to add * @param pos an integer specifying the position at which to add the * new menu item * @return the new menu item * @exception IllegalArgumentException if the value of * <code>pos</code> &lt; 0 */ @Override public JMenuItem insert(Action a, int pos) { if (pos < 0) { throw new IllegalArgumentException("index less than zero."); } ensurePopupMenuCreated(); JMenuItem mi = new JMenuItem(a); mi.setHorizontalTextPosition(JButton.TRAILING); mi.setVerticalTextPosition(JButton.CENTER); popupMenu.insert(mi, pos); return mi; } /** * Inserts a separator at the specified position. * * @param index an integer specifying the position at which to * insert the menu separator * @exception IllegalArgumentException if the value of * <code>index</code> &lt; 0 */ @Override public void insertSeparator(int index) { if (index < 0) { throw new IllegalArgumentException("index less than zero."); } ensurePopupMenuCreated(); popupMenu.insert( new JPopupMenu.Separator(), index ); } /** * Removes the specified menu item from this menu. If there is no * popup menu, this method will have no effect. * * @param item the <code>JMenuItem</code> to be removed from the menu */ @Override public void remove(JMenuItem item) { if (popupMenu != null) popupMenu.remove(item); } /** * Removes the menu item at the specified index from this menu. * * @param pos the position of the item to be removed * @exception IllegalArgumentException if the value of * <code>pos</code> &lt; 0, or if <code>pos</code> * is greater than the number of menu items */ @Override public void remove(int pos) { if (pos < 0) { throw new IllegalArgumentException("index less than zero."); } if (pos > getItemCount()) { throw new IllegalArgumentException("index greater than the number of items."); } if (popupMenu != null) popupMenu.remove(pos); } /** * Removes the component <code>c</code> from this menu. * * @param c the component to be removed */ @Override public void remove(Component c) { if (popupMenu != null) popupMenu.remove(c); } /** * Removes all menu items from this menu. */ @Override public void removeAll() { if (popupMenu != null) popupMenu.removeAll(); } /** * Returns the number of components on the menu. * * @return an integer containing the number of components on the menu */ @Override @BeanProperty(bound = false) public int getMenuComponentCount() { int componentCount = 0; if (popupMenu != null) componentCount = popupMenu.getComponentCount(); return componentCount; } /** * Returns the component at position <code>n</code>. * * @param n the position of the component to be returned * @return the component requested, or <code>null</code> * if there is no popup menu * */ @Override public Component getMenuComponent(int n) { if (popupMenu != null) return popupMenu.getComponent(n); return null; } /** * Returns an array of <code>Component</code>s of the menu's * subcomponents. Note that this returns all <code>Component</code>s * in the popup menu, including separators. * * @return an array of <code>Component</code>s or an empty array * if there is no popup menu */ @Override @BeanProperty(bound = false) public Component[] getMenuComponents() { if (popupMenu != null) return popupMenu.getComponents(); return new Component[0]; } /** * A listener class that watches for a popup window closing. * When the popup is closing, the listener deselects the menu. * <p> * <strong>Warning:</strong> * Serialized objects of this class will not be compatible with * future Swing releases. The current serialization support is * appropriate for short term storage or RMI between applications running * the same version of Swing. As of 1.4, support for long term storage * of all JavaBeans * has been added to the <code>java.beans</code> package. * Please see {@link java.beans.XMLEncoder}. */ @SuppressWarnings("serial") protected class WinListener extends WindowAdapter implements Serializable { JPopupMenu popupMenu; /** * Create the window listener for the specified popup. * * @param p the popup menu for which to create a listener * @since 1.4 */ public WinListener(JPopupMenu p) { this.popupMenu = p; } /** * Deselect the menu when the popup is closed from outside. */ public void windowClosing(WindowEvent e) { setSelected(false); } } /** * Returns an array of <code>MenuElement</code>s containing the submenu * for this menu component. If popup menu is <code>null</code> returns * an empty array. This method is required to conform to the * <code>MenuElement</code> interface. Note that since * <code>JSeparator</code>s do not conform to the <code>MenuElement</code> * interface, this array will only contain <code>JMenuItem</code>s. * * @return an array of <code>MenuElement</code> objects */ @Override @BeanProperty(bound = false) public MenuElement[] getSubElements() { if(popupMenu == null) return new MenuElement[0]; else { MenuElement[] result = new MenuElement[1]; result[0] = popupMenu; return result; } } /** * Sets the <code>ComponentOrientation</code> property of this menu * and all components contained within it. This includes all * components returned by {@link #getMenuComponents getMenuComponents}. * * @param o the new component orientation of this menu and * the components contained within it. * @exception NullPointerException if <code>orientation</code> is null. * @see java.awt.Component#setComponentOrientation * @see java.awt.Component#getComponentOrientation * @since 1.4 */ @Override public void applyComponentOrientation(ComponentOrientation o) { super.applyComponentOrientation(o); if ( popupMenu != null ) { int ncomponents = getMenuComponentCount(); for (int i = 0 ; i < ncomponents ; ++i) { getMenuComponent(i).applyComponentOrientation(o); } popupMenu.setComponentOrientation(o); } } /** * Sets the orientation for this menu and its associated popup menu * determined by the {@code ComponentOrientation} argument. * * @param o the new orientation for this menu and * its associated popup menu. */ @Override public void setComponentOrientation(ComponentOrientation o) { super.setComponentOrientation(o); if ( popupMenu != null ) { popupMenu.setComponentOrientation(o); } } @Override public JPopupMenu getPopupMenu() { ensurePopupMenuCreated(); return popupMenu; } @Override protected void paintComponent(Graphics g) { g.setColor(UI.mainColor); super.paintComponent(g); Graphics2D g2 = (Graphics2D) g; if (getModel().isSelected()) { g2.setColor(highlite); } else { g2.setColor(UI.mainColor); } g2.fillRect(0, 0, getWidth(), getHeight()); if (getModel().isSelected()) { g2.setColor(UI.mainColor); } else { g2.setColor(UI.textColor); } g2.drawString(getText(), xOffSetText, 20); } } ```
I need to extract info from a professional experience section like the following and store the result in a dataframe. https://www.linkedin.com/in/maxlvsq/details/experience/ [example][1] I have been reading about how to do it, including this stack overflow thread: https://stackoverflow.com/questions/75539164/get-the-experience-section-of-a-linkedin-profile-with-selenium-and-python, which proposes this solution: jobs = driver.find_elements(By.CSS_SELECTOR, 'section:has(#experience)>div>ul>li') for job in jobs: exp['job'] += [job.find_element(By.CSS_SELECTOR, 'span[class="mr1 t-bold"] span').text] exp['company'] += [job.find_element(By.CSS_SELECTOR, 'span[class="t-14 t-normal"] span').text] exp['date'] += [job.find_element(By.CSS_SELECTOR, 'span[class="t-14 t-normal t-black--light"] span').text] try: exp['location'] += [job.find_element(By.CSS_SELECTOR, 'span[class="t-14 t-normal t-black--light"]:nth-child(4) span').text] except NoSuchElementException: exp['location'] += ['*missing value*'] try: exp['description'] += [job.find_element(By.CSS_SELECTOR, 'ul li ul span[aria-hidden=true]').text] except NoSuchElementException: exp['description'] += ['*missing value*'] This solution however does not work for me, because the elements do not exist anymore under those names. Here is what I tried. I can get out the description and timeframes (but I face the issue that the lists have different length). For the position, company name, and location I have not been able to find the class or id names. # description descriptions = driver.find_elements(By.CLASS_NAME, 'pvs-list__outer-container') # timeframes timeframes = driver.find_elements(By.CLASS_NAME, 'pvs-entity__caption-wrapper') Is there anyone who knows how to fix that? Thanks :) [1]: https://i.stack.imgur.com/j8asV.png
I have a project idea in mind and I don't know how to achieve it. Let me explain. My idea is to create a web app that suggests travel destination ideas depending on dates and a budget. But as far as I know all flight or hotel APIs available need a destination as a query parameter, so I'm stuck here. A workaround could be to create my own dataset of flight and hotel price, but I have no idea how to achieve this effectively and this is gonna take time and money to collect everything, so I'm not sure I can afford to do this. What do you think? Have you another idea to help me to achieve this idea?
{"Voters":[{"Id":724039,"DisplayName":"Luuk"},{"Id":9214357,"DisplayName":"Zephyr"},{"Id":466862,"DisplayName":"Mark Rotteveel"}],"SiteSpecificCloseReasonIds":[18]}
I need help with the Livewire component update based on the select dropdown. ``` class FutureTreeMapChart extends Component { public $segment = 'N50'; public $expiry = '2024-02-25'; public $data; public function fetchTreeMap() { if (!empty($this->segment) && !empty($this->expiry)) { .....some codes to get data from DB. .... $this-data = DB query. } $this->dispatch('dataUpdated'); } public function render() { $this->fetchTreeMap(); return view('livewire.future.future-tree-map-chart'); } } ``` Now in the component blade file, ``` @script <script> $wire.on('dataUpdated', () => { var rawData = {!! $data->toJson() !!}; console.log(rawData); console.log('updated'); }); </script> @endscript ``` Whenever I change ```segment``` or ```expiry``` I can see there is an update request sent to the server and I get a response, but the problem is that rawData always logs for ``` public $segment = 'N50';```, Even if I select a different option for ```segment`` it logs for N50 only, I did ```dd($this->data)``` on change, and it gets correct data from the database based on the selected segment, but on the script, it always prints one which is selected as public property, To me, it looks like some issues in Lifecycle, but I could not point out why ```rawData``` always gets the default ```segment`` data, What is wrong? Thanks,
Livewire component update with new data
|laravel|laravel-livewire|
is there anyone know hoy to access to the BIOS in a thomson SP-HERO91.1BK32, because i want to reset windows and make it a new pc so i tried all the posible keys but I haven't made it how to acces to the bios in a thomson SP-HERO91.1BK32
how to access to the bios in a thomson SP-HERO91.1BK32
|bios|
null
Is this what you’re trying to do? `cond` provides the N different conditions (i.e., a loop-variable-dependent bool function) and `foo` introduces recursion: ```cpp #include <iostream> bool cond(int cond_which, int current_loop_variable) { switch (cond_which) { case 0: return current_loop_variable < 5; case 1: return current_loop_variable < 3; /* More... can be a hell of complicated, related with states, whatever */ default: return false; } } void foo(int we_may_call_it_the_meta_loop_variable) { for (int i = 0; cond(we_may_call_it_the_meta_loop_variable, i); ++i) { foo(we_may_call_it_the_meta_loop_variable + 1); std::cout << "in loop " << we_may_call_it_the_meta_loop_variable << ", i = " << i << std::endl; } }; int main() { foo(0); return 0; } ``` Clearly this is not an infinite recursion.
VS error on aspx file Eval(), expecting semi-colon
|c#|asp.net|itemtemplate|
I have DateTime string in following format: > 3/15/24 4:25:51.000 PM EST And I need to parse it. I was able to work out template as below: > M/d/yy h:mm:ss.fff tt K And it's almost OK, but iit doesn't recognize "EST" code and it shows TimeZone as below: > 3/15/24 4:25:51.000 PM -05.00 How could I cope with this? How can I provide format for TimeZone codes?
TimeZone Codes in DateTime Formatter
|c#|.net|
|java|spring-boot|redis|spring-data-redis|jedis|
# You have not included the script in your HTML In order to execute the script, you need to add a `<script>` element into your HTML document. ```html <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <script src="code.js" defer></script> </head> <body> <div class="container"> <h2><span id="count">0</span></h2> <button id="decBtn" class="button" onclick="onDec()">-</button> <button id="incBtn" class="button" onclick="onInc()">+</button> </div> </body> </html> ``` Notice I've modified your filename to `code.js` and I've used the `defer` keyword to ensure the code runs *after* the HTML loads.
Is it a good practice to use `Inertia.reload()` in your laravel project when you want to reload your component after a post request? If you think there is another way that would be better don't hesitate to suggest me. **Front React** ``` const addToFavorite = async (videogameId: number) => { await axios.post(route("favorites.store"), { videogame_id: videogameId, user_id: currentUserId, }); Inertia.reload(); }; ``` ---------- ``` <button type="button" onClick={() => addToFavorite(videogame.id)}> <StarIcon /> </button> ``` ---------- **Controller** ``` public function store(FavoriteRequest $request) { $favorite = Favorites::create($request->all()); $favorite->save(); return redirect()->back(); } ```
In base R you could do something like: ```r combo <- combn(names(emot)[-1], 2) t(combn(names(emot)[-1], 2)) |> as.data.frame() |> setNames(c("target", "source")) |> transform(count = sapply(asplit(combo, 2), \(x) sum(rowSums(emot[,x]) == length(x)))) ``` Basically, get all the combinations of your column names, excluding `id`, and then iterate to retrieve those columns and apply some logic. **Output** ``` target source count 1 happy sad 0 2 happy angry 0 3 happy excited 2 4 sad angry 0 5 sad excited 1 6 angry excited 0 ```
It prevents of registering users over admin area, REST and xml rpc function execute_on_register_post_event($sanitized_user_login, $user_email, $errors){ wp_die('Forbidden, is manualy disabled by pwa'); } add_action( "register_post", "execute_on_register_post_event" , 10, 3); add_filter( 'pre_user_login' , 'my_username_block' ); function my_username_block( $user_login ) { wp_die('Forbidden, is manualy disabled by pwa'); }
I need to determine the generic type(s) applied to a Java `Object` at runtime. For a situation like `Map<String, String>`, that is rather easy. I have code that looks like this: protected Class<?>[] getGenericParameterTypes(Field field) { ParameterizedType pt = (ParameterizedType) field.getGenericType(); Type[] types = pt.getActualTypeArguments(); Class<?>[] ptClasses = new Class<?>[types.length]; for (int i = 0; i < types.length; i++) { ptClasses[i] = (Class<?>) types[i]; } return ptClasses; } This works fine for the simple use case. What I'm struggling with is a situation that popped up where I have a more complex `Map`, like `Map<String, List<String>>` or `Map<String, List<List<String>>>`. How do I apply this logic to get the types/parameterized types for this `Map`?
Java Reflection - Get generic type, with possible generic of generic?
|java|generics|reflection|
I have Stable Diffusion running in a VM in GCP. I want to generate a picture based on text but also have a specific word in the background. For example: "City skyline" as the picture and "New York" as a text in the background. I have only found solutions where you either add a picture with the background text or uses python to create pil images. Is there a way to send the background text as a parameter? I am creating a .NET service. The api for /sdapi/v1/txt2img is this: { "prompt": "City skyline", "negative_prompt": "", "styles": [ "string" ], "seed": -1, "subseed": -1, "subseed_strength": 0, "seed_resize_from_h": -1, "seed_resize_from_w": -1, "sampler_name": "string", "batch_size": 1, "n_iter": 1, "steps": 50, "cfg_scale": 7, "width": 512, "height": 512, "restore_faces": true, "tiling": true, "do_not_save_samples": false, "do_not_save_grid": false, "eta": 0, "denoising_strength": 0, "s_min_uncond": 0, "s_churn": 0, "s_tmax": 0, "s_tmin": 0, "s_noise": 0, "override_settings": {}, "override_settings_restore_afterwards": true, "refiner_checkpoint": "string", "refiner_switch_at": 0, "disable_extra_networks": false, "comments": {}, "enable_hr": false, "firstphase_width": 0, "firstphase_height": 0, "hr_scale": 2, "hr_upscaler": "string", "hr_second_pass_steps": 0, "hr_resize_x": 0, "hr_resize_y": 0, "hr_checkpoint_name": "string", "hr_sampler_name": "string", "hr_prompt": "", "hr_negative_prompt": "", "sampler_index": "Euler", "script_name": "string", "script_args": [], "send_images": true, "save_images": false, "alwayson_scripts": {} }
Stable Diffusion, how to set a background text using the /sdapi/v1/txt2img
|stable-diffusion|
i have a zsh [plugin](https://github.com/babarot/enhancd), thru [zplug](https://github.com/zplug/zplug) installed to `$HOME/.zplug/repos/babarot/enhancd`, and it exposes a function: `__enhancd::cd`. now, what i would like to be able to do is to spawn a terminal running this zsh function. i tried running e.g.: `wezterm -e __enhancd::cd`. this fails however, stating this name could not be found on the `$PATH`. this makes me wonder: how might one manually ensure such functions get loaded while still being able to invoke those functions from the moment the terminal spawns?
{"OriginalQuestionIds":[37984906],"Voters":[{"Id":14853083,"DisplayName":"Tangentially Perpendicular"},{"Id":1509264,"DisplayName":"MT0","BindingReason":{"GoldTagBadge":"sql"}}]}
I regularly work with Python files that are provided to me as templates, which use an indentation of 2. However, I personally prefer working with an indentation width of 4, which is what I've set in my `.vimrc`. However, because of the indentation-sensitivity of Python, the typical `gg=G` way to fix indentation to my preferred indentation width does not work well at all to convert a file to my preferred indentation. Furthermore, just leaving the indentation at a width of 2 screws up with my tabstop settings. To fix this, what I'd like to do is have some system to convert a 2-space indented file into a 4-space indented file. I don't know what the easiest way to do this would be, but I'm thinking to `vmap <Tab>` to increase the tab width of the selected lines by 1, and `vmap <S-Tab>` to decrease the width by 1. I don't know if there is some built-in method to do this, or if this would require some find/replace rule, but I think having some way to fix the indentation to my preferred width would be useful, given that the autoindent is not smart enough to fix this properly.
Today I upgraded Symfony-cli to version 5.8.13 with brew. In my project, I start a new web server: `Symfony-cli server:start` After that I open my browser to 127.0.0.1:8000, but my web server Symfony crashes ```none 2024/03/23 10:19:36 http: panic serving 127.0.0.1:49889: runtime error: index out of range [0] with length 0 goroutine 35 [running]: net/http.(*conn).serve.func1() net/http/server.go:1898 +0xbe panic({0x102440c0?, 0xc00038e120?}) runtime/panic.go:770 +0x132 github.com/symfony-cli/symfony-cli/envs.(*Local).webServer(0xc000430660) github.com/symfony-cli/symfony-cli/envs/local.go:262 +0x5b8 github.com/symfony-cli/symfony-cli/envs.(*Local).Extra(0xc000430660) github.com/symfony-cli/symfony-cli/envs/local.go:210 +0x38f github.com/symfony-cli/symfony-cli/envs.AsMap({0x10297800, 0xc000430660}) github.com/symfony-cli/symfony-cli/envs/envs.go:86 +0x258 github.com/symfony-cli/symfony-cli/local/php.(*Server).generateEnv(0xc000177340, 0xc00037e120) github.com/symfony-cli/symfony-cli/local/php/envs.go:76 +0x9f8 github.com/symfony-cli/symfony-cli/local/php.(*Server).Serve(0xc000177340, {0x10294898, 0xc000404000}, 0xc00037e120, 0xc000430600) github.com/symfony-cli/symfony-cli/local/php/php_server.go:209 +0x7f github.com/symfony-cli/symfony-cli/local/http.(*Server).Handler(0xc000385a00, {0x10294898, 0xc000404000}, 0xc00037e120) github.com/symfony-cli/symfony-cli/local/http/http.go:244 +0x538 github.com/symfony-cli/symfony-cli/local/http.(*Server).ProxyHandler(0xc000385a00, {0x10294448, 0xc0001761c0}, 0xc00037e120) github.com/symfony-cli/symfony-cli/local/http/http.go:187 +0x2d8 net/http.HandlerFunc.ServeHTTP(0xfa15cb9?, {0x10294448?, 0xc0001761c0?}, 0xc0003c3b68?) net/http/server.go:2166 +0x29 net/http.serverHandler.ServeHTTP({0xc0004300f0?}, {0x10294448?, 0xc0001761c0?}, 0x6?) net/http/server.go:3137 +0x8e net/http.(*conn).serve(0xc000488090, {0x102956f0, 0xc0003400f0}) net/http/server.go:2039 +0x5e8 created by net/http.(*Server).Serve in goroutine 54 net/http/server.go:3285 +0x4b4 ``` I tested on another machine and I have the same problem.
I have an esp32 and i wish to use it to drive a HC-SR04 sonar module. I use interrupts to get information from sensors,then I use a queue to pass the data to a freertos task to output it. At first, it work and output the correct data, but after few second, it report an error and reboot. Here is the error: Guru Meditation Error: Core 1 panic'ed (LoadProhibited). Exception was unhandled. Core 1 register dump: PC : 0x40084c90 PS : 0x00050631 A0 : 0x800d31c4 A1 : 0x3ffbf53c A2 : 0x00000040 A3 : 0x00018040 A4 : 0x000637ff A5 : 0x3ffbf50c A6 : 0x00000008 A7 : 0x00000000 A8 : 0x00000001 A9 : 0x4008bf6e A10 : 0x00060b23 A11 : 0x3ffc4a14 A12 : 0x3ff44000 A13 : 0xffffff00 A14 : 0x00000000 A15 : 0x00000020 SAR : 0x0000001d EXCCAUSE: 0x0000001c EXCVADDR: 0x800d31d0 LBEG : 0x400899a4 LEND : 0x400899ba LCOUNT : 0xffffffff Backtrace: 0x40084c8d:0x3ffbf53c |<-CORRUPTED Then I found that if I delete the code that were used to push the data to the queue, it will work normally. So I guass that is the problem,but I don't Know how to fix it. Here is main: ``` radar radar0(25,35); void setup() { // put your setup code here, to run once: Serial.begin(115200); Serial.setDebugOutput(true); radar0.start(); } ``` Here is how radar class define: ``` class radar { private: uint8_t txPin,rxPin; Ticker loopTrigger; //ticker that use to trigger loop Ticker singalEnder; //ticker that use to generate a 1ms pulse QueueHandle_t dstQueue; //queue that use to pass dst to coroutine float previousDst; bool enable; unsigned long echoStartTime; //The time the echo start received void loop(); void echoStartHandler(); //callback when the echo start void echoEndHandler(); //callback when the echo end void queueListener(); public: radar(uint8_t txPin,uint8_t rxPin); void start(); }; radar::radar(uint8_t txPin,uint8_t rxPin){ this->txPin=txPin; this->rxPin=rxPin; this->enable=true; this->dstQueue = xQueueCreate(4,sizeof(float)); } void radar::start(){ //set pin mode pinMode(this->txPin,OUTPUT); pinMode(this->rxPin,INPUT); //low down the txPin digitalWrite(this->txPin,LOW); //Create a coroutine for listening to the dstQueue auto fn = [](void *arg){static_cast<radar*>(arg)->queueListener();}; xTaskCreate(fn,"dstListener",1024,this,0,NULL); //enable the radar this->enable=true; this->loop(); } void radar::queueListener(){ float dst; while (this->enable) { if (xQueueReceive(this->dstQueue,&dst,0)==pdFALSE){ //sleep 10ms if the queue is empty vTaskDelay(10/portTICK_PERIOD_MS); continue; } if (abs(dst-this->previousDst)>5){ Serial.println(dst); this->previousDst=dst; } } vTaskDelete(NULL); } void radar::echoStartHandler(){ this->echoStartTime = micros(); //Set rxPin pull-down interrupt attachInterruptArg(rxPin,[](void* r){static_cast<radar*>(r)->echoEndHandler();},this,FALLING); } void radar::echoEndHandler(){ detachInterrupt(this->rxPin); unsigned long echoEndTime = micros(); float pluseTime; if (echoEndTime > this->echoStartTime){ //If the variable does not overflow pluseTime = echoEndTime - this->echoStartTime; }else{ pluseTime = echoEndTime + (LONG_MAX - this->echoStartTime); } float dst = pluseTime * 0.0173; //push the dst to queue BaseType_t xHigherPriorityTaskWoken; xQueueSendFromISR(this->dstQueue,&dst,&xHigherPriorityTaskWoken); if (xHigherPriorityTaskWoken==pdTRUE){ portYIELD_FROM_ISR(); } } void radar::loop(){ if (!this->enable){ return; } //Set loop() to be triggered after 100ms this->loopTrigger.once_ms<radar*>(100,[](radar* r){r->loop();},this); //Generate a 1ms pulse at txPin digitalWrite(this->txPin,HIGH); this->singalEnder.once_ms<uint8_t>(1,[](uint8_t pin){digitalWrite(pin,LOW);},this->txPin); //Set rxPin pull-up callback attachInterruptArg(rxPin,[](void* r){static_cast<radar*>(r)->echoStartHandler();},this,RISING); } ``` Thank for your help! ps: Please forgive my poor English.I'm not a native speaker.
`valueFormatter` does work with sunburst. For `valueFormatter` to work properly, 1. It shouldn't be used along with `formatter` 2. EChart version should be at least 5.3.0 To separate thousands, this part: ``` tooltip: { trigger: 'item', formatter: '{b}:<br/><b>{c}</b>', }, ``` Has to be replaced by: ``` tooltip: { trigger: 'item', valueFormatter: value => value.toLocaleString(), }, ```
Here is what worked for me: Delete **package-lock.json** Then try to redeploy your project `firebase deploy` NB: this solution is not ideal but that's the only thing that's working for me at the moment
Recently added an experimental implementation of server contexts to the [next-impl-getters][1] package. The implementation API mirrors client contexts, so there should be no difficulties in using them. The alternative is to use the [unstable_cache][2] function. [1]: https://github.com/vordgi/next-impl-getters [2]: https://nextjs.org/docs/app/api-reference/functions/unstable_cache
Try this: <p-tree [value]="files"> <ng-template let-node pTemplate="default"> {{ node.label }} </ng-template> </p-tree> https://www.primefaces.org/primeng-v16-lts/tree#template
I would suggest to use Winulator or Box86 in Termux. I have found in personal experience that QEMU is very slow to load, slow after loading, and very memory hungry.
{"Voters":[{"Id":87189,"DisplayName":"tadman"},{"Id":9223839,"DisplayName":"Joakim Danielson"},{"Id":3695849,"DisplayName":"Teja Nandamuri"}]}
Given an linear system Ax=b, x = [x1; x2], where A,b are given and x1 is also given. A is symmetric. I want to compute the gradient of x1 in terms of A,b, i.e. dx1/dA, dx1/db. It seems that torch.autograd.backward() can only compute the gradient by solving the whole linear system. But I want to make it more efficient by not solving x1 again since it is already given. Is it feasible? If so, how to implement it using pytorch? For now, I only know how to get the gradient by solving the whole system: ``` #[A1 A2; A3 A4] * [x1; x2] = [b1; b2] m1 = 10 n1 = 10 m3 = 5 n3 = n1 m2 = m1 n2 = m1 + m3 - n1 m4 = m3 n4 = n2 A = torch.rand((m1+m3,n1+n2)).clone().detach().requires_grad_(True) A1 = A[:m1,:n1] A2 = A[:m1,n1:] A3 = A[m1:,:n1] A4 = A[m1:,n1:] x1 = torch.ones((n1,1)).clone().detach().requires_grad_(True) x2_gt = torch.rand((n2,1)) b1 = (A1 @ x1 + A2 @ x2_gt).detach().requires_grad_(True) b2 = (A3 @ x1 + A4 @ x2_gt).detach().requires_grad_(True) b = torch.vstack((b1,b2)) x = torch.linalg.solve(A,b) x.backward(torch.ones(m1+m3,1)) ```
It is not necessary to notate these relationships in the model. The reason we write those relationships is that we can build queries easier. For example: you have a User model which has a one-to-many relationship with a Post model, you can define the relationships in the models like this: User.php public function posts(): HasMany { return $this->hasMany(Post::class) } Post.php public function user(): BelongsTo { return $this->belongsTo(User::class) } Then in your controllers you can easily get all the posts belonging to a user like this: $user = Auth::user(); // retrieve the authenticated user $posts = $user->posts(); // retrieve all the posts related to the user. Otherwise you would have to do it like this: $user = Auth::user(); // retrieve the authenticated user $posts = Post::where('user_id', $user->id); // retrieving all the posts This was ofcourse a simple example, but you can already see the power of Laravel's Eloquent relationships. Here you can read more about defining relationships and querying with Eloquent relationships: https://laravel.com/docs/10.x/eloquent-relationships So to summarize: you don't have to define the relationships in your models. The relationship is the fact that you have a foreign key. The reason why it is recommended to define the relationships in your models is so that you can take advantage of Laravel's power. I hope you understand it better now.
Is there a way to make this request with UrlFetchApp in app script? `curl -X GET http://test.com/api/demo -H 'Content-Type: application/json' -d '{"data": ["words"]}'` I attempted it with this code: ``` const response = UrlFetchApp.fetch(API_URL, { method: "GET", headers: { "Content-Type": "application/json" }, payload: JSON.stringify(payload) }); ``` *The payload and the endpoint are the exact same as the curl request which I tested* However I got this error "Failed to deserialize the JSON body into the target type: missing field name at line 1 column 88".
You could use subsetting in base R: df$newd <- df[-1][cbind(seq_len(nrow(df)), match(df$time, names(df)[-1]))] df time M0 M12 newd 1 M0 1 8 1 2 M12 2 5 5 3 M0 4 9 4 4 M0 5 2 5 5 M12 1 1 1 --- Another way-though abit inefficient: diag(as.matrix(df[df$time])) [1] 1 5 4 5 1
I have powershell code where I am trying to fetch the releases using azure devops rest api and able to do it successfully I am using below rest Api. Only the issue which I am facing is when I check from azure portal it is having more releases of that particular deployments whereas rest api is giving me only top 6-7 release information? GET https://vsrm.dev.azure.com/fabrikam/A13d3daac-03b8-4a23-9cc4-2c3de65dab63/_apis/release/deployments?definitionId=38&api-version=7.1-preview.2 Could someone tell me why this behavior?
Azure devops rest api is giving me only few releases information.?
|azure|azure-devops|azure-devops-rest-api|
`page:finish` is triggered when the page has been rendered. It does not wait for any API call the page might have made, which would then trigger further updates to the page layout. What should work is calling ``` nextTick(() => router.go()) ``` after the page updated the data. To my knowledge, it reloads the page softly, navigating to any `#hash` the URL might contain.
This 'Microsoft.Bcl.AsyncInterfaces' have dependencies on .NETFramework v4.6.2, .NETStandard v2.0 and v2.1. This dll is used in .NETFramework v4.8 application while accessing this dll i throws exception '**Could not load file or assembly 'netstandard, Version=2.1.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51' or one of its dependencies. The system cannot find the file specified.**'. Here i don't understand why it is trying to load netstandard 2.1 dll in a .NETFramework 4.8 application, so it is not supported or is it possible to skip loading the netstandard 2.1 dependency using config?. Please clarify this issue. In the `InnerException` and **FusionLog** log message says, it tries to load the netstandard v2.1 dll from different locations. [![enter image description here][1]][1] **Fusion Log:** [![enter image description here][2]][2] **.NETStandard v2.1 dependency:** [![enter image description here][3]][3] [1]: https://i.stack.imgur.com/QlV4I.png [2]: https://i.stack.imgur.com/oW5nP.png [3]: https://i.stack.imgur.com/ZZxiV.png
.Net 4.6 framework dll trying to load it's netstandard2.1 dependency
I have a C# DLL which already uses `CsvHelper` to read CSV files. So I was wondering if `CsvHelper` has the capacity for me to simply pass it a `string` (*not* a file) and it return the list of tokens? So much so, that: > 2023/11/06,Name,PartType,"“Hey, This is the Theme!”",1 becomes a list: 1. 2023/11/06 2. Name 3. PartType 4. “Hey, This is the Theme!” 5. 1 ---------- ## Update ## I have ended up with this C# method, based on some other answers and the comments below: public int ParseCSVText(string textToParse, string delimiter, out string[] tokens) { List<string> listTokens = new List<string>(); using (var stringReader = new StreamReader(textToParse)) { var config = new CsvConfiguration(CultureInfo.InvariantCulture); config.Delimiter = delimiter; config.HasHeaderRecord = false; using (var reader = new CsvReader(stringReader, config)) { while (reader.Read()) { listTokens.Add(reader.GetField(0)); listTokens.Add(reader.GetField(1)); listTokens.Add(reader.GetField(2)); listTokens.Add(reader.GetField(3)); listTokens.Add(reader.GetField(4)); } } } tokens = listTokens.ToArray(); return listTokens.Count; } The associated C++ wrapper: ```cpp bool CMSATools::ParseCSVText(const int fieldCount, const CString textToParse, const CString delimiter, CStringArray& listTokens) { SAFEARRAY* saTokens = nullptr; if (m_pInterface != nullptr) { long count{}; const auto hr = m_pInterface->ParseCSVText(textToParse.AllocSysString(), delimiter.AllocSysString(), &saTokens, &count); if (SUCCEEDED(hr)) ConvertSAFEARRAY<BSTR, CStringArray>(saTokens, listTokens); else throw_if_fail(hr); } return listTokens.GetSize() == fieldCount; } ``` But when I run my code, eg: ```cpp theApp.MSAToolsInterface().ParseCSVText(5, lineText, strDelimiter, listFields) ``` and go into debug the `HRESULT` of the C# is saying the *file can't be found*. There is no file - it is a string.
I am trying to use ```mutate``` + ```ifelse``` to create a new variable in the dataset. My example dataset is below ``` df = structure(list(id = c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10), resp_gender = c("female", "male", "female", "female", "male", "female", "male", "male", "female", "female"), hoh_gender = c("male", "male", "male", "male", "female", "male", "female", "female", "male", "male"), is_hoh = c("no", "no", "no", "yes", "no", "no", "yes", "no", "no", "yes"), gender_final = c("male", "male", "male", "female", "female", "male", "male", "female", "male", "female")), class = c("tbl_df", "tbl", "data.frame"), row.names = c(NA, -10L)) ``` The goal is to create the column gender_final so that if is_hoh == yes then it takes the value of hoh_gender and if it's no it takes the value of resp_gender. I am using the code below which seems not to be producing accurate results ``` mutate(gender_final = ifelse(is_hoh == "yes", hoh_gender, resp_gender)) ```
add `max-height: calc(100% - 1.4em);` to data class.
Note: I simplified the code for testing. I have an express.js route with the following code: ``` // /auth/register/confirm/:confirmationToken const registerConfirm = asyncHandler(async (req, res, next) => { console.log('registerConfirm'); res.status(httpStatus.OK).json({ msg: 'Registration confirmed' }); }); ``` I call it from Angular with the following code: ``` this.authService.registerConfirm('abcdef').subscribe(); ``` In my node.js console, I always get two lines with `registerConfirm` instead of one: ``` registerConfirm registerConfirm ``` It's as if it was making two `PUT` requests from Angular except that in my network's tab I only have one `OPTION` and one `PUT` call. I also tried to call this route from Postman and it worked properly. It doesn't work when the call is made from Angular. Edit: @Slang Here is where I declare the route as a PUT request: ``` import express from 'express'; import { registerConfirm } from '../controllers/auth.controller.js'; const router = express.Router(); router.put('/register/confirm/:confirmationToken', registerConfirm); export default router; ```
spawn terminal running zsh function from plugin
|shell|terminal|zsh|
{"OriginalQuestionIds":[70685602],"Voters":[{"Id":2886891,"DisplayName":"Honza Zidek"},{"Id":2696260,"DisplayName":"M. Deinum","BindingReason":{"GoldTagBadge":"java"}}]}
Is there a firewall rule you need to allow for clamav on port 3310? That solved the issue for me on AWS. I had to include an inbound rule for ClamAV on port 3310 to create a socket file.
In my case, I did not build "Authentication" in my Firebase project. After built it and configured providers, I could find the `CLIENT_ID` and `REVERSED_CLIENT_ID`.
Why aren't my card box shadows showing in the browser?
Using LEAD to get next distinct date
I wish to use flags such as `i` (case insensitive) and `s` (dot matches new line) in BigQuery using REGEXP_REPLACE. For the inputs, `My name is X`, `my Name is Y`, `MY NAME is Z`, i wish to replace X,Y,Z with some constant C, such that the output is for ex. `My name is C` I know that you can use these flags in the following way i.e `(?is:My name is )(\w+). `, however the first group becomes a non-capturing group, that doesnt allow me to refer to it via a number such as `\1` like this (since \1 refers to X, instead of `my name is`) `REGEXP_REPLACE(str, r'(?is:My name is )(\w+). ', r'\1 C')` How can i use flags with capturing groups?