instruction
stringlengths
0
30k
βŒ€
Almost got it. You missed referencing the second value. ```python values = ['done 0.0', 'done 3.9', 'failed system busy'] for v in values: match v.split(): case 'done', x if float(x) > 0: print('Well done') case 'done', x if float(x) == 0: print('It is okay') case 'failed', *rest: print(v) ``` Also, you may want to add a last case that catches the not covered ones: ```python case _: print('Any other case') ``` This is clearer and more concise than the `Γ¬f-then-else-try-catch` alternative. Actually, `match` was created just for cases like this one. That's why it's called _**structural pattern** matching_.
**I was facing the same issue**, Here is how I resolved this error: I installed `styled-components.macro` using `npm`. `npm i styled-components.macro --dev` [![enter image description here][1]][1] **And then use it like this:** `import styled from 'styled-components/macro';` [1]: https://i.stack.imgur.com/jt8kk.png
I am experimenting with `crash` utility that is used to decode linux kdump files. My setup consists of linux kernel 6.5 running on `qemu-system-aarch64`. The rootfs used is buildroot. I have edited the `/etc/init.d/rcS` to setup crashkernel and generate kdumps. ``` #hackish way of achieving things # Check if /proc/vmcore exists if [ -e "/proc/vmcore" ]; then echo "collecting core" # Get the current date and time TSTAMP=$(date +"%Y%m%d%H%M%S") # Define the filename for the kdump file FILENAME="kernel.${TSTAMP}.core.kdump" # Run makedumpfile to create the vmcore dump makedumpfile --message-level 4 -d 17,31 /proc/vmcore "${FILENAME}" reboot else echo "loading crashkernel into memory" # /proc/vmcore does not exist, so we run kexec kexec -p /Image --append="console=ttyAMA0,115200n8 root=/dev/nfs rw nfsroot=10.105.226.234:/home/naveen/nfsroot/rootfs-buildroot-arm64/,nolock,vers=4,tcp ip=10.105.226.235" fi ``` I developed a simplistic kernel module with below code, to generate crash due to null pointer dereference : ``` static int __init null_deref_module_init(void) { // Pointer to an integer, initialized to NULL int *null_pointer = NULL; printk(KERN_INFO "Null dereference module loaded\n"); // Dereferencing the NULL pointer to trigger a crash printk(KERN_INFO "Triggering null pointer dereference...\n"); *null_pointer = 1; // This line will cause a null pointer dereference return 0; // This will never be reached } ``` As soon as I load this kernel module, the qemu guest kernel crashes, as expected. And I have a successful kdump as well. When I go to decode this with kdump utility (tried multiple releases including latest 8.0.4), the utility itself crashes. What could be the possible reasons for the crash? ``` $ sudo crash ~/.repos/src/arm64/linux/vmlinux kernel.20240330170747.core.kdump crash 8.0.4 Copyright (C) 2002-2022 Red Hat, Inc. Copyright (C) 2004, 2005, 2006, 2010 IBM Corporation Copyright (C) 1999-2006 Hewlett-Packard Co Copyright (C) 2005, 2006, 2011, 2012 Fujitsu Limited Copyright (C) 2006, 2007 VA Linux Systems Japan K.K. Copyright (C) 2005, 2011, 2020-2022 NEC Corporation Copyright (C) 1999, 2002, 2007 Silicon Graphics, Inc. Copyright (C) 1999, 2000, 2001, 2002 Mission Critical Linux, Inc. Copyright (C) 2015, 2021 VMware, Inc. This program is free software, covered by the GNU General Public License, and you are welcome to change it and/or distribute copies of it under certain conditions. Enter "help copying" to see the conditions. This program has absolutely no warranty. Enter "help warranty" for details. GNU gdb (GDB) 10.2 Copyright (C) 2021 Free Software Foundation, Inc. License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html> This is free software: you are free to change and redistribute it. There is NO WARRANTY, to the extent permitted by law. Type "show copying" and "show warranty" for details. This GDB was configured as "--host=x86_64-pc-linux-gnu --target=aarch64-elf-linux". Type "show configuration" for configuration details. Find the GDB manual and other documentation resources online at: <http://www.gnu.org/software/gdb/documentation/>. For help, type "help". Type "apropos word" to search for commands related to "word"... please wait... (determining panic task)Segmentation fault ``` Had I built this module as built-in, I get proper crash message (of course no kdump), ``` [ 63.406244] pc : null_deref_module_init+0x30/0x1000 [npdereference] [ 63.407287] lr : null_deref_module_init+0x24/0x1000 [npdereference] ``` I already [logged this as an issue with maintainers][1], but I can't wait. Even though it should not have crashed, but I think I can make crash-utility happy by giving what it is expecting (yet to find what). Could it be related to the symbols of kernel module? Can someone please provide hints to get through it. [1]: https://github.com/crash-utility/crash/issues/176
crash utility itself crashes while decoding kdump generated from null pointer dereference in kernel module
|c|linux-kernel|crash|gdb|kernel-module|
My Android app uses Fragments and includes Google signin authorization via Firebase. After signing in and starting a Fragment transaction, the following appears, overlaying the Fragment underneath it: [![enter image description here][1]][1] It's as if the gray screen was a Dialog window. When I touch the screen, the gray view disappears: [![enter image description here][2]][2] Has anyone here seen this problem or know what's causing it? [1]: https://i.stack.imgur.com/BW3MF.jpg [2]: https://i.stack.imgur.com/3WYsQ.jpg
{"Voters":[{"Id":298225,"DisplayName":"Eric Postpischil"},{"Id":1377097,"DisplayName":"beaker"},{"Id":9952196,"DisplayName":"Shawn"}]}
I’m trying to figure out an algorithm to distribute a set of 20 to 5000 items into a variable number of boxes (2 to 50). Items are identified by a number of properties, and we need to distribute them into the boxes as evenly as possible by their properties (evenly, not randomly). Each item has (in order of priority): 1. Color: red, blue, green, yellow 2. Shape: round, square, or triangle 3. Size: small, medium, large 4. New or Used The goal is for each box to end up with the same total number of items, the same number of each color, same number of each shape, etc. The property values of the incoming items are effectively random (or at least unpredictable). There can also be a variable number of properties, so maybe weight, material, or other criteria may be added later on. If the number of items is not evenly divisible by the number of boxes, then some boxes will have 1 more item than the others (whole units only). We want the contents of the boxes to end up as close to identical as possible – no box should be different or better than any other box (aside from issues where whole units cannot be divided). If it were just 1 property, that is easy enough – just loop through each color and split them between the boxes – similar to dealing cards. But then add the subsequent criteria, and then… well then short of brute force, I’m stuck. So I’m hoping somebody here has some advice on how to accomplish this in a reasonably efficient way. Scoring the quality of a solution is based on the priority of each property. So in the example, even color distribution is most important, then shape, etc. The score for a particular property could be a simple sum of the max difference of the counts of each value between boxes. So say there are 2 boxes. If each has 5 of each color, the score for the color property is 0. If one box had 3 blue, and the other had 7 blue, the score would be 4. Lowest score wins. For the total score of a solution, maybe an appended string of all the property scores would work. With the 4 properties of the example, a perfect total score would be 00-00-00-00. And 00-99-99-99 beats 01-00-00-00.
Selenium Wire webdriver cannot browse site
|python|selenium-webdriver|http2|mitmproxy|seleniumwire|
null
I've been working on addressing a specific constraint in OPL and attempted to write code to solve it. However, it's not functioning as expected. Could anyone provide guidance on the correct approach to do that. Here is the constraint: [![constraint image][1]][1] ``` range J = 1..5; range R = 1..3; range T = 1..10; int P[J] = [0,1,2,3,4]; int d[J] = [1, 1, 3, 5, 2]; int EF[J] = [1, 2, 1, 1, 1]; int LF[J] = [2, 3, 4, 6, 2]; subject to { forall(j in J, i in P[j]) sum (t in EF[j]..LF[j]) (t - d[j]) * x[j][t] - sum (t in EF[i]..LF[i]) t * x[i][t] >= 0; } ``` I've attempted to apply my knowledge in OPL to address this issue, but I'm encountering difficulties. I would appreciate any advice on how to resolve this. [1]: https://i.stack.imgur.com/ZyWkk.png
Implementing Constraints in OPL Using CPLEX
|javascript|python|php|
The accepted answer is wrong because the crypto/rand [rand.Int][2] function: > returns a uniform random value in [0, max). It panics if max <= 0. Here is an answer that doesn't skip the 2^130 - 1 value. // Max value, a 130-bits integer, i.e 2^130 - 1 var max *big.Int = big.NewInt(0).Exp(big.NewInt(2), big.NewInt(130), nil) // Generate cryptographically strong pseudo-random between [0, max) n, err := rand.Int(rand.Reader, max) if err != nil { // error handling } fmt.Println(n) [2]: https://pkg.go.dev/crypto/rand?utm_source=gopls#Int
When starting the training of yolov9-e or yolov9-c I always get this error: `your text`Traceback (most recent call last): File "/content/yolov9/train.py", line 634, in <module> main(opt) File "/content/yolov9/train.py", line 528, in main train(opt.hyp, opt, device, callbacks) File "/content/yolov9/train.py", line 304, in train loss, loss_items = compute_loss(pred, targets.to(device)) # loss scaled by batch_size File "/content/yolov9/utils/loss_tal.py", line 168, in __call__ pred_distri, pred_scores = torch.cat([xi.view(feats[0].shape[0], self.no, -1) for xi in feats], 2).split( File "/content/yolov9/utils/loss_tal.py", line 168, in <listcomp> pred_distri, pred_scores = torch.cat([xi.view(feats[0].shape[0], self.no, -1) for xi in feats], 2).split( AttributeError: 'list' object has no attribute 'view' I am trying to train it using the code snippet from the roboflow platform. Based on the videos I watched nobody got this error when training these two models using the basic code snipped of roboflow. I tried clearing the GPU memory with: import torch import os torch.cuda.empty_cache() os.environ['PYTORCH_CUDA_ALLOC_CONF'] = 'expandable_segments:True'
Attribute error of train.py file while training YOLOv9-e
|yolo|
null
Why isn't corepack enabled
|node.js|yarnpkg|
The slow (but reliable) method is to read all of the lines in the file and return the last one. Something like: ```csharp static string? GetLastLine(string filename) { using StreamReader reader = new(filename); string? last = null; while (reader.ReadLine() is string line) last = line; return last; } ``` Of course this allocates a lot of strings for no good reason, and the GC will have to get rid of them all shortly afterwards. Not ideal, but that's how it goes. (The `async` version is simple enough to make, but this runs in a few ms per MB. Up to you.) To get it to go faster you can try just reading the last part of the file - enough to get a couple of lines - and process that. You'll need to know the maximum line length for this, just so you can guarantee that you get at least one full line. Assuming that you're working with ASCII or UTF8 data you can probably do something like this: ```csharp static string? GetLastLine(string filename, int maxLineLength) { using Stream stream = File.OpenRead(filename); stream.Position = stream.Length - maxLineLength * 3 / 2; using StreamReader reader = new(stream); string? last = null; while (reader.ReadLine() is string line) last = line; return last; } ``` (This should work in fairly constant time regardless of the size of the file, since it will always process the same amount of data - about 100 microseconds on my machine for a 1MB file using `maxLineLength = 150`. Again, conversion to `async` version is simple.) And finally, if you're expecting lines to be added to the file over time and you want to just read the fresh lines from the file, keep track of the file size and resume reading from there when the file size changes.
How can I initialize my functions to use second database instead of the default one? I use the following code, but noticed a slower response while accessing the database. const admin = require('firebase-admin'); admin.initializeApp({ databaseURL: "https://newdatabaseurl" }); var database = admin.database(); The following code responds slowly: await database.ref("restRooms").once('value').then(async (snap) => { ///some code }); Connecting to second database invokes the query slowly.
|javascript|firebase|firebase-realtime-database|google-cloud-functions|
null
> Could an unitialized pointer be a NULL pointer? An uninitialized pointer could be a null pointer. (Do not use β€œNULL” for a null pointer. `NULL` is a specific macro defined by standard C headers with some different implications.) > From what I have read a NULL pointer points to the memory location "0"… Many C implementations use memory address zero for null pointers, but this is not the only possibility. The C standard merely requires a null pointer to compare unequal to any object or function in the C program. > … and an unitialized pointer points to a random location? No, β€œrandom” is a [different concept](https://en.wikipedia.org/wiki/Randomness). Saying something is random is asserting there is a lack of pattern or predictability to it. While it would not violate the C standard for an uninitialized object to behave randomly, the C standard does not say it does that, and it is unlikely that an uninitialized object would actually behave randomly rather than having at least some pattern of behavior arising out of the programming environment, although not a pattern controlled by the C standard. An uninitialized object is said to have an *indeterminate* value. An indeterminate value is not any particular value but is a description of how the object behaves. Effectively, it means the C standard does not require the object to have a determined valueβ€”in other words, the value is not fixed; it can appear to be different at different typesβ€”and does not require a C implementation to take the value from any particular place, including the memory reserved for the object. This means that, during optimization, a compiler may take the value of the object from memory, from a processor register, or anywhere else, and it may use different sources at different times, and other aspects of the program or the environment may change whatever source or sources the program is using for the value. So the value of the object in the program may appear to change. For example, if `a` is an uninitialized `int`, then `printf("%d\n", a); printf("%d\n", a);` could print two different numbers. > Could it be that this random location sometimes is the "0" so that it is a NULL pointer as well? It can happen that the value used for an indeterminate pointer is a null pointer.
{"OriginalQuestionIds":[47648775],"Voters":[{"Id":874188,"DisplayName":"tripleee","BindingReason":{"GoldTagBadge":"shell"}}]}
Far from perfect. This one: * wraps each word in a ``<span>`` * calculates by ``offsetHeight`` if a SPAN spans multiple lines * of so it found a hyphened word * it then **removes** each _last_ character from the ``<span>`` to find when the word wrapped to a new line <!-- begin snippet: js hide: false console: true babel: false --> <!-- language: lang-html --> <style> .hyphen { background: pink } .remainder { background: lightblue } </style> <process-text lang="en" style="display:inline-block; overflow-wrap: word-break; hyphens: auto; zoom:1.2; width: 7em"> By using words like "incomprehensibilities", we can demonstrate word breaks. </process-text> <script> customElements.define('process-text', class extends HTMLElement { connectedCallback() { setTimeout(() => { let words = this.innerHTML.trim().split(/(\W+)/); let spanned = words.map(w => `<span>${w}</span>`).join(''); this.innerHTML = spanned; let spans = [...this.querySelectorAll("span")]; let defaultHeight = spans[0].offsetHeight; let hyphend = spans.map(span => { let hyphen = span.offsetHeight > defaultHeight; console.assert(span.offsetHeight == defaultHeight, span.innerText, span.offsetWidth); span.classList.toggle("hyphen", hyphen); if (hyphen) { let saved = span.innerText; while (span.innerText && span.offsetHeight > defaultHeight) { span.innerText = span.innerText.slice(0, -1); } let remainder = document.createElement("span"); remainder.innerText = saved.replace(span.innerText, ""); remainder.classList.add("remainder"); span.after(remainder); } }) console.log(this.querySelectorAll("span").length, "<SPAN> created" ); }) //setTimeout to read innerHTML } // connectedCallback }); </script> <!-- end snippet --> The error is "demonstrate" _fits_ when shortened to "demonstr" **-** "ate" Needs some more JS voodoo
Consider something like [Google Input Tools](https://www.google.com/inputtools/) for instance, which can transliterate text in multiple languages using the Latin script. As you type a word, it interactively autocompletes it, showing you multiple possible results. My question is, do the major OSs (i.e. Linux, macOS and Windows) enable developers to implement something like [Google Input Tools](https://www.google.com/inputtools/) system-wide? Such that a user can get the autocomplete service with a popup next to any text input field in any OS application?
OS-wide text autocomplete service with popup
|user-interface|autocomplete|operating-system|popup|transliteration|
I want to create a masonry layout layout with infinity scrolling. [![enter image description here][1]][1] [1]: https://i.stack.imgur.com/kVaHh.png
I'm using `emotion/react: ^11.10.5`, `mui/material: ^5.11.0` and `Next.js v13.1.2`; And I've used MUI `sx` and Emotion/React `css` to style my react components, also most of the pages are SSR. <br/><br/> Problem is that styles are applied with delay, so the page is rendered, or loaded without any style, and after a second styles are applied. <br/><br/> Can anyone help me to solve the problem?
I recently chose to remake the popular game called "soccer physics" but in pygame instead of its original engine, unity. However, I have a quite limited understanding of pygame and implementing game physics, so I've only managed to create [this][1] so far with characters and sprites I found online (I know it's quite bad but it's my first time trying to code an actual 2d game). I aimed to make it a bit more fun and unique with the city background and the platform. I decided to only make one player for now as I'll be using object oriented programming, so I'm thinking I can just create the other 3 players once I've made the code for one of them in a class. Please do correct me if I'm mistaken on that. The main problem right now is the jumping and collisions, which are going to be a big obstacle for me. I managed to make the characters a very simple jump function, with moving and tilting in random directions, however it looks sort of robotic and there's no ragdoll or realistic physics to the jumping, as seen in the original soccer physics. I also have no idea on how I'll make the ball collide with the players and the ground and move accordingly. I've looked up countless tutorials but all of them use simple circles, whereas I'm trying to use an actual image of a football as a sprite along with football players, and I'm finding find this very hard to implement. Here's what I've got so far: ``` if keys[pygame.K_a] and not jumping: # checks to see if up arrow key is pressed and player isn't jumping jumping = True # sets jumping to true - activates the jump algorithm possibilities = [(x - xvelocity), (x + xvelocity)] # list of the two possible directions - right and left angles = [15,20,25,30,35] # list of random possible angles direction = random.choice(possibilities) # picks a random direction for movement angle = random.choice(angles) # picks a random angle from the given list ``` ``` if jumping: # checks if jumping is set to true (in other words if a has been pressed) y -= yvelocity # moves the player's y-position upwards yvelocity -= gravity # induces gravity to the jumping velocity, resulting in a deceleration and the player moving back down if y <= 300: # checks to see if plauer is above a certain height in the jump, and isn't colliding with the goalpost if direction == possibilities[1] and not goalright.rect.colliderect(hitbox): # checks if direction is chosen to be forward or backward x = x + xvelocity # moves player forward/left else: # checks if direction is chosen to be forward or backward x = x - xvelocity # moves player backward/right xvelocity = 1 # returns velocity back to normal if yvelocity < -15: # checks to see if max velocity/height is reached jumping = False # stops the jumping function yvelocity = 15 # returns velocity to original value / moves the player back down if direction == possibilities[1] and x < 665: # if direction is to the right (x + the velocity) display.blit((pygame.transform.rotate(player1kick, -1*angle)),(x,y)) # draws player rotated at a clockwise angle, depending on the direction they're moving elif direction == possibilities[0] and x < 665: # if direction is to the left (x - the velocity) display.blit((pygame.transform.rotate(player1kick, angle)),(x,y)) # if direction is to the left, player rotates anti-clockwise; if to the right, player rotates clockwise. else: display.blit(player1,(x,y)) # draws normal state if too close to the goal else: display.blit(player1,(x,y)) # draws normal state on the ground ``` I know it's a big ask, but if someone could give me advice on how to implement the football and jumping, similar to soccer physics, that would be great. Otherwise, please tell me if I've just made a bad choice trying to do this in pygame. [1]: https://imgur.com/a/51vLFW6
The repository Jammy Release does not have a Release file
I have a requirement to upload over API a video and embed it to a WordPress page, which needs to be one-time viewable and then never accessible again. Also the video needs to have no buttons to stop/pause/rewind/rewatch; once you land on the page, it will start playing and you will not see the video ever again. The access can be granted either by URL sent by email or password protected. Second option would be not embedded, can be viewable on some streaming or video providing service like youtube or vimeo or any other, just need the previously mentioned requirements regarding privacy (one-time viewable is most important). Current solution is on wordpress web page which currently implements WordPress's **PPWP plugin**, to lock content per path with a password. But this solution has a flaw. Videos uploaded to let's say `www.wordpress-domain.com/video-storage/video1.mp4` need to be public to be embedded for instance to path: `www.wordpress-domain.com/page1/private-sub-page/`. So if the user knows the video path (or paths) `/video-storage/video1.mp4` they can just paste the video urls and play all of the videos that should be "private". So my question now is what would be the best solution to upload a video or share a video over API and make the privacy as described in the requirements? Is there any tool/video hosting platform that enables this? I have searched and looked up for instance Vimeo, but all vimeo offers is domain based links that are private, which is fine, but they don't offer one time views, which is a necessary requirement. And most of other video hosting apps offer the same functionalities as Vimeo does.
Password protected or private URL one-time viewable video access
|wordpress|password-protection|one-time-password|vimeo-player|video-embedding|
null
I want to install solr 9.x on a fresh linux server in order to run a pretty old application, migrating from solr 8.x. As of 9.x the data-import handler is no longer part of solr, therefore I installed https://github.com/SearchScale/dataimporthandler to overcome the issue. Solr is running but the core will not load due to a config problem. I am unsure if it is related to dataimport-handler or any other issue. Error log: 31/03/2024, 19:11:32 WARN false findix SolrConfig Couldn't add files from /opt/solr-9.5.0/dist filtered by solr-dataimporthandler-.*\.jar to classpath: java.nio.file.NoSuchFileException: /opt/solr-9.5.0/dist 31/03/2024, 19:11:32 ERROR false findix CoreContainer SolrCore failed to load on startup the file/folder dist does not exist, however /opt/solr-9.5.0/ does. While calling the application error msg: Solr Error: org.apache.solr.core.SolrCoreInitializationException: SolrCore 'findix' is not available due to init failure: Could not load conf for core findix: Error loading solr config from /var/solr/data/findix/conf/solrconfig.xml at org.apache.solr.core.CoreContainer.getCore(CoreContainer.java:2280) at org.apache.solr.core.CoreContainer.getCore(CoreContainer.java:2249) at org.apache.solr.servlet.HttpSolrCall.init(HttpSolrCall.java:257) at org.apache.solr.servlet.HttpSolrCall.call(HttpSolrCall.java:509) at org.apache.solr.servlet.SolrDispatchFilter.dispatch(SolrDispatchFilter.java:262) at org.apache.solr.servlet.SolrDispatchFilter.lambda$doFilter$0(SolrDispatchFilter.java:219) at org.apache.solr.servlet.ServletUtils.traceHttpRequestExecution2(ServletUtils.java:249) at org.apache.solr.servlet.ServletUtils.rateLimitRequest(ServletUtils.java:215) at org.apache.solr.servlet.SolrDispatchFilter.doFilter(SolrDispatchFilter.java:213) at org.apache.solr.servlet.SolrDispatchFilter.doFilter(SolrDispatchFilter.java:195) at org.eclipse.jetty.servlet.FilterHolder.doFilter(FilterHolder.java:210) at org.eclipse.jetty.servlet.ServletHandler$Chain.doFilter(ServletHandler.java:1635) at org.eclipse.jetty.servlet.ServletHandler.doHandle(ServletHandler.java:527) at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:131) at org.eclipse.jetty.security.SecurityHandler.handle(SecurityHandler.java:598) at org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:122) at org.eclipse.jetty.server.handler.ScopedHandler.nextHandle(ScopedHandler.java:223) at org.eclipse.jetty.server.session.SessionHandler.doHandle(SessionHandler.java:1580) at org.eclipse.jetty.server.handler.ScopedHandler.nextHandle(ScopedHandler.java:221) at org.eclipse.jetty.server.handler.ContextHandler.doHandle(ContextHandler.java:1384) at org.eclipse.jetty.server.handler.ScopedHandler.nextScope(ScopedHandler.java:176) at org.eclipse.jetty.servlet.ServletHandler.doScope(ServletHandler.java:484) at org.eclipse.jetty.server.session.SessionHandler.doScope(SessionHandler.java:1553) at org.eclipse.jetty.server.handler.ScopedHandler.nextScope(ScopedHandler.java:174) at org.eclipse.jetty.server.handler.ContextHandler.doScope(ContextHandler.java:1306) at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:129) at org.eclipse.jetty.server.handler.ContextHandlerCollection.handle(ContextHandlerCollection.java:149) at org.eclipse.jetty.server.handler.InetAccessHandler.handle(InetAccessHandler.java:228) at org.eclipse.jetty.server.handler.HandlerCollection.handle(HandlerCollection.java:141) at org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:122) at org.eclipse.jetty.rewrite.handler.RewriteHandler.handle(RewriteHandler.java:301) at org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:122) at org.eclipse.jetty.server.handler.gzip.GzipHandler.handle(GzipHandler.java:822) at org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:122) at org.eclipse.jetty.server.Server.handle(Server.java:563) at org.eclipse.jetty.server.HttpChannel$RequestDispatchable.dispatch(HttpChannel.java:1598) at org.eclipse.jetty.server.HttpChannel.dispatch(HttpChannel.java:753) at org.eclipse.jetty.server.HttpChannel.handle(HttpChannel.java:501) at org.eclipse.jetty.server.HttpConnection.onFillable(HttpConnection.java:287) at org.eclipse.jetty.io.AbstractConnection$ReadCallback.succeeded(AbstractConnection.java:314) at org.eclipse.jetty.io.FillInterest.fillable(FillInterest.java:100) at org.eclipse.jetty.io.SelectableChannelEndPoint$1.run(SelectableChannelEndPoint.java:53) at org.eclipse.jetty.util.thread.strategy.AdaptiveExecutionStrategy.runTask(AdaptiveExecutionStrategy.java:421) at org.eclipse.jetty.util.thread.strategy.AdaptiveExecutionStrategy.consumeTask(AdaptiveExecutionStrategy.java:390) at org.eclipse.jetty.util.thread.strategy.AdaptiveExecutionStrategy.tryProduce(AdaptiveExecutionStrategy.java:277) at org.eclipse.jetty.util.thread.strategy.AdaptiveExecutionStrategy.run(AdaptiveExecutionStrategy.java:199) at org.eclipse.jetty.util.thread.ReservedThreadExecutor$ReservedThread.run(ReservedThreadExecutor.java:411) at org.eclipse.jetty.util.thread.QueuedThreadPool.runJob(QueuedThreadPool.java:969) at org.eclipse.jetty.util.thread.QueuedThreadPool$Runner.doRunJob(QueuedThreadPool.java:1194) at org.eclipse.jetty.util.thread.QueuedThreadPool$Runner.run(QueuedThreadPool.java:1149) at java.base/java.lang.Thread.run(Thread.java:829) Caused by: org.apache.solr.common.SolrException: Could not load conf for core findix: Error loading solr config from /var/solr/data/findix/conf/solrconfig.xml at org.apache.solr.core.ConfigSetService.loadConfigSet(ConfigSetService.java:278) at org.apache.solr.core.CoreContainer.createFromDescriptor(CoreContainer.java:1707) at org.apache.solr.core.CoreContainer.lambda$loadInternal$12(CoreContainer.java:1057) at com.codahale.metrics.InstrumentedExecutorService$InstrumentedRunnable.run(InstrumentedExecutorService.java:212) at java.base/java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:515) at java.base/java.util.concurrent.FutureTask.run(FutureTask.java:264) at org.apache.solr.common.util.ExecutorUtil$MDCAwareThreadPoolExecutor.lambda$execute$0(ExecutorUtil.java:299) at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128) at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628) ... 1 more Caused by: org.apache.solr.common.SolrException: Error loading solr config from /var/solr/data/findix/conf/solrconfig.xml at org.apache.solr.core.SolrConfig.readFromResourceLoader(SolrConfig.java:161) at org.apache.solr.core.ConfigSetService.createSolrConfig(ConfigSetService.java:309) at org.apache.solr.core.ConfigSetService.loadConfigSet(ConfigSetService.java:262) ... 9 more Caused by: java.security.AccessControlException: access denied ("java.io.FilePermission" "/usr/share/java" "read") at java.base/java.security.AccessControlContext.checkPermission(AccessControlContext.java:472) at java.base/java.security.AccessController.checkPermission(AccessController.java:897) at java.base/java.lang.SecurityManager.checkPermission(SecurityManager.java:322) at java.base/java.lang.SecurityManager.checkRead(SecurityManager.java:661) at java.base/sun.nio.fs.UnixPath.checkRead(UnixPath.java:818) at java.base/sun.nio.fs.UnixFileSystemProvider.newDirectoryStream(UnixFileSystemProvider.java:399) at java.base/java.nio.file.Files.newDirectoryStream(Files.java:604) at org.apache.solr.core.SolrResourceLoader.getURLs(SolrResourceLoader.java:289) at org.apache.solr.core.SolrResourceLoader.getFilteredURLs(SolrResourceLoader.java:318) at org.apache.solr.core.SolrConfig.initLibs(SolrConfig.java:969) at org.apache.solr.core.SolrConfig.(SolrConfig.java:243) at org.apache.solr.core.SolrConfig.readFromResourceLoader(SolrConfig.java:153) ... 11 more - also logged in/home/www/logs/solr-errors.log q=*:*&start=0&rows=30&fq=type:classifieds&fq=country:DE&fq={!tag=white_label_id}white_label_id:0&fq=confirmed:1&fl=*,score&facet=true&facet.mincount=1&facet.limit=100&facet.field={!ex=province}province&facet.field={!ex=area}area&facet.field={!ex=quarter}quarter&facet.field={!ex=details}details&facet.field={!ex=rooms}rooms&facet.field={!ex=sqm}sqm&facet.field={!ex=picture}picture&facet.field={!ex=ad_type}ad_type&facet.field={!ex=xx_cat_1}xx_cat_1&facet.field={!ex=xx_cat_2}xx_cat_2&facet.field={!ex=xx_cat_3}xx_cat_3&stats=true&stats.field={!ex=price}price What seems to be the problem here?
Upgrading to Solr 9 failes due to NoSuchFileException
|solr|
{"OriginalQuestionIds":[25751453],"Voters":[{"Id":16343464,"DisplayName":"mozway","BindingReason":{"GoldTagBadge":"pandas"}}]}
Check the data element of field BILD in table ZPROJECT_24035. Case handling is done through the domain of the data element in SE11->Domain->TEXT10->Definition Tab->output properties->Lowercase checkbox. for example: - Domain CHAR10: lowercase checkbox unchecked. Any value in this field is always converted to uppercase. - Domain TEXT10: lowercase checkbox checked. This field allows uppercase and/or lowercase characters. There is no lowercase-only domain, if that is the case, before writing to the database it must be converted to lowercase, by code or through a conversion exit routine function (standard or z).
1. Add a click event to detect which element was clicked (`svgElem.onclick`) 2. Create a panel (`div`) 3. For each attribute ([attributes](https://developer.mozilla.org/en-US/docs/Web/API/Element/attributes) can get all current attributes), add an `input` field in the panel 4. Add an `input.onchange` event handler to update the element's attribute: `input.onchange = () => {element.setAttribute(attr.name, input.value)}` ### simple version <!-- begin snippet: js hide: false console: false babel: false --> <!-- language: lang-html --> <style> .selected {outline: 2px dashed red;} body {display: flex;} </style> <svg width="500" height="500" xmlns="http://www.w3.org/2000/svg"> <rect width="30" height="60" x="80" y="10" style="transform: rotate(30deg)"/> <line x1="143" y1="100" x2="358" y2="55" fill="#000000" stroke="#000000" stroke-width="4" stroke-dasharray="8,8" opacity="1"></line> <circle cx="50" cy="50" r="10" fill="green"/> </svg> <div id="info-panel"></div> <script> const svgElement = document.querySelector('svg') svgElement.addEventListener('click', (event) => { document.querySelector(`[class~='selected']`)?.classList.remove("selected") const targetElement = event.target targetElement.classList.add("selected") displayAttrsPanel(targetElement) }) function displayAttrsPanel(element) { const infoPanel = document.getElementById('info-panel') infoPanel.innerHTML = '' const attributes = element.attributes for (let i = 0; i < attributes.length; i++) { const attr = attributes[i] const frag = createInputFragment(attr.name, attr.value) const input = frag.querySelector('input') input.onchange = () => { element.setAttribute(attr.name, input.value) } infoPanel.append(frag) } } function createInputFragment(name, value) { return document.createRange() .createContextualFragment( `<div><label>${name}<input value="${value}"></div>` ) } </script> <!-- end snippet --> ## Full code The above example is a relatively concise version. The following example provides more settings, such as: - [**type**](https://www.w3schools.com/tags/tag_input.asp): input can perform simple judgments to distinguish whether it is `input.type={color, number, text}`, etc. - **Delete Button**: add the button on each properties for delete. - **New Attribute Button**: The ability to add new attributes through the panel - [**dialog**](https://www.w3schools.com/tags/tag_dialog.asp): For more complex attributes like {class, style, [d](https://www.w3schools.com/graphics/svg_path.asp), [points](https://www.w3schools.com/graphics/svg_polyline.asp)}, pupup an individual dialog can be used to set each value separately <!-- begin snippet: js hide: false console: false babel: false --> <!-- language: lang-html --> <style> .selected {outline: 2px dashed red;} body {display: flex;} </style> <svg width="500" height="500" xmlns="http://www.w3.org/2000/svg"> <rect width="30" height="60" x="80" y="10" style="transform: rotate(30deg);opacity: 0.8;"/> <line x1="143" y1="100" x2="358" y2="55" fill="#000000" stroke="#000000" stroke-width="4" stroke-dasharray="8,8" opacity="1"></line> <circle class="cute big" cx="50" cy="50" r="10" fill="green"/> <polygon points="225,124 114,195 168,288 293,251.123456"></polygon> <polyline points="50,150 100,75 150,50 200,140 250,140" fill="yellow"></polyline> <path d="M150 300 L75 200 L225 200 Z" fill="purple"></path> </svg> <div id="info-panel"></div> <script> const svgElement = document.querySelector('svg') svgElement.addEventListener('click', (event) => { document.querySelector(`[class~='selected']`)?.classList.remove("selected") const targetElement = event.target targetElement.classList.add("selected") displayAttrsPanel(targetElement) }) function displayAttrsPanel(element) { const infoPanel = document.getElementById('info-panel') infoPanel.innerHTML = '' // Sorting is an optional feature designed to ensure the presentation order remains as fixed as possible. const attributes = [...element.attributes].sort((a, b)=>{ return a.name < b.name ? -1 : a.name > b.name ? 1 : 0 }) for (let i = 0; i < attributes.length; i++) { const attr = attributes[i] const frag = createInputFragment(attr.name, attr.value) // add event const input = frag.querySelector('input') const deleteBtn = frag.querySelector('button') input.onchange = () => { element.setAttribute(attr.name, input.value) } // allow delete attribute deleteBtn.onclick = () => { element.removeAttribute(attr.name) displayAttrsPanel(element) // refresh } // For special case, when clicking the label, sub-items can be displayed separately, making it convenient for editing. const label = frag.querySelector("label") if (["class", "style", "points", "d"].includes(attr.name)) { label.style.backgroundColor = "#d8f9d8" // for the user know it can click label.style.cursor = "pointer" let splitFunc const cbOptions = [] switch (attr.name) { case "points": // https://www.w3schools.com/graphics/svg_polygon.asp case "class": splitFunc=value=>value.split(" ") cbOptions.push((newValues)=>element.setAttribute(attr.name, newValues.join(" "))) break case "style": splitFunc=value=>value.split(";") cbOptions.push((newValues)=>element.setAttribute(attr.name, newValues.join(";"))) break case "d": // https://www.w3schools.com/graphics/svg_path.asp const regex = /([MLHVCSQTAZ])([^MLHVCSQTAZ]*)/g; splitFunc=value=>value.match(regex) cbOptions.push((newValues)=>element.setAttribute(attr.name, newValues.join(""))) } label.addEventListener("click", () => { openEditDialog(attr.name, attr.value, splitFunc, (newValues) => { for (const option of cbOptions) { option(newValues) } displayAttrsPanel(element) // refresh }) }) } infoPanel.append(frag) } // Add New Attribute Button const frag = document.createRange() .createContextualFragment( `<div><label>+<input placeholder="attribute"><input placeholder="value"></label><button>Add</button></div>` ) const [inputAttr, inputVal] = frag.querySelectorAll("input") frag.querySelector("button").onclick = () => { const name = inputAttr.value.trim() const value = inputVal.value.trim() if (name && value) { element.setAttribute(name, value) inputAttr.value = '' inputVal.value = '' displayAttrsPanel(element) // refresh } } infoPanel.appendChild(frag) } function createInputFragment(name, value) { const frag = document.createRange() .createContextualFragment( `<div><label>${name}</label><input value="${value}"><button>-</button></div>` ) const input = frag.querySelector("input") switch (name) { case "stroke": case "fill": input.type = "color" break case "opacity": input.type = "range" input.step = "0.05" input.max = "1" input.min = "0" break case "cx": case "cy": case "r": case "rx": case "ry": case "x": case "y": case "x1": case "x2": case "y1": case "y2": case "stroke-width": input.type = "number" break default: input.type = "text" } return frag } function openEditDialog(name, valueStr, splitFunc, callback) { const frag = document.createRange() .createContextualFragment( `<dialog open> <div style="display: flex;flex-direction: column;"></div> <button id="add">Add</button> <button id="save">Save</button></dialog>` ) const dialog = frag.querySelector("dialog") const divValueContainer = frag.querySelector('div') const addBtn = frag.querySelector("button#add") const saveBtn = frag.querySelector("button#save") const values = splitFunc(valueStr) for (const val of values) { const input = document.createElement("input") input.value = val divValueContainer.append(input) } // Add addBtn.onclick = () => { const input = document.createElement("input") divValueContainer.append(input) } // Save saveBtn.onclick = () => { const newValues = [] dialog.querySelectorAll("input").forEach(e=>{ if (e.value !== "") { newValues.push(e.value) } }) callback(newValues) dialog.close() } document.body.append(dialog) } </script> <!-- end snippet -->
i have string ```"This auction will run from Friday 28 July - Monday 7 August. It will close from 7pm (GMT) on Monday 7 August 2023. Read here for information on how our auctions end."``` and im trying to get dates from this string ``` const regex = /(\d{1,2} \w+(?: \d{4})?)/g; const dates = str.match(regex) ``` this is regex that i wrote and in regex checker site((\d{1,2} \w+(?: \d{4})?)) it matches for 28 july, 7 august and 7 august 2023, but in javascript it only matches for 7 august and 7 august 2023, whats wrong?
I try to extract the state of a switch from a mqtt message I get when the switch toggles. The mqtt message I get is: >{"src":"shellyplus1-08b61fd9e540","dst":"shellyplus1-08b61fd9e540/events","method":"NotifyStatus","params":{"ts":1711558165.32,"input:0":{"id":0,"state":true}} I need to know the value of the key "state" I tried following code ``` let mqtt = require('mqtt'); //Connect to the MQTT Server let client = mqtt.connect('mqtt://localhost'); client.on("connect",function(){ client.subscribe("shellyplus1-08b61fd9e540/events/rpc"); console.log("connected to mqtt Server"); }); //parse Sensor message client.on ('message',function(topic,message,packet){ var msgObject = JSON.parse(message.toString()) var stringified = JSON.stringify(msgObject,'',2); // console.log("topic is "+ topic); console.log(stringified.params); //works console.log(stringified.params.ts); //works //console.log(stringified.params."input:0"); //SyntaxError: Unexpected string }); ``` I tried different ways to parse the message. I can read from the stringified object but only till the key "params" and also I can read "ts" but I have to jump to "input:0" and further to "state". There I get always an error because of the : in the key name. Or is there a different way to get the value of key "state"? Thank you in advance Joerg Brits answer works but this is only the half way to my target. I need to extract the value of the 'state' and neither a dot notation nor the bracket notation works. ... console.log(msgObject.params["input:0"].state); console.log(msgObject.params["input:0"]["state"]); ... I get always >TypeError: Cannot read properties of undefined (reading 'state')
I'm creating a slider using Swiper JS which reveals the next slider partially as following ![1][] However it's work great until end of original slides and when the loop mode enabled duplicate slides start next slide is disapear and appear on next one Following is what I tried so far in JS Fiddle: ``` <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <title>Swiper demo</title> <meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1, maximum-scale=1" /> <!-- Link Swiper's CSS --> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/swiper@8/swiper-bundle.min.css" /> </head> <body> <!-- Swiper --> <div class="swiper mySwiper"> <div class="swiper-wrapper"> <div class="swiper-slide"> <div> <img src="https://picsum.photos/200" alt=""> </div> <div> <p> Lorem ipsum dolor sit amet, consectetur adipisicing elit. Dolorum id, velit, voluptatem quis quisquam quas rem, ea, quia iusto tempore animi alias. Natus, voluptas accusantium. </p> </div> </div> <div class="swiper-slide"> <div> <img src="https://picsum.photos/200" alt=""> </div> <div> <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Odit tempora perspiciatis ratione excepturi labore, expedita eos quis sequi consequuntur, doloremque odio soluta fugit, ut sed?</p> </div> </div> <div class="swiper-slide"> <div> <img src="https://picsum.photos/200" alt=""> </div> <div> <p> Lorem ipsum dolor sit amet, consectetur adipisicing elit. Dolorum id, velit, voluptatem quis quisquam quas rem, ea, quia iusto tempore animi alias. Natus, voluptas accusantium. </p> </div> </div> <div class="swiper-slide"> <div> <img src="https://picsum.photos/200" alt=""> </div> <div> <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Odit tempora perspiciatis ratione excepturi labore, expedita eos quis sequi consequuntur, doloremque odio soluta fugit, ut sed?</p> </div> </div> </div> <div class="swiper-button-next"></div> <div class="swiper-button-prev"></div> </div> <!-- Swiper JS --> <script src="https://cdn.jsdelivr.net/npm/swiper@8/swiper-bundle.min.js"></script> </body> </html> ``` ``` .swiper-slide{ display:flex !important; } .swiper-slide div{ width:calc(50% - 25px); display: flex; justify-content: center; align-items: center; } .swiper-slide div:nth-child(2){ padding-left: 25px; } .swiper-slide div:nth-child(2) p { max-width:200px; } img{ width:100%; } .mySwiper{ padding-right: 100px !important; } ``` ``` var swiper = new Swiper(".mySwiper", { loop:true, navigation: { nextEl: ".swiper-button-next", prevEl: ".swiper-button-prev", }, }); ``` [1]:https://i.stack.imgur.com/L0e9N.png
{"Voters":[{"Id":3527297,"DisplayName":"Gustav"},{"Id":7607190,"DisplayName":"June7"},{"Id":2422778,"DisplayName":"Mike Szyndel"}],"SiteSpecificCloseReasonIds":[16]}
I was just trying to run HTML Code on vs code through google chrome. Its working correctly on other browsers. [![enter image description here][1]][1] What can be the problem, the other html files are running correctly which I have made before. [1]: https://i.stack.imgur.com/3kWBO.png
The Python 3.12 embedding documentation for embedding gives this example: ``` #define PY_SSIZE_T_CLEAN #include <Python.h> int main(int argc, char *argv[]) { wchar_t *program = Py_DecodeLocale(argv[0], NULL); if (program == NULL) { fprintf(stderr, "Fatal error: cannot decode argv[0]\n"); exit(1); } Py_SetProgramName(program); /* optional but recommended */ Py_Initialize(); PyRun_SimpleString("from time import time,ctime\n" "print('Today is', ctime(time()))\n"); if (Py_FinalizeEx() < 0) { exit(120); } PyMem_RawFree(program); return 0; } ``` Although calling `Py_SetProgramName()` is recommended, it throws a compile warning: ``` test01.c:12:5: warning: 'Py_SetProgramName' is deprecated [-Wdeprecated-declarations] Py_SetProgramName(program); /* optional but recommended */ ^ /opt/python/3.11/include/python3.11/pylifecycle.h:37:1: note: 'Py_SetProgramName' has been explicitly marked deprecated here Py_DEPRECATED(3.11) PyAPI_FUNC(void) Py_SetProgramName(const wchar_t *); ^ /opt/python/3.11/include/python3.11/pyport.h:336:54: note: expanded from macro 'Py_DEPRECATED' #define Py_DEPRECATED(VERSION_UNUSED) __attribute__((__deprecated__)) ^ 1 warning generated. ``` The resulting excecutable runs and if you add `import sys` and `print(sys.executable)` to the `PyRun_SimpleString()` argument, the correct executable name is shown. Although this was deprecated in 3.11, and is still recommended for 3.12, but I rather get rid of the warning. How should I change the program?
How to set the Python executable name, now that Py_SetProgramName() is deprecated?
|python|c|python-c-api|
Following the alternatives mentioned in the documentation for `Py_SetProgramName` and succesfully merging code from [Initialization with PyConfig](https://docs.python.org/3/c-api/init_config.html#initialization-with-pyconfig) I got this working program: ``` #define PY_SSIZE_T_CLEAN #include <Python.h> int main(int argc, char *argv[]) { wchar_t *program = Py_DecodeLocale(argv[0], NULL); if (program == NULL) { fprintf(stderr, "Fatal error: cannot decode argv[0]\n"); exit(1); } PyStatus status; PyConfig config; PyConfig_InitPythonConfig(&config); status = PyConfig_SetString(&config, &config.program_name, program); if (PyStatus_Exception(status)) { goto exception; } status = Py_InitializeFromConfig(&config); if (PyStatus_Exception(status)) { goto exception; } PyRun_SimpleString( "import sys\n" "from time import time,ctime\n" "print('Today is', ctime(time()))\n" "print('executable:', sys.executable)\n" ); if (Py_FinalizeEx() < 0) { exit(120); } PyMem_RawFree(program); PyConfig_Clear(&config); return 0; exception: PyConfig_Clear(&config); Py_ExitStatusException(status); } ``` Afterwards I found that the dev (3.13) preview Documentation contained an updated example, which did away with the `program` variable, and showed that the `config` can be cleared before running the program: ``` #define PY_SSIZE_T_CLEAN #include <Python.h> int main(int argc, char *argv[]) { PyStatus status; PyConfig config; PyConfig_InitPythonConfig(&config); status = PyConfig_SetBytesString(&config, &config.program_name, argv[0]); if (PyStatus_Exception(status)) { goto exception; } status = Py_InitializeFromConfig(&config); if (PyStatus_Exception(status)) { goto exception; } PyConfig_Clear(&config); PyRun_SimpleString( "import sys\n" "from time import time,ctime\n" "print('Today is', ctime(time()))\n" "print('executable:', sys.executable)\n" ); if (Py_FinalizeEx() < 0) { exit(120); } return 0; exception: PyConfig_Clear(&config); Py_ExitStatusException(status); } ```
**WHEN USING SSR IMPLEMENTATION WITH NEXTJS 13** When following the implementation enforced on TanStack's docs, you would be encouraged to create a request based client for Server Side and a singleton client for Client Side. But when using `queryClient.invalidateQueries`, be sure to use queryClient from `useQueryClient` instead of importing your global client. Here is an example of how to do it when invalidating in a mutation. ``` export const useAddProductToCartMutation = () => { const queryClient = useQueryClient(); return useMutation({ mutationFn: async (data: { productId: number }) => { return await addProductToCart(data.productId); }, onSettled: async () => { queryClient.invalidateQueries({ queryKey: ["cart"], refetchType: "all", }); }, }); };
I have upgraded an ASP.NET MVC project, written in C# and running on .NET 4.7.2, to .NET 8.0. I get this error: > The type or namespace name 'DirectoryServices' does not exist in the namespace 'System' (are you missing an assembly reference?) I have tried to install `System.ServiceModel.Primitive` and it didn't work. The old code uses using System.Security.Principal; using System.ServiceModel;
Upgraded C# / ASP.NET MVC project from .NET 4.7.2 to .NET 8.0
Something with the terminal is caching those .env values, I don't know if that's technically what's going on. But killing the terminal instance and running the process again from a new terminal should bring in the latest values.
I want to `require` a Ruby file in another file. These two files are in two different directories. I have `require second_file` at the top of the first file. Ruby says it can't load such file. Is that because it's in a different directory? I tried writing the full path to the second file but it still can't load the file. How can I load the second file into the first?
How to require a Ruby file from another directory
|ruby|require|
Two steps: 1. use 'complete' from '[tidyr][1]' to create the fake data (e.g., 'max(Data$Height) * 1000') for the missing combination(s) of 'Month' and 'Site': `library(dplyr); library(tidyr); new_data <- Data %>% complete(Month, Site, fill = list(Height = max(Data$Height) * 1000));` 2. plot *without* the fake data created using `ylim` in `coord_cartesian`: `ggplot(new_data, aes(Site, Height)) + geom_boxplot(aes(fill = Month)) + coord_cartesian(ylim = range(Data$Height))` [1]: https://tidyr.tidyverse.org/reference/complete.html
While you can't have a `box-shadow: linear-gradient(#9198E5, #E66465)`, you could take advantage of [Pseudo-elements](https://developer.mozilla.org/en-US/docs/Web/CSS/Pseudo-elements) to have the same gradient mixing it with `filter: blur(10px);` to have the same effect of shadow, note that `#back` must have `z-index: -2` to sit behind the pseudo-element. Also, note that because of the different sizes between `html` height and `#front` height the gradient spread color will be different, so to make sure that it will have an effect like _ dissolve_ I used chrome dev tool to pick the hex colors, the first color picked from the bottom of the green rectangle and the second color will be picked from the top of the green rectangle. <!-- begin snippet: js hide: false console: true babel: false --> <!-- language: lang-css --> html { height: 500px; background: linear-gradient(#9198E5, #E66465); } #back { position: absolute; top: 100px; left: 100px; width: 200px; height: 200px; background-color: #FFBBBB; z-index: -2; } #front { position: absolute; display: block; top: 200px; left: 200px; width: 200px; height: 200px; background-color: #BBFFBB; } #front:before { content: ""; position: absolute; inset: 0; background: linear-gradient(#ac87bc, #d17085); filter: blur(10px); transform: translate(-40px, -40px); z-index: -1; } <!-- language: lang-html --> <div id="back"></div> <div id="front"></div> <!-- end snippet -->
Next js delay before applying Emotion and MUI styles
The transposition table uses keys from the position of player 0 and player 1 from bitboards and includes the player turn at the end, I did that to guarantee unique keys for all states. But this seems to be slow because of fmt.Sprintf. I have two functions where I store and retrieve, and in each of them I build the key and do a check or store. type TTFlag int64 const ( Exact TTFlag = 0 UpperBound TTFlag = 1 LowerBound TTFlag = 2 ) type TTEntry struct { BestScore float64 BestMove int Flag TTFlag Depth int IsValid bool } type Solver struct { NodeVisitCounter int TTMapHitCounter int TTMap map[string]TTEntry } func NewSolver() *Solver { return &Solver{ NodeVisitCounter: 0, TTMapHitCounter: 0, TTMap: make(map[string]TTEntry), } } func (s *Solver) StoreEntry(p *Position, entry TTEntry) { key := fmt.Sprintf("%d:%d:%d", p.Bitboard[0], p.Bitboard[1], p.PlayerTurn) s.TTMap[key] = entry } func (s *Solver) RetrieveEntry(p *Position) TTEntry { key := fmt.Sprintf("%d:%d:%d", p.Bitboard[0], p.Bitboard[1], p.PlayerTurn) if entry, exists := s.TTMap[key]; exists { s.TTMapHitCounter++ return entry } return TTEntry{} } What can I do to optimize this further? How can I make better keys without the use of fmt.Sprintf and string concatenation? Edit: The Position struct is keeps track of game state: type Position struct { Bitboard [2]uint64 PlayerTurn int HeightBB [7]int NumberOfMoves int } HeightBB is an array that keeps track of the height of the columns, so we know where to put the piece in the bitmap.
|javascript|css|next.js|material-ui|emotion|
Does anyone know why `getById` and `getReferenceById` work differently? I'm using `JpaRepository` and the method `getReferenceById` doesn't throw `EntityNotFoundException` but getById throws this exception when the object doesn't exist
I have some questions about some concepts, and they are not well solved through search engines and gpt, so I hope you can explain them to me. I don't understand "nn layout" and "nt layout" of neural network memory layout. There are two explanations, but I don't know which one is correct. One explanation is that "NN" stands for "numerator numerator",in NN layout, the layout of input and weight tensors are both "numerator". "Numerator" means that the channels in the tensor are placed in the first dimension. ; NT stands for "numerator denominator", In NT layout, the layout of the input tensor is "numerator", while the layout of the weight tensor is "denominator". This means that the channels of the input tensor are still in the first dimension, while the channels of the weight tensor are in the second dimensions" Another explanation is "nn stands for column-major layout and nt stands for row-major layout." Hope someone can give me an accurate explanation, thank you!
what's the difference between "nn layout" and "nt layout"
|computer-vision|computer-science|cpu-architecture|
You can add this code to your theme's `functions.php` file: ``` <?php // functions.php function display_category_post_counts_atakanau() { $categories = get_categories(); $category_list = array(); foreach ($categories as $category) { if ($category->category_parent == 0) { $category_list[$category->name] = array( 'total_post_count' => $category->count, 'sub_categories' => array() ); } else { $parent = get_category($category->category_parent); while ($parent->category_parent != 0) { $parent = get_category($parent->category_parent); } if (!isset($category_list[$parent->name])) { $category_list[$parent->name] = array( 'total_post_count' => $parent->count, 'sub_categories' => array() ); } $category_list[$parent->name]['sub_categories'][$category->name] = $category->count; $category_list[$parent->name]['total_post_count'] += $category->count; } } $show_level_2 = false; $output = '<ul>'; foreach ($category_list as $category_name => $info) { $output .= '<li>' . $category_name . ' - Total Post Count: ' . $info['total_post_count']; if ($show_level_2 && !empty($info['sub_categories'])) { $output .= '<ul>'; foreach ($info['sub_categories'] as $sub_category_name => $post_count) { $output .= '<li>' . $sub_category_name . ' - Post Count: ' . $post_count . '</li>'; } $output .= '</ul>'; } $output .= '</li>'; } $output .= '</ul>'; return $output; } add_shortcode('shortcode_category_post_counts', 'display_category_post_counts_atakanau'); ``` Then, you can add this shortcode to your posts, pages, and widgets using the following code: `[shortcode_category_post_counts]` It will run the function and show the output. Like: [![sample html output][1]][1] [1]: https://i.stack.imgur.com/z9xru.png
This looks like a bug. I've [opened issue #27](https://github.com/statnet/ergm.multi/issues/27) for it.
I try to run a multi-layered ERGM with the **ergm.multi** package in R with two layers. Before, I ran an ERGM for each layer, which all worked our perfectly. However, when trying to run the respective multi-layer ERGM, I get the error message concerning nodal attributes: > Error in \`ergm_Init_abort()\`:! In term β€˜nodeifactor’ in package β€˜ergm’ (called from term β€˜L’ in package β€˜ergm.multi’): β€˜srh’ is/are not valid nodal attribute(s). Following the statnet tutorial (https://statnet.org/workshop-advanced-ergm/), I specified my multi-layered network as follows: ```r hf2_A <- network1 | network2 # superset of all edges in any layer # set attributes hf2_A[,, names.eval="network1"] <- as.matrix(network1) hf2_A[,, names.eval="network2"] <- as.matrix(network2) hf2_A hf_A <- Layer(hf2_A, c("network1","network2")) hf_A #A set.vertex.attribute(hf_A, attrname = "pid", value = as.vector(network_names_A)) set.vertex.attribute(hf_A, attrname = "sup", value = as.vector(sup_A)) set.vertex.attribute(hf_A, attrname = "nas", value = as.vector(nas_A)) set.vertex.attribute(hf_A, attrname = "age", value = as.vector(age_A)) set.vertex.attribute(hf_A, attrname = "srh", value = as.vector(srh_A)) set.vertex.attribute(hf_A, attrname = "casmin", value = as.vector(casmin_A)) ``` `hf_A` looks then like this: ``` Combined 2 networks on β€˜.LayerID’/β€˜.LayerName’: 1: n = 50, directed = TRUE, bipartite = FALSE, loops = FALSE 2: n = 50, directed = TRUE, bipartite = FALSE, loops = FALSE Network attributes: vertices = 100 directed = TRUE hyper = FALSE loops = FALSE multiple = FALSE bipartite = FALSE ergm: Length Class Mode constraints 2 formula call total edges= 247 missing edges= 0 non-missing edges= 247 Vertex attribute names: .bipartite .LayerID .LayerName .undirected age casmin nas pid srh sup vertex.names Edge attribute names: network1 network2 ``` However, when running my multi-layered ERGM, I will still get the error message specified above. ```r m1 <- ergm(hf_A ~ L(~edges + mutual + gwidegree(decay=.1, fixed=TRUE) + gwodegree(decay=.1, fixed=TRUE) + gwesp(decay=.1, fixed=TRUE) +edgecov(A_friend_w1)+edgecov(A_kin_w1) +nodeifactor("srh")+nodeofactor("srh")+nodeifactor("nas")+nodeofactor("nas")+nodematch("srh")+nodematch("nas") +nodematch("age")+nodematch("casmin")+nodefactor("age")+nodefactor("casmin"), ~network1) + L(~edges + mutual + gwidegree(decay=.1, fixed=TRUE) + gwodegree(decay=.1, fixed=TRUE) + gwesp(decay=.1, fixed=TRUE) +edgecov(A_health_w1)+edgecov(A_kin_w1) +nodeifactor("srh")+nodeofactor("srh")+nodeifactor("nas")+nodeofactor("nas")+nodematch("srh")+nodematch("nas") +nodematch("age")+nodematch("casmin")+nodefactor("age")+nodefactor("casmin"), ~network2) ) ``` Did anyone else encounter a similar problem? Or knows why I get the error message?
In c++, It's possible to use some tricks with the help of constexpr, to write a MACRO that encrypts strings in compile-time, and decrypts them in runtime, and we could use something like ENCRYPT("MyString") to achieve this. An example is the following header file: https://github.com/skadro-official/skCrypter/blob/master/files/skCrypter.h Is this also possible in Rust? I want to encrypt my strings in compile time, and decrypt them in runtime.
How to encrypt a string at compile-time and decrypt it at runtime in Rust, similar to constexpr encryption in c++?
|rust|
I'm encountering difficulties implementing a MEJS audio player on my WordPress website. Although the player container is displaying correctly, the player itself is not appearing. So here are the functions (first one is designed to generate a list of clickable tracks based on the provided product ID, it's the A1, A2, B1 etc elements before add to cart button): ``` function display_playlist_tracks($product_id) { $short_description = get_post_field('post_excerpt', $product_id); preg_match('/ids="([^"]+)"/', $short_description, $matches); if (!empty($matches[1])) { $track_ids = explode(',', $matches[1]); $playlist_tracks = '<div style="text-align: left;">'; foreach ($track_ids as $track_id) { $track_name = get_the_title($track_id); // Find the position of the first dot or space $position = strpos($track_name, '.') !== false ? strpos($track_name, '.') : strpos($track_name, ' '); // Extract the characters up to this position $track_name_short = substr($track_name, 0, $position); // Build the HTML for each track $playlist_tracks .= '<span class="mp3-clickable" data-track-url="' . esc_url(wp_get_attachment_url($track_id)) . '">' . $track_name_short . '</span> '; } $playlist_tracks .= '</div>'; echo $playlist_tracks; } } function add_custom_audio_player() { // Output the audio player container with its styling echo '<div id="audio-player-container" style="position: fixed; bottom: 0; left: 0; right: 0; background-color: #8cff27; padding: 10px; display: none;">'; // Output the audio element with the appropriate class echo '<audio class="mejs__player"></audio>'; echo '</div>'; } // Hook the function to the wp_footer action add_action('wp_footer', 'add_custom_audio_player'); ``` And the script relative to it: document.addEventListener('DOMContentLoaded', function () { var audioPlayer = document.querySelector('.mejs__player'); var audioPlayerContainer = document.getElementById('audio-player-container'); if (audioPlayer && audioPlayerContainer) { function displayAudioPlayer(trackUrl) { audioPlayer.src = trackUrl; audioPlayer.play(); audioPlayerContainer.style.display = 'block'; } document.querySelectorAll('.mp3-clickable').forEach(function (element) { element.addEventListener('click', function () { displayAudioPlayer(this.getAttribute('data-track-url')); }); }); } else { console.error('Les Γ©lΓ©ments audioPlayer ou audioPlayerContainer ne sont pas trouvΓ©s dans le DOM.'); } Here's the website: https://haunted-dancehall.com/ Any suggestions?? I've tried these codes and the player container is displaying correctly but the player itself is not appearing
I have a Leaflet control that I add to the map using the code below. ``` ... var FilterControl = L.Control.extend({ options: { position: 'topleft' }, onAdd: function(map) { this._div = L.DomUtil.create('div', 'leaflet-formcontrol'); L.DomEvent.disableClickPropagation(this._div); return this._div; }, }); ... var filterControl = new FilterControl(); filterControl.addTo(map); ``` On the map itself, I bound an event listener: ``` map.on('click', remove_highlights) ``` Now, my problem is that when a 'click' event is started (mousedown) in the control layer, but ends on the map (on mouseup) after dragging the mouse, the click event of the map is triggered, which I do not want. The situation occurs quite easily because there is a slider on the controllayer. [Mozilla](https://stackoverflow.com) describes the behaviour, but it does not become clear to me how to solve it. For instance, stopPropagation() or stopImmediatePropagation() does not work, not on the map or on the layercontrol, when adding a click event listener to it. Also, setting `L.DomEvent.disableClickPropagation(..)` but then on the map element, does not work. Does anyone have any experience with this problem? Best, Robert
Stop propagation of javasript/leaflet click event that starts in one element and ends in another
|javascript|events|leaflet|event-bubbling|
null
I have a page in Laravel that includes a start date, a deadline, and an end date. I aim to calculate and display the final date when I input the number of days (deadline). I've utilized Laravel Collective for the controls. Start date: ```php {!! Form::text('StartDate', jdate($task->StartDate)->format('Y-m-d'), ['class'=>'myform-control']) !!} ``` Deadline: ```php {!! Form::text('Deadline', null, ['class'=>'myform-control','style'=>'width:50px;']) !!} <script> $('#Deadline').change(function() { const dval = parseInt($('#Deadline').val()); const StartDate = document.getElementById("StartDate").value; const startdateToEnglish = StartDate.toEnglishDigit(); const startdateToEngArray = startdateToEnglish.split('-').map(Number); var inputF = document.getElementById("EndDate"); var edate = new persianDate(startdateToEngArray).add('days', dval).format('YYYY-MM-DD'); console.log(startdateToEngArray, dval, edate); inputF.value = edate; }); </script> ``` End date: ```php {!! Form::text('EndDate', jdate($task->EndDate)->format('Y-m-d'), ['class'=>'myform-control observer-example','style'=>'width:180px;','old'=>'EndDate']) !!} ``` I've implemented this template for both the store and edit blades. The event handler works in the store blade, but the edit blade adds a month to the date and the day. If I input the value 6 in the deadline, the final date will be one month and six days later. I'm puzzled because the conditions are identical, and I've copied the codes related to the editing blade from the store blade. The values displayed in the console are the same except for the end date.
JavaScript change event issue in calculating new date with deadline
My instance of func app currently under consumption plan. There is one timer trigger logic that needs to make bunch on http requests - 10k and fails due to consumption plan "connections" limitation. Is it possible to automatically switch to premium plan for 1 hour daily and then switch it back to consumption? Or maybe azure function was not the best choice here - basically I need to execute some logic daily (it takes about 1 hour on 1 core PC), so it does not make sense to pay more but just for this 1 hour of work. Any suggestions? Thank you!
I have a code for Arduino Nano RP2040 written with the usage of Raspberry Pi SDK (it was written to use with Raspberry Pi Pico, but then I switched to Arduino Nano Connect RP2040). Now I want to add WiFi functionality to it, so I want to control the WiFi NINA which is on the board. I'm trying to port Arduino's WIFININA library to Raspberry Pi: change the pins numbers, replace the SPI functions with the ones from Raspberry SDK etc. Unfortunately already when sending first SPI command to WiFi module it fails. Here is the code: ``` #include <stdio.h> #include <stdlib.h> #include "pico/stdlib.h" #include "hardware/spi.h" #define SET_PASSPHRASE_CMD 0x11 #define START_CMD 0xE0 #define END_CMD 0xEE #define REPLY_FLAG 1<<7 #define NINA_GPIO0 (2u) #define SPI1_CIPO (8u) #define SPI1_COPI (11u) #define SPI1_SCK (14u) #define SPIWIFI_SS (9u) #define SPIWIFI spi1 static uint8_t SLAVEREADY = 10; // handshake pin static uint8_t SLAVERESET = 3; // reset pin int transfer(uint8_t buf_to_write, uint8_t buf_to_read = 11) { printf("transfer - buf_to_write = %u, buf_to_read = %u \n", buf_to_write, buf_to_read); int response{0}; response = spi_write_read_blocking(SPIWIFI, &buf_to_write, &buf_to_read, 1); printf("transfer - response = %u, buf_to_read = %u \n", response, buf_to_read); return response; } void sendCmd(uint8_t cmd, uint8_t numParam) { printf("sendCmd - cmd = %u, numParam = %u \n", cmd, numParam); uint8_t buf_to_write{START_CMD}; transfer(buf_to_write); buf_to_write = cmd & ~(REPLY_FLAG); transfer(buf_to_write); buf_to_write = numParam; transfer(buf_to_write); if(numParam == 0) { printf("sendCmd - END_CMD \n"); buf_to_write = END_CMD; transfer(buf_to_write); } } int main() { stdio_init_all(); sleep_ms(2000); gpio_init(SPIWIFI_SS); gpio_set_dir(SPIWIFI_SS, GPIO_OUT); gpio_init(SLAVEREADY); gpio_set_dir(SLAVEREADY, GPIO_IN); gpio_init(SLAVERESET); gpio_set_dir(SLAVERESET, GPIO_OUT); gpio_init(NINA_GPIO0); gpio_set_dir(NINA_GPIO0, GPIO_OUT); gpio_put(NINA_GPIO0, 1); gpio_put(SPIWIFI_SS, 1); gpio_put(SLAVERESET, 0); sleep_ms(10); gpio_put(SLAVERESET, 1); sleep_ms(750); gpio_put(NINA_GPIO0, 0); gpio_set_dir(NINA_GPIO0, GPIO_IN); // initialize SPI spi_init(SPIWIFI, 8000000); spi_set_format(SPIWIFI, 8, SPI_CPOL_0, SPI_CPHA_0, SPI_MSB_FIRST); gpio_set_function(SPI1_COPI, GPIO_FUNC_SPI); gpio_set_function(SPI1_SCK, GPIO_FUNC_SPI); sleep_ms(10); gpio_put(SPIWIFI_SS, 0); sendCmd(SET_PASSPHRASE_CMD, 2); gpio_put(SPIWIFI_SS, 1); while(true) { sleep_ms(10); } } ``` Here is the result of the print: ``` sendCmd - cmd = 17, numParam = 2 transfer - buf_to_write = 224, buf_to_read = 11 transfer - response = 1, buf_to_read = 0 transfer - buf_to_write = 17, buf_to_read = 11 transfer - response = 1, buf_to_read = 0 transfer - buf_to_write = 2, buf_to_read = 11 transfer - response = 1, buf_to_read = 0 ``` `buf_to_read` is always "0", but it should contain some response. When I run the same using Arduino's WIFININA, there is always some response. And for the response to command "17" is always "54". Any suggestions what am I doing wrong? Below working version, which is using Arduino's SDK (communication with WiFi is based on WiFiNINA library, which can be found here https://github.com/arduino-libraries/WiFiNINA/tree/master/src/utility): ``` #include <SPI.h> #include "pins_arduino.h" #include "SPI.h" #define SET_PASSPHRASE_CMD 0x11 #define START_CMD 0xE0 #define END_CMD 0xEE #define REPLY_FLAG 1<<7 #define SLAVESELECT (26u) #define SLAVEREADY (27u) #define SLAVERESET (24u) #define NINA_GPIO0 (20u) char spiTransfer(volatile char data) { Serial.print("spiTransfer - data = "); Serial.println((uint8_t)data); char result = SPI1.transfer(data); Serial.print("spiTransfer - result = "); Serial.println((uint8_t)result); return result; // return the received byte } void sendCmd(uint8_t cmd, uint8_t numParam) { Serial.print("sendCmd - cmd = "); Serial.print(cmd); Serial.print(" numParam = "); Serial.println(numParam); // Send SPI START CMD spiTransfer(START_CMD); // Send SPI C + cmd spiTransfer(cmd & ~(REPLY_FLAG)); // Send SPI totLen //spiTransfer(totLen); // Send SPI numParam spiTransfer(numParam); // If numParam == 0 send END CMD if (numParam == 0) spiTransfer(END_CMD); } void setup() { Serial.begin(9600); delay(2000); pinMode(SLAVESELECT, OUTPUT); pinMode(SLAVEREADY, INPUT); pinMode(SLAVERESET, OUTPUT); pinMode(NINA_GPIO0, OUTPUT); digitalWrite(NINA_GPIO0, HIGH); digitalWrite(SLAVESELECT, HIGH); digitalWrite(SLAVERESET, LOW); delay(10); digitalWrite(SLAVERESET, HIGH); delay(750); digitalWrite(NINA_GPIO0, LOW); pinMode(NINA_GPIO0, INPUT); SPI1.begin(); SPI1.beginTransaction(SPISettings(8000000, MSBFIRST, SPI_MODE0)); digitalWrite(SLAVESELECT,LOW); sendCmd(SET_PASSPHRASE_CMD, 2); digitalWrite(SLAVESELECT,HIGH); SPI1.endTransaction(); } void loop() { // Nothing in the loop for this example } ``` In this case the result is: ``` sendCmd - cmd = 17 numParam = 2 spiTransfer - data = 224 spiTransfer - result = 176 spiTransfer - data = 17 spiTransfer - result = 54 spiTransfer - data = 2 spiTransfer - result = 222 ``` Both above codes send only part of full command. I wrote the full code which is sending the full command with parameters to connect to WiFi. In case of code which is using Raspberry's SDK it was failing, but the Arduino's was successful. Here I post only the first part to make it easier to read. Already in this part, there is a difference in the results. I couldn't find any documentation for that WiFi module, which would allow to write driver for it. Hence I'm trying to port Arduino's WiFiNINA library.
Check the **Trackpad** settings on the Mac: ![Screenshot](https://i.stack.imgur.com/yyaWP.png) With the settings shown here, it works for me when I hold using three fingers.
Although your method worked, I still wouldn’t recommend doing it that way. In general, I would leave the explicit creation of threads for cases of extreme necessity, when it is impossible to do otherwise. The same applies to all UI elements. You should create and work with them only in the main application thread. Therefore, I would suggest that you replace your code with the code I proposed below. And it’s better to replace the code not only in Core/Net applications, but also in the Framework. ```cs { WpfSplashScreen splash = new WpfSplashScreen(); splash.Loaded += async delegate { await Task.Delay(3000); splash.Close(); }; splash.Show(); } ``` Since you often use a display like this, you can create an extension method and use it: ```cs public static class WindowHelper { public static void Show(this Window window, int delayClose) { window.Loaded += async delegate { await Task.Delay(3000); window.Close(); }; window.Show(); } } ``` ```cs { new WpfSplashScreen().Show(3000); } ```
**TL;DR** ```python X_train_permuted = ( X_train_permuted.with_columns( pl.DataFrame(shuffle_arr, schema=features) ) ) ``` ----- Let's work with a simple example. **X_train_permuted** ```python import polars as pl import numpy as np np.random.seed(0) data = {f'feature_{i}': np.random.rand(4) for i in range(0,3)} X_train_permuted = pl.DataFrame(data) X_train_permuted shape: (4, 3) β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ feature_0 ┆ feature_1 ┆ feature_2 β”‚ β”‚ --- ┆ --- ┆ --- β”‚ β”‚ f64 ┆ f64 ┆ f64 β”‚ β•žβ•β•β•β•β•β•β•β•β•β•β•β•ͺ═══════════β•ͺ═══════════║ β”‚ 0.548814 ┆ 0.423655 ┆ 0.963663 β”‚ β”‚ 0.715189 ┆ 0.645894 ┆ 0.383442 β”‚ β”‚ 0.602763 ┆ 0.437587 ┆ 0.791725 β”‚ β”‚ 0.544883 ┆ 0.891773 ┆ 0.528895 β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ ``` **Shuffle `feature_0` and `feature_1`** Use a list to keep track of the features you are shuffling: `features = ["feature_0", "feature_1"]`. ```python features = ["feature_0", "feature_1"] shuffle_arr = np.array(X_train_permuted[:, features]) from sklearn.utils import check_random_state random_state = check_random_state(42) random_seed = random_state.randint(np.iinfo(np.int32).max + 1) random_state.shuffle(shuffle_arr) shuffle_arr array([[0.71518937, 0.64589411], [0.60276338, 0.43758721], [0.5488135 , 0.4236548 ], [0.54488318, 0.891773 ]]) ``` **Replace associated columns in `X_train_permuted` with `shuffle_arr` values** * Use [`pl.DataFrame.with_columns`](https://docs.pola.rs/py-polars/html/reference/dataframe/api/polars.DataFrame.with_columns.html) and pass a [`pl.DataFrame`](https://docs.pola.rs/py-polars/html/reference/dataframe/index.html) with `schema=features`. ```python X_train_permuted = ( X_train_permuted.with_columns( pl.DataFrame(shuffle_arr, schema=features) ) ) X_train_permuted shape: (4, 3) β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ feature_0 ┆ feature_1 ┆ feature_2 β”‚ β”‚ --- ┆ --- ┆ --- β”‚ β”‚ f64 ┆ f64 ┆ f64 β”‚ β•žβ•β•β•β•β•β•β•β•β•β•β•β•ͺ═══════════β•ͺ═══════════║ β”‚ 0.715189 ┆ 0.645894 ┆ 0.963663 β”‚ β”‚ 0.602763 ┆ 0.437587 ┆ 0.383442 β”‚ β”‚ 0.548814 ┆ 0.423655 ┆ 0.791725 β”‚ β”‚ 0.544883 ┆ 0.891773 ┆ 0.528895 β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ ```
regex working not as expected javascript, displays wrong values
|javascript|regex|
null
``` FROM node:19.5.0-alpine RUN npm i -g nodemon WORKDIR /app COPY package* . RUN pwd RUN apk update && apk add npm RUN npm install COPY . . RUN pwd RUN npm run build EXPOSE 3007 CMD [ "npm", "run", "preview" ] ``` In terminal ``` docker build -t saathi . ``` Getting error ``` 0.0s => CACHED [ 6/10] RUN apk update && apk add npm 0.0s => ERROR [ 7/10] RUN npm install 24.7s ------ > [ 7/10] RUN npm install: 1.064 npm WARN EBADENGINE Unsupported engine { 1.064 npm WARN EBADENGINE package: 'vite@5.1.6', 1.064 npm WARN EBADENGINE required: { node: '^18.0.0 || >=20.0.0' }, 1.064 npm WARN EBADENGINE current: { node: 'v19.5.0', npm: '9.3.1' } 1.064 npm WARN EBADENGINE } 24.50 npm ERR! code ERR_SOCKET_TIMEOUT 24.50 npm ERR! network Socket timeout 24.50 npm ERR! network This is a problem related to network connectivity. 24.50 npm ERR! network In most cases you are behind a proxy or have bad network settings. 24.50 npm ERR! network 24.50 npm ERR! network If you are behind a proxy, please make sure that the 24.50 npm ERR! network 'proxy' config is set properly. See: 'npm help config' 24.51 24.51 npm ERR! A complete log of this run can be found in: 24.51 npm ERR! /root/.npm/_logs/2024-03-31T17_24_20_245Z-debug-0.log ------ Dockerfile:12 -------------------- 10 | RUN pwd 11 | RUN apk update && apk add npm 12 | >>> RUN npm install 13 | COPY . . 14 | RUN pwd -------------------- ERROR: failed to solve: process "/bin/sh -c npm install" did not complete successfully: exit code: 1 (base) riz@riz-Aspier-XXXX:~/Desktop/Saathi/frontend$ ``` Can anyone tell me why i am getting this error . I have tried many thing and also search answer on stackoverflow , but all the approach have been failed , in my case . Why i am getting error after npm install , i am not able to find . Please help me
Facing error in creating image of my react+vite project . Dockerfile error
|reactjs|docker|dockerfile|vite|
null
Coroutines can be used in the main thread for network calls, but network calls may take more time because of multiple reasons, and for that time the main thread is blocked. Because the main thread is responsible for rendering the UI, it will give a bad user experience as well as it may result in ANR (Application Not Responding).
In my Flutter Web Application, I have the following created tables for an address in Supabase: ``` -- Table for Region CREATE TABLE regions ( id SERIAL PRIMARY KEY, region_name TEXT NOT NULL ); -- Table for Province CREATE TABLE provinces ( id SERIAL PRIMARY KEY, province_name TEXT NOT NULL, region_id INT REFERENCES regions(id) NOT NULL ); -- Table for Municipalities/Cities CREATE TABLE municipalities ( id SERIAL PRIMARY KEY, municipality_name TEXT NOT NULL, province_id INT REFERENCES provinces(id) NOT NULL ); -- Table for Barangay (similar to a District or Ward) CREATE TABLE barangays ( id SERIAL PRIMARY KEY, barangay_name TEXT NOT NULL, municipality_id INT REFERENCES municipalities(id) NOT NULL ); ``` I need to retrieve the complete address by concatenating the results so I created a Remote Procedure Call: ``` CREATE OR REPLACE FUNCTION get_complete_address(respondent_id TEXT) RETURNS TEXT AS $$ DECLARE address TEXT; BEGIN SELECT CONCAT(COALESCE(r.purok, ''), ' ', b.barangay_name, ', ', m.municipality_name, ', ', p.province_name, ', ', reg.region_name) INTO address FROM respondents r INNER JOIN barangays b ON r.barangay_id = b.id INNER JOIN municipalities m ON b.municipality_id = m.id INNER JOIN provinces p ON m.province_id = p.id INNER JOIN regions reg ON p.region_id = reg.id WHERE r.id = respondent_id::uuid; RETURN address; END; $$ LANGUAGE plpgsql; ``` Purok is smaller than a barangay and may be null. Testing it in the Supabase Dashboard, it worked using ```SELECT get_complete_address("<respondent_id>");``` I wanted this to be included in the Flutter Data Model and have also updated an existing Repository. This is how the data model for a Respondent is: ``` class Respondent { final String id; ... final String? purok; final int barangayId; final String? completeAddress; Respondent({ required this.id, ... this.purok, required this.barangayId, this.completeAddress }); Respondent.fromJson(Map<String, dynamic> json) : id = json['id'], ... purok = json['purok'], barangayId = json['barangay_id'], completeAddress = json['complete_address']; Map<String, dynamic> toJson() => <String, dynamic>{ 'id': id, ... 'purok': purok, 'barangay_id': barangayId, 'complete_address' : completeAddress, }; } ``` In my Repository: ``` Future<Respondent> getRespondent(String id) async { try { print('Getting respondent'); final response = await supabase .from('respondents') .select( '*, parent_group:parent_group_id(description), get_complete_address(id) AS complete_address') .eq('id', id) .single(); print('Response: $response'); return Respondent.fromJson(response); } catch (error) { throw Exception(error); } } ``` The line 'Getting respondent' is printing, but the next *print('Response: $response');* didn't. It means either it has an error in the query, or it was not successfully mapped in the data model. I do not know which is causing the error since it has no error messages. How can I solve or at least try debug this issue? I have been trying to seek Bing/Copilot's assistance, but it keeps showing a deprecated/obsolete function. Thanks in advance.
Embed a mjes player on footer
|wordpress|mediaelement|mediaelement.js|
null