instruction
stringlengths
0
30k
Since there is almost no description about the Use Case, what the input could be look like including edge cases, extremes, etc., not sure if the following minimal example could be a feasible approach ```lang-yaml --- - hosts: localhost become: false gather_facts: false vars: my_list: - /tmp/one/two - /root/whatever tasks: - debug: msg: "{{ my_list + (my_list | map('dirname')) + ['/tmp'] }}" ``` resulting into an output of ```lang-yaml TASK [debug] ***** ok: [localhost] => msg: - /tmp/one/two - /root/whatever - /tmp/one - /root - /tmp ``` In the example it is considered that there is in any case a `/tmp` directory. Then just [append list variable to another list](https://stackoverflow.com/a/31045409/6771046). For other cases one may [accept the other here given answer](https://stackoverflow.com/a/78150520/6771046) as it is the most generic approach and will for work for all deep path structures.
I am searching for the methods to implement a custom payment gateway in OpenEdx Tutor Ecommerce. As far as i have found, OpenEdx as of now doesn't support custom payment gateway. which means that we would have to make changes in the codebase rather than use plugins. Can anybody guide regarding it? anything regarding it would be really helpful. Thanks in advance.
How to integrate a custom payment gateway in OpenEdx Tutor Ecommerce?
|python|payment-gateway|openedx|
`enter code here`i am trying to do the beaglebone black with `core-image-sato` build using yocto project version 4.0.16 (kirkstone). I am using Ubuntu 20.04LTS The build `MACHINE ?= "beaglebone"`, and then I encountered an ERROR during the process. The error is related to `core-image-sato-1.0-r0 do_rootfs`, and the details are attached below. ERROR: core-Image-sato-1.0-ro do_rootfs: Postinstall scriptlets of ['tl-sgx-ddk- um'] have falled. If the intention is to defer them to first boot, then please place them into pkg_postinst_ontarget:S(PN) (). 1 is no longer supported. Deferring to first boot via 'extt Details of the failure are in /home/swan/yocto/sources/tmp/work/beaglebone-poky- linux-gnueabt/core-Image-sato/1.8-re/temp/log.do_rootfs. ERROR: Logfile of fallure stored to: /home/swan/yocto/sources/tmp/work/beaglebon e-poky-linux-gnueabt/core-image-sato/1.8-r0/temp/log.do_rootfs.3737254 ERROR: Task (/home/swan/yocto/poky/meta/recipes-sato/images/core-image-sato.bbid rootfs) falled with exit code 1 NOTE: Tasks Summary: Attempted 7612 tasks of which 7609 didn't need to be rerun and 1 failed. Summary: 1 task failed: /home/swan/yocto/poky/meta/recipes-sato/images/core-image-sato.bb:do_rootfs Summary: There was 1 ERROR message, returning a non-zero exit code. [![error][1]][1] [1]: https://i.stack.imgur.com/yDng9.png The logfile shows this error: update-rc.d: /home/swan/yocto/sources/tmp/work/beaglebone-poky-linux-gnueabi/core-image-sato/1.0-r0/rootfs/etc/init.d/rc.pvr: file does not exist %post(ti-sgx-ddk-um-1.17.4948957-r38.beaglebone): waitpid(3912896) rc 3912896 status 100 warning: %post(ti-sgx-ddk-um-1.17.4948957-r38.beaglebone) scriptlet failed, exit status 1 Error in POSTIN scriptlet in rpm package ti-sgx-ddk-um
How can I tell that a query runs multi-threaded in QuestDB?
|sql|database|questdb|
You should check the execution plan for your query. You can see it by adding EXPLAIN clause at the beginning of the query text: ```sql EXPLAIN SELECT timestamp, first(price) AS open, last(price) AS close, min(price), max(price), sum(amount) AS volume FROM trades WHERE symbol = 'BTC-USD' AND timestamp > dateadd('d', -1, now()) SAMPLE BY 15m ALIGN TO CALENDAR; ``` If you see `Async ...` nodes in the output, e.g. `Async JIT Group By` or `Async JIT Filter`, it means that the corresponding parts of the query execution plan run in parallel, i.e. on multiple threads.
I want to fetch the child user ID based on the parent ID. I have found a solution https://stackoverflow.com/questions/45444391/how-to-count-members-in-15-level-deep-for-each-level-in-php but am getting some errors. I have created a class - ``` <?php Class Team extends Database { private $dbConnection; function __construct($db) { $this->dbConnection = $db; } public function getDownline($id, $depth=5) { $stack = array($id); for($i=1; $i<=$depth; $i++) { // create an array of levels, each holding an array of child ids for that level $stack[$i] = $this->getChildren($stack[$i-1]); } return $stack; } public function countLevel($level) { // expects an array of child ids settype($level, 'array'); return sizeof($level); } private function getChildren($parent_ids = array()) { $result = array(); $placeholders = str_repeat('?,', count($parent_ids) - 1). '?'; $sql="select id from users where pid in ($placeholders)"; $stmt=$this->dbConnection->prepare($sql); $stmt->execute(array($parent_ids)); while($row=$stmt->fetch()) { $results[] = $row->id; } return $results; } } ``` I am using the class like this - ``` $id = 4; $depth = 2; // get the counts of his downline, only 2 deep. $downline_array = $getTeam->getDownline($id, $depth=2); ``` I am getting errors - In line $placeholders = str_repeat('?,', count($parent_ids) - 1). '?'; > Fatal error: Uncaught TypeError: count(): Argument #1 ($value) must be > of type Countable|array, int given in and second > Warning: PDOStatement::execute(): SQLSTATE[HY093]: Invalid parameter > number: number of bound variables does not match number of tokens in line $sql="select id from users where pid in ($placeholders)"; $stmt=$this->dbConnection->prepare($sql); I want to fetch the child user ID in 5 levels
**I have 2 clusters,both publicly accessible,same security groups,but in different public subnets,I can connect to one cluster from local, but not the other. Tried connecting via cluster ip, tried adding my ip as well as 0.0.0.0/0 to security groups, rebooted cluster after allowing public access, nothing helped.**
I'm new one in Django and trying to develop website. What I need is to use slugs in URLs in Django. When I use id's everything works well. I have done the following steps: 1. I have a model Posts with . ``` class Post(models.Model): title = models.CharField(max_length=100) slug = models.SlugField(max_length=100, unique=True, default='') content = models.TextField() category = models.ForeignKey(Category, on_delete=models.CASCADE, null=True, blank=True) photo = models.ImageField(upload_to='post_photos/', blank=True) # ImageField для хранения изображений created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) is_published = models.BooleanField(default=False) def __str__(self): return self.title def save(self, *args, **kwargs): if not self.photo: # Если поле photo пустое, генерируем случайный путь к изображению random_image_path = get_random_image_path() self.photo = random_image_path # Привязываем случайное изображение к объекту Post super().save(*args, **kwargs) def get_absolute_url(self): return reverse('post', kwargs={'post_slug': self.slug}) ``` 2. I have written the following in my urls.py and views.py ``` path('fitness/<slug:post_slug>/', views.show_post, name='post'), ``` ``` def show_post(request, post_slug): post = get_object_or_404(Post, slug=post_slug) return render(request, 'show_post.html', {'post': post}) ``` and this works well. But then I try to make some amendmens to use slugs. The following ones: ``` def get_absolute_url(self): return reverse('post', kwargs={'post_slug': self.slug}) ``` `def show_post(request, post_slug): ` ` post = get_object_or_404(Post, slug=post_slug, category__slug='fitness') ` `return render(request, 'show_post.html', {'post': post})` And I get the following error Page not found (404) “/home/tkzeujpw/blog/fitness/fitness-post-1” does not exist Request Method: GET Request URL: http://example.com/fitness/fitness-post-1 Raised by: django.views.static.serve Using the URLconf defined in example.urls, Django tried these URL patterns, in this order: admin/ [name='index'] healthy-nutrition/ [name='nutrition'] fitness/ [name='fitness'] fitness/<slug:post_slug>/ [name='post'] ^(?P<path>.*)$ The current path, fitness/fitness-post-1, matched the last one. You’re seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page. But I change only one parameter self.pk to self.slug. Please help me to solve this problem. Much appreciated. I've searched in web to solve the problem. But as I can see the code is correct (probably).
I have an Enum that I already use for multiple other purposes, however in those cases I use the Enum like a public variable of the class meaning I can access it like `EntityManager.FAll`. However, in the new use case I have for it I want to use the Enum in that class as a function parameter of another class's function like `CEntityManager::EBroadcastTypes`. But no matter what I try, when I try to compile the code this always fails telling me that either when using the scope operator I need to be using a Class or Namespace even though this is a class (error code: C2653), or that `EBroadcastTypes` isnt a known identifier (error code: 2061). Just to further 'visualize' this, as an example. I want to use this Enum for 'filtering channels' when Ray Casting, so that I can either only check for specific Wanted Entities. ``` EntityManager.h class CEntityManager { public: enum EBroadcastTypes { FAll, FVehicle, FProjectile, FDynamic, // Any Entity that can movement on update (ie. Vehicle and Shells) FStatic, // Any Entity that never moves (ie. Scenery) }; struct BroadcastFilter { EBroadcastTypes type; vector<string> channels; }; vector<BroadcastFilter> m_BroadcastFilters; vector<string> GetChannelsOfFilter(EBroadcastTypes Type) { for (const auto& BroadcastFilter : m_BroadcastFilters) { if (BroadcastFilter.type == Type) { return BroadcastFilter.channels; } } } } ``` ``` Main.h // Primary Update(tick) function Update() { if()// On Some condition { TFloat32 range = 400.0f HitResult Hit = RayCast(ray, EntityManager.FAll, range); // Do something with Hit ... } } ``` RayCast file doesn't contain a class, simply functions that fall under the same category that would be used across multiple points/classes throughout the code. ``` CRayCast.h #include "EntityManager.h" HitResult RayCast(CRay ray, , TFloat32 Range); ``` ``` CRayCast.cpp #include "CRayCast.cpp" // Actually using EntityManager here, other than for getting the Enum. extern CEntityManager EntityManager; HitResult RayCast(CRay, CEntityManager::EBroadcastTypes, TFloat32 Range) { // Do the raycasting here // ... } ``` So is there any way to actually use the Enum like this? Tried including the header as well as forward declaring both the class and enum (the compiler then told me it didn't know what those forwards are).
Using an Enum inside a Class as a Function parameter outside of its Class
|c++|windows|class|enums|
null
I'm trying to implement some basic auth for a NextJS app. I have a FastAPI backend which sends a JWT as a cookie on a successful login, which I can see setting the cookie in chrome dev tools, but I can't access this in NextJS. The FastAPI code for the token request is: ``` @router.post('/users/token') async def get_token(response: Response, form_data: Annotated[OAuth2PasswordRequestForm, Depends()]): print('Token requested') if users_collection.find_one({'email': form_data.username}) == None: raise HTTPException(status_code=404, detail='email_not_found') try: user = authenticate_user(form_data.username, form_data.password) except Exception as exception: print("exception in get_token calling authenticate user") print("get_token exception = " ) print(exception) return exception if not user: raise HTTPException(status_code=401, detail='incorrect_credentials') access_token_expiration_delta = timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES) access_token = create_access_token(data={'sub': user.email}, expires_delta=access_token_expiration_delta) response.set_cookie(key='access_token', value=access_token, samesite='lax', httponly='true') response.status_code = 200 print('cookie set') return response ``` this sets a cookie in chrome: [![enter image description here](https://i.stack.imgur.com/bRqQz.png)](https://i.stack.imgur.com/bRqQz.png) However any requests do not send the cookie with the request: ``` 'use client' import { useCookies } from 'next-client-cookies'; // further code... const clientCookies = useCookies(); async function onSubmit(event: FormEvent<HTMLFormElement>) { event.preventDefault(); const formData = new FormData(event.currentTarget); console.log(formData); const rawFormData = { username: formData.get('username'), password: formData.get('password'), }; console.log(rawFormData); const response = await fetch(apiAddress + 'users/token', { method: 'POST', body: formData, credentials: 'include', }); console.log(response.status); console.log(typeof response.status); if (response.status === 404) { handleUserNotFoundOpen(); } if (response.status == 401) { console.log('Password incorrect'); handlePasswordIncorrectOpen(); } if (response.status == 200) { console.log('client Cookie:'); const tokenCookie = clientCookies.get('access_token'); console.log(tokenCookie); // Returns undefined const login_check = await fetch(apiAddress + 'users/get_user/', { credentials: 'include', }); console.log(login_check); router.push('/dashboard'); } ``` The get_user endpoint is: ``` @router.get('/users/get_user/') async def get_user(request: Request): print('get current active user called') try: header = request.headers.get("Cookie") print(header) except Exception as e: print('cookie exception') print(e) try: access_token = request.cookies.get('access_token') print('received access token = ' + str(access_token)) user = await get_current_user(request.cookies.get('access_token')) print('user =') print(user) except Exception as e: print('error encountered') print(e) return {"error": "yes"} print("all good") return {"Authenticated": "Yes"} ``` The backend shows no cookie being provided in the request (received access token = None). Dev tools console also shows no cookie being retrieved. My understanding is the cookie should be automatically sent with all requests to the backend, but this doesn't seem to be happening. Requesting the same in POSTMan and then making a GET request to another API endpoint works just fine so I think I am doing something wrong in NextJS. [![enter image description here][1]][1] [1]: https://i.stack.imgur.com/zzzkH.png Is there a fix for this or is there a simpler way of implementing auth with NextJS? I'd prefer to use JWT as I plan on implementing middleware to check for valid JWTs for protected routes.
Accessing/Sending Cookies with NextJS
|next.js|cookies|fastapi|
you can manually transform the data in order to compare them to a uniform distribution: ``` transformed_data = -np.log10(p_values_data) expected_quantiles = stats.uniform.ppf(np.linspace(0.001, 0.999, len(transformed_data))) ``` and then the command you've already provided
{"OriginalQuestionIds":[1535327],"Voters":[{"Id":523612,"DisplayName":"Karl Knechtel","BindingReason":{"GoldTagBadge":"python"}}]}
I'm using df.compare where I'm doing a diff between 2 csv's which have same index/row names, but when it does df.compare, it does the diff as expected but gives the row index numbers as 0,2,5,... where ever it find the diff between the csv's. What I'm looking out is instead of the row numbers where It finds the diff, I need df.compare to show me the row text. diff_out_csv = old.compare(latest,align_axis=1).rename(columns={'self':'old','other':'latest'}) Current output - NUMBER1 NUMBER2 NUMBER3 old latest old latest old latest 0 -14.1685 -14.0132 -1.2583 -1.2611 NaN NaN 2 -9.7875 -12.2739 -0.3532 -0.3541 86.0 100.0 3 -0.0365 -0.0071 -0.0099 -0.0039 6.0 2.0 4 -1.9459 -1.5258 -0.5402 -0.0492 73.0 131.0 Desired Output - NUMBER1 NUMBER2 NUMBER3 old latest old latest old latest JACK -14.1685 -14.0132 -1.2583 -1.2611 NaN NaN JASON -9.7875 -12.2739 -0.3532 -0.3541 86.0 100.0 JACOB -0.0365 -0.0071 -0.0099 -0.0039 6.0 2.0 JIMMY -1.9459 -1.5258 -0.5402 -0.0492 73.0 131.0 I was able to replace the column names using df.compare.rename(columns={}) but how do I replace 0, 2, 3, 4 with the text names ?
i am trying to do the beaglebone black with `core-image-sato` build using yocto project version 4.0.16 (kirkstone). I am using Ubuntu 20.04LTS The build `MACHINE ?= "beaglebone"`, and then I encountered an ERROR during the process. The error is related to `core-image-sato-1.0-r0 do_rootfs`, and the details are attached below. ERROR: core-Image-sato-1.0-ro do_rootfs: Postinstall scriptlets of ['tl-sgx-ddk- um'] have falled. If the intention is to defer them to first boot, then please place them into pkg_postinst_ontarget:S(PN) (). 1 is no longer supported. Deferring to first boot via 'extt Details of the failure are in /home/swan/yocto/sources/tmp/work/beaglebone-poky- linux-gnueabt/core-Image-sato/1.8-re/temp/log.do_rootfs. ERROR: Logfile of fallure stored to: /home/swan/yocto/sources/tmp/work/beaglebon e-poky-linux-gnueabt/core-image-sato/1.8-r0/temp/log.do_rootfs.3737254 ERROR: Task (/home/swan/yocto/poky/meta/recipes-sato/images/core-image-sato.bbid rootfs) falled with exit code 1 NOTE: Tasks Summary: Attempted 7612 tasks of which 7609 didn't need to be rerun and 1 failed. Summary: 1 task failed: /home/swan/yocto/poky/meta/recipes-sato/images/core-image-sato.bb:do_rootfs Summary: There was 1 ERROR message, returning a non-zero exit code. [![error][1]][1] [1]: https://i.stack.imgur.com/yDng9.png The logfile shows this error: update-rc.d: /home/swan/yocto/sources/tmp/work/beaglebone-poky-linux-gnueabi/core-image-sato/1.0-r0/rootfs/etc/init.d/rc.pvr: file does not exist %post(ti-sgx-ddk-um-1.17.4948957-r38.beaglebone): waitpid(3912896) rc 3912896 status 100 warning: %post(ti-sgx-ddk-um-1.17.4948957-r38.beaglebone) scriptlet failed, exit status 1 Error in POSTIN scriptlet in rpm package ti-sgx-ddk-um
Hello You can check this tool from google [Google Vision Api](https://cloud.google.com/vision?_gl=1*fac9wt*_up*MQ..&gclid=Cj0KCQjwncWvBhD_ARIsAEb2HW_oca4BYUArStP5y35WD5cf5lWarhAdkEsyFF8s_X0OtSIOEKfDHnMaAuQ3EALw_wcB&gclsrc=aw.ds)
null
"Best" is obviously subjective, but your proposed approach works well. And it describes the only limitation, forcing the use of one over the other. > I would say if it's single column unique then can use `unique=true` at column level and if unique key contains multiple columns then use `@UniqueConstraints`. Of course, one might argue for always using `@UniqueConstraints` in order to make the code more uniform. But that is really a matter of code style.
The code below raises `TypeError: insert_image() takes 2 positional arguments but 3 were given`. Can someone tell me how to fix it? ``` class PDFEditor: def __init__(self, input_pdf_path): self.pdf_document = fitz.open(input_pdf_path) def add_image(self, page_number, image_path): pdf_page = self.pdf_document[page_number - 1] rect1 = fitz.Rect(100, 100, 200, 200) pdf_page.insert_image(rect1, image_path, keep_proportion=True, overlay=True) def add_text(self, page_number, x, y, text_to_add, font_name='Helvetica', font_size=12): pdf_page = self.pdf_document[page_number - 1] pdf_page.insert_text((x, y), text_to_add, fontsize=font_size, fontname=font_name) def save(self, output_pdf_path): self.pdf_document.save(output_pdf_path) if __name__ == '__main__': poa_path = os.path.join(os.getcwd(), 'example.pdf') pdf_editor = PDFEditor(poa_path) pdf_editor.add_image(page_number=2, image_path='screenshot example.jpg') pdf_editor.save('test.pdf') ``` I tried to delete or add `self` in different place, like front of `pdf_page`. But it didn't change. At the same time, method `add_text` works well. So I really feel confused..
Getting 404 error when trying to use slugs in Django
|django|slug|
null
`''file:///......../node_modules/openai/core.mjs:285 throw new APIConnectionError(cause: response);` `APIConnectionError: Connection error. at OpenAI.makeRequest (file:///......../node_modules/openai/core.mjs:285:19) at process.processTicksAndRejections (node:internal/process/task_queues:95:5) at async main (file:///......../openai.js:6:22) { status: undefined, headers: undefined, error: undefined, code: undefined, param: undefined, type: undefined, cause: FetchError: request to https://api.openai.com/v1/chat/completions failed, reason: connect ETIMEDOUT 168.143.171.189:443 at ClientRequest.<anonymous> (........\node_modules\node-fetch\lib\index.js:1501:11) at ClientRequest.emit (node:events:518:28) at TLSSocket.socketErrorListener (node:_http_client:495:9) at TLSSocket.emit (node:events:530:35) at emitErrorNT (node:internal/streams/destroy:169:8) at emitErrorCloseNT (node:internal/streams/destroy:128:3) at process.processTicksAndRejections (node:internal/process/task_queues:82:21) { type: 'system', errno: 'ETIMEDOUT', code: 'ETIMEDOUT' } }''` I hope reseive the answer
when i use openaiAPI, a error such as "APIConnectionError: Connection error."
|node.js|openapi|
null
I have below regex <!-- begin snippet: js hide: false console: true babel: false --> <!-- language: lang-js --> const stringPattern = "[a-zA-Z0-9]*"; const stringRegex = new RegExp(stringPattern, "g"); const str = "there are 33 states and 7 union territory in india."; const matches = str.match(stringRegex); console.log({matches}); <!-- end snippet --> why does this result contains whitespaces also while in the regex, have not used `\s` or ` `. and how do we exclude whitespace ? ```js [ "there", "", "are", "", "33", "", "states", "", "and", "", "7", "", "union", "", "territory", "", "in", "", "india", "", "" ] ```
I'm working on my thesis about Ethereum and I want to extract some historical data on a daily basis from 2016 to now (on an hourly basis could be perfect but I can do with daily). The data I need are : - Daily transaction on the Ethereum blockchain - Daily market capitalization (or supply because I already have the price) - Daily Active adresses (if possible) Pleaseeee help me. I tried with different APIs, like Coingecko, Coinmaketcap, and Etherscan, but only on Python as I'm familiar with it and I'm using it for my project. Everey APIs I've tried are limited in requests or in historical data, and it's verey expensive just for 1-3 data points to take a subscription..
Historical data scrapping / collection for Ethereum
|python|api|ethereum|blockchain|
null
Currently there is no `Name` field in the model `Genre`, however there is a `name` field. `catalog migration 0001_initial` indicates this was not always so and it changed at some point. <pre><code>migrations.CreateModel( name='Genre', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('<b>Name</b>', models.CharField(help_text='Enter a book genre', max_length=200, unique=True)), ], <b>^</b> ), <b>|- - <em>Added initially</em></b></code></pre> The simplest solution is a catastrophic database drop and restart. Of course this is unprofessional but if there’s nothing to save/fight for, why stress yourself? There are a thousand and one solutions some of which I’ll work on and get back with test solutions.
We have 1 scenario where user accidentally voided the payment through datachange using Check#voidCheck() method. Is there any way to unvoid the payment ? CC Version : v9.0.4 , PL Version : v9.14.11
How to unvoid payment in ClaimCenter
|guidewire|
I'm currently trying to build a trello-like application with lists and tasks. I wanted to incorporate drag n drop functionality so I added the dndkit library. I've [managed][1] to make the tasks sortable between the lists, and I would like to make the lists sortable aswell. However when I try to nest DndContext and SortableContext the application sometimes enters a weird recursive re-render loop and throws the following error repeatedly: `Warning: Maximum update depth exceeded. This can happen when a component calls setState inside useEffect, but useEffect either doesn't have a dependency array, or one of the dependencies changes on every render.` The application then proceeds adds an `undefined` task into the data and fails when it maps over the data to re-render. I've tried logging to see where the error might be but I was only able to figure out the addition of the `undefined`, not the source of it or the re-render loop. [Here][2] is the current code I have, and here the [repo][3] with both branches. Here is a video demonstrating the issue: https://imgur.com/a/HzRCK9B [1]: https://codesandbox.io/p/github/suspiciousRaccoon/dndkit-sortable-draggable-droppables/only-tasks?layout=%257B%2522sidebarPanel%2522%253A%2522GIT%2522%252C%2522rootPanelGroup%2522%253A%257B%2522direction%2522%253A%2522horizontal%2522%252C%2522contentType%2522%253A%2522UNKNOWN%2522%252C%2522type%2522%253A%2522PANEL_GROUP%2522%252C%2522id%2522%253A%2522ROOT_LAYOUT%2522%252C%2522panels%2522%253A%255B%257B%2522type%2522%253A%2522PANEL_GROUP%2522%252C%2522contentType%2522%253A%2522UNKNOWN%2522%252C%2522direction%2522%253A%2522vertical%2522%252C%2522id%2522%253A%2522clsy493xe00062a688ldylwtg%2522%252C%2522sizes%2522%253A%255B70%252C30%255D%252C%2522panels%2522%253A%255B%257B%2522type%2522%253A%2522PANEL_GROUP%2522%252C%2522contentType%2522%253A%2522EDITOR%2522%252C%2522direction%2522%253A%2522horizontal%2522%252C%2522id%2522%253A%2522EDITOR%2522%252C%2522panels%2522%253A%255B%257B%2522type%2522%253A%2522PANEL%2522%252C%2522contentType%2522%253A%2522EDITOR%2522%252C%2522id%2522%253A%2522clsy493xe00022a683gfceuph%2522%257D%255D%257D%252C%257B%2522type%2522%253A%2522PANEL_GROUP%2522%252C%2522contentType%2522%253A%2522SHELLS%2522%252C%2522direction%2522%253A%2522horizontal%2522%252C%2522id%2522%253A%2522SHELLS%2522%252C%2522panels%2522%253A%255B%257B%2522type%2522%253A%2522PANEL%2522%252C%2522contentType%2522%253A%2522SHELLS%2522%252C%2522id%2522%253A%2522clsy493xe00042a6814d95r0n%2522%257D%255D%252C%2522sizes%2522%253A%255B100%255D%257D%255D%257D%252C%257B%2522type%2522%253A%2522PANEL_GROUP%2522%252C%2522contentType%2522%253A%2522DEVTOOLS%2522%252C%2522direction%2522%253A%2522vertical%2522%252C%2522id%2522%253A%2522DEVTOOLS%2522%252C%2522panels%2522%253A%255B%257B%2522type%2522%253A%2522PANEL%2522%252C%2522contentType%2522%253A%2522DEVTOOLS%2522%252C%2522id%2522%253A%2522clsy493xe00052a682afm6z65%2522%257D%255D%252C%2522sizes%2522%253A%255B100%255D%257D%255D%252C%2522sizes%2522%253A%255B50%252C50%255D%257D%252C%2522tabbedPanels%2522%253A%257B%2522clsy493xe00022a683gfceuph%2522%253A%257B%2522tabs%2522%253A%255B%257B%2522id%2522%253A%2522clsy493xe00012a68jcq4o4jz%2522%252C%2522mode%2522%253A%2522permanent%2522%252C%2522type%2522%253A%2522FILE%2522%252C%2522filepath%2522%253A%2522%252FREADME.md%2522%252C%2522state%2522%253A%2522IDLE%2522%257D%255D%252C%2522id%2522%253A%2522clsy493xe00022a683gfceuph%2522%252C%2522activeTabId%2522%253A%2522clsy493xe00012a68jcq4o4jz%2522%257D%252C%2522clsy493xe00052a682afm6z65%2522%253A%257B%2522id%2522%253A%2522clsy493xe00052a682afm6z65%2522%252C%2522activeTabId%2522%253A%2522clsyvy6e500132a65rago0llc%2522%252C%2522tabs%2522%253A%255B%257B%2522type%2522%253A%2522SETUP_TASKS%2522%252C%2522id%2522%253A%2522clsyvy6e500132a65rago0llc%2522%252C%2522mode%2522%253A%2522permanent%2522%257D%255D%257D%252C%2522clsy493xe00042a6814d95r0n%2522%253A%257B%2522id%2522%253A%2522clsy493xe00042a6814d95r0n%2522%252C%2522activeTabId%2522%253A%2522clsy4daqd00gy2a683rp1h7da%2522%252C%2522tabs%2522%253A%255B%257B%2522id%2522%253A%2522clsy493xe00032a680tzfarij%2522%252C%2522mode%2522%253A%2522permanent%2522%252C%2522type%2522%253A%2522TERMINAL%2522%252C%2522shellId%2522%253A%2522clsy46aoh000rdmgm6e945ax9%2522%257D%252C%257B%2522type%2522%253A%2522TASK_LOG%2522%252C%2522taskId%2522%253A%2522CSB_RUN_OUTSIDE_CONTAINER%253D1%2520devcontainer%2520templates%2520apply%2520--template-id%2520%255C%2522ghcr.io%252Fdevcontainers%252Ftemplates%252Fjavascript-node%255C%2522%2520--template-args%2520%27%257B%257D%27%2520--features%2520%27%255B%255D%27%2522%252C%2522id%2522%253A%2522clsy4c1sf005u2a684rp4dxno%2522%252C%2522mode%2522%253A%2522permanent%2522%257D%252C%257B%2522type%2522%253A%2522TASK_LOG%2522%252C%2522taskId%2522%253A%2522dev%2522%252C%2522id%2522%253A%2522clsy4daqd00gy2a683rp1h7da%2522%252C%2522mode%2522%253A%2522permanent%2522%257D%255D%257D%257D%252C%2522showDevtools%2522%253Atrue%252C%2522showShells%2522%253Atrue%252C%2522showSidebar%2522%253Atrue%252C%2522sidebarPanelSize%2522%253A15%257D [2]: https://codesandbox.io/p/github/suspiciousRaccoon/dndkit-sortable-draggable-droppables/tasks-and-lists?file=%2Fsrc%2FApp.jsx&layout=%257B%2522sidebarPanel%2522%253A%2522GIT%2522%252C%2522rootPanelGroup%2522%253A%257B%2522direction%2522%253A%2522horizontal%2522%252C%2522contentType%2522%253A%2522UNKNOWN%2522%252C%2522type%2522%253A%2522PANEL_GROUP%2522%252C%2522id%2522%253A%2522ROOT_LAYOUT%2522%252C%2522panels%2522%253A%255B%257B%2522type%2522%253A%2522PANEL_GROUP%2522%252C%2522contentType%2522%253A%2522UNKNOWN%2522%252C%2522direction%2522%253A%2522vertical%2522%252C%2522id%2522%253A%2522clsy65dxz00062a68w9k0r6zr%2522%252C%2522sizes%2522%253A%255B70%252C30%255D%252C%2522panels%2522%253A%255B%257B%2522type%2522%253A%2522PANEL_GROUP%2522%252C%2522contentType%2522%253A%2522EDITOR%2522%252C%2522direction%2522%253A%2522horizontal%2522%252C%2522id%2522%253A%2522EDITOR%2522%252C%2522panels%2522%253A%255B%257B%2522type%2522%253A%2522PANEL%2522%252C%2522contentType%2522%253A%2522EDITOR%2522%252C%2522id%2522%253A%2522clsy65dxy00022a68gczekuk3%2522%257D%255D%257D%252C%257B%2522type%2522%253A%2522PANEL_GROUP%2522%252C%2522contentType%2522%253A%2522SHELLS%2522%252C%2522direction%2522%253A%2522horizontal%2522%252C%2522id%2522%253A%2522SHELLS%2522%252C%2522panels%2522%253A%255B%257B%2522type%2522%253A%2522PANEL%2522%252C%2522contentType%2522%253A%2522SHELLS%2522%252C%2522id%2522%253A%2522clsy65dxy00042a6890wqhl46%2522%257D%255D%252C%2522sizes%2522%253A%255B100%255D%257D%255D%257D%252C%257B%2522type%2522%253A%2522PANEL_GROUP%2522%252C%2522contentType%2522%253A%2522DEVTOOLS%2522%252C%2522direction%2522%253A%2522vertical%2522%252C%2522id%2522%253A%2522DEVTOOLS%2522%252C%2522panels%2522%253A%255B%257B%2522type%2522%253A%2522PANEL%2522%252C%2522contentType%2522%253A%2522DEVTOOLS%2522%252C%2522id%2522%253A%2522clsy65dxz00052a688hq6gpg8%2522%257D%255D%252C%2522sizes%2522%253A%255B100%255D%257D%255D%252C%2522sizes%2522%253A%255B50%252C50%255D%257D%252C%2522tabbedPanels%2522%253A%257B%2522clsy65dxy00022a68gczekuk3%2522%253A%257B%2522id%2522%253A%2522clsy65dxy00022a68gczekuk3%2522%252C%2522tabs%2522%253A%255B%257B%2522id%2522%253A%2522clsy7wjl700022a68x0y9ai3q%2522%252C%2522mode%2522%253A%2522permanent%2522%252C%2522type%2522%253A%2522FILE%2522%252C%2522filepath%2522%253A%2522%252Fsrc%252FApp.jsx%2522%252C%2522state%2522%253A%2522IDLE%2522%257D%255D%252C%2522activeTabId%2522%253A%2522clsy7wjl700022a68x0y9ai3q%2522%257D%252C%2522clsy65dxz00052a688hq6gpg8%2522%253A%257B%2522id%2522%253A%2522clsy65dxz00052a688hq6gpg8%2522%252C%2522activeTabId%2522%253A%2522clsy67pfw00hp2a68duwgagnb%2522%252C%2522tabs%2522%253A%255B%257B%2522type%2522%253A%2522TASK_PORT%2522%252C%2522taskId%2522%253A%2522dev%2522%252C%2522port%2522%253A5173%252C%2522id%2522%253A%2522clsy67pfw00hp2a68duwgagnb%2522%252C%2522mode%2522%253A%2522permanent%2522%252C%2522path%2522%253A%2522%252F%2522%257D%255D%257D%252C%2522clsy65dxy00042a6890wqhl46%2522%253A%257B%2522id%2522%253A%2522clsy65dxy00042a6890wqhl46%2522%252C%2522activeTabId%2522%253A%2522clsy67lyu00el2a68dkiztd8w%2522%252C%2522tabs%2522%253A%255B%257B%2522id%2522%253A%2522clsy65dxy00032a68x8r2z7me%2522%252C%2522mode%2522%253A%2522permanent%2522%252C%2522type%2522%253A%2522TERMINAL%2522%252C%2522shellId%2522%253A%2522clsy46aoh000rdmgm6e945ax9%2522%257D%252C%257B%2522type%2522%253A%2522TASK_LOG%2522%252C%2522taskId%2522%253A%2522CSB_RUN_OUTSIDE_CONTAINER%253D1%2520devcontainer%2520templates%2520apply%2520--template-id%2520%255C%2522ghcr.io%252Fdevcontainers%252Ftemplates%252Fjavascript-node%255C%2522%2520--template-args%2520%27%257B%257D%27%2520--features%2520%27%255B%255D%27%2522%252C%2522id%2522%253A%2522clsy66dwh003z2a68whpk8kwo%2522%252C%2522mode%2522%253A%2522permanent%2522%257D%252C%257B%2522type%2522%253A%2522TASK_LOG%2522%252C%2522taskId%2522%253A%2522dev%2522%252C%2522id%2522%253A%2522clsy67lyu00el2a68dkiztd8w%2522%252C%2522mode%2522%253A%2522permanent%2522%257D%255D%257D%257D%252C%2522showDevtools%2522%253Atrue%252C%2522showShells%2522%253Atrue%252C%2522showSidebar%2522%253Atrue%252C%2522sidebarPanelSize%2522%253A15%257D [3]: https://github.com/suspiciousRaccoon/dndkit-sortable-draggable-droppables
You can simplify your code a bit. See if this works with your word list: ``` import java.nio.file.*; import java.util.*; import java.util.stream.*; import java.io.*; public class WordList { public static void main(String[] args) throws Exception { System.out.println(new WordList().readWordsFromFile(args[0])); } public List<String> readWordsFromFile(String filename) throws IOException { List<String> words = null; try (Stream<String> lines = Files.lines(Path.of(filename))) { words = lines.filter(WordList::isValidWord).map(String::toLowerCase).toList(); } return words; } // Check if a word is valid based on your criteria private static boolean isValidWord(String word) { // You can define your own criteria for a valid word here // For example, check for minimum length, only alphabetic characters, etc. return word.matches("\\p{Alpha}{4,}"); } } ```
Doing: ```dart switch (item.runtimeType) { case TodayDivider: ... ``` uses a [constant pattern](https://dart.dev/language/pattern-types#constant) that compares the `Type` object returned by `item.runtimeType` for equality. Equality for `Type` objects is object identity; they compare equal only to themselves regardless of relationships between types. You instead should use a [variable pattern](https://dart.dev/language/pattern-types#variable) that matches `item` and not `item.runtimeType`: ```dart switch (item) { case TodayDivider _: widget = const TodayDivider(); case DateDivider item: widget = DateDivider(date: item.date); case CheckinCTA _: widget = const CheckinCTA(); case EntryPreview item: widget = EntryPreview( id: item.id, title: item.title, summary: item.summary, ); default: widget = const Text('Unknown item type'); } ```
I can get an Azure Site Recovery plan with powershell : $RecoveryPlan = Get-AzRecoveryServicesAsrRecoveryPlan | where {$_.name -eq "MyRecPlan"} But how do I get a list of all the VMs in this plan with powershell?
Azure Site Recovery - Powershell - How to get a list of all the VMs in a Recovery Plan
|azure|powershell|
I have a two column csv file. Column 1 is string values, column 2 is integer values. If a term is found in a string in Column 1 I want to return the corresponding value in Column 2. | Col1 | Col2 | | -------- | -------------- | | green | 3 | | red | 6 | If Col1 contains "ed" return the corresponding row value in Col2, in this case 6. Thanks. ``` import pandas as pd # Read the CSV file into a pandas DataFrame file_name = input("Enter file name: ") df = pd.read_csv(file_name) string1 = input("Enter search term: ") #check if each element in the DataFrame contains the partial string matches = df.apply(lambda col: col.astype(str).str.contains(string1, case=False)) #get the row and column indices where the partial string matches rows, cols = matches.values.nonzero() for row, col in zip(rows, cols): print(f"Match found at Row: ", row) ```
API cannot connect to SQL with Docker
|c#|asp.net|sql-server|docker|docker-compose|
I'm trying to write this code and I'm only partially done. Not sure how to finish it. Tried many times only to get errors. See attachments for partial code. [code 1][1] [code 2][2] this is the program and what the output should be. only hla basic instructions. use jmp and cmp for loops PROGRAM 6: Crazy 8s Game Write a program that reads a set of three different numbers. Then by subtracting off tens, determine if any of the values ends in an eight. Continue looping as long as one of the numbers in the set ends in eight. Three sets with a value ending in eight wins the game! Shown below are sample program dialogues to help you build your program. Gimme a number: 20 Gimme a number: 12 Gimme a number: 44 Sorry Charlie! You lose the game! Gimme a number: 58 Gimme a number: 23 Gimme a number: 70 One of them ends in eight! Gimme a number: 1 Gimme a number: 12 Gimma a number: 28 One of them ends in eight! Gimme a number: 7 Gimme a number: 8 Gimme a number: 22 One of them ends in eight! You Win The Game! Gimme a number: 51 Gimme a number: 51 Gimme a number: 51 Sorry Charlie! You lose The Game! [1]: https://i.stack.imgur.com/C1TKj.png [2]: https://i.stack.imgur.com/krK40.png
I've deployed OpenStack via DevStack on an Ubuntu server (IP: 192.168.1.9). I'm seeking guidance on exposing OpenStack instances to my local network (IP range: 192.168.1.x). How can I configure OpenStack to allow instances to be accessed from my host machine using local network IPs without encountering conflicts? Any insights would be appreciated. I've deployed OpenStack via DevStack on an Ubuntu server (IP: 192.168.1.9). I'm seeking guidance on exposing OpenStack instances to my local network (IP range: 192.168.1.x).
How to Expose OpenStack Instances to Local Host Physical Network?
|openstack|openstack-neutron|
null
<html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.4/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.4.0/p5.js"></script> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css"> <title>Game Cards App</title> <link rel="icon" type="image/png" href="https://cdn1.iconfinder.com/data/icons/entertainment-events-hobbies/24/card-game-cards-hold-512.png"> <style> #main-content { display: none; } * { box-sizing: border-box; } body { min-height: 100vh; display: flex; align-items: center; justify-content: center; flex-flow: column wrap; background: radial-gradient(circle, rgba(7, 50, 22, 255) 0%, rgba(0, 0, 0, 255) 100%); animation: shine 4s linear infinite; color: white; font-family: "Lato"; -webkit-font-smoothing: antialiased; text-rendering: optimizeLegibility; } ul { margin: 0; padding: 0; list-style-type: none; max-width: 800px; width: 100%; margin: 0 auto; padding: 15px; text-align: center; overflow-x: hidden; } .card { float: left; position: relative; width: calc(33.33% - 30px + 9.999px); height: 340px; margin: 0 30px 30px 0; perspective: 1000; } .card:first-child .card__front { background:#5271C2; } .card__front img { width: 100%; height: 100%; object-fit: cover; } .card:first-child .card__num { text-shadow: 1px 1px rgba(52, 78, 147, 0.8) } .card:nth-child(2) .card__front { background:#35a541; } .card:nth-child(2) .card__num { text-shadow: 1px 1px rgba(34, 107, 42, 0.8); } .card:nth-child(3) { margin-right: 0; } .card:nth-child(3) .card__front { background: #bdb235; } .card:nth-child(3) .card__num { text-shadow: 1px 1px rgba(129, 122, 36, 0.8); } .card:nth-child(4) .card__front { background: #db6623; } .card:nth-child(4) .card__num { text-shadow: 1px 1px rgba(153, 71, 24, 0.8); } .card:nth-child(5) .card__front { background: #3e5eb3; } .card:nth-child(5) .card__num { text-shadow: 1px 1px rgba(42, 64, 122, 0.8); } .card:nth-child(6) .card__front { background: #aa9e5c; } .card:nth-child(6) .card__num { text-shadow: 1px 1px rgba(122, 113, 64, 0.8); } .card:last-child { margin-right: 0; } .card__flipper { cursor: pointer; transform-style: preserve-3d; transition: all 0.6s cubic-bezier(0.23, 1, 0.32, 1); border: 3.5px solid rgba(255, 215, 0, 0.6); /* Altın sarısı rengi ve parıltılı efekt */ background-image: linear-gradient(45deg, rgba(255, 215, 0, 0.5), transparent, rgba(255, 215, 0, 0.5)); /* Arkaplan gradienti */ } .card__front, .card__back { position: absolute; backface-visibility: hidden; top: 0; left: 0; width: 100%; height: 340px; } .card__front { transform: rotateY(0); z-index: 2; overflow: hidden; } .card__back { transform: rotateY(180deg) scale(1.1); background: linear-gradient(45deg, #483D8B, #301934, #483D8B, #301934); display: flex; flex-flow: column wrap; align-items: center; justify-content: center; box-shadow: 0 4px 20px rgba(0, 0, 0, 0.3); } .card__back span { font-weight: bold; /* Metni kalın yap */ color: white; /* Beyaz renk */ font-size: 16px; position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); } .card__name { font-size: 32px; line-height: 0.9; font-weight: 700; } .card__name span { font-size: 14px; } .card__num { font-size: 100px; margin: 0 8px 0 0; font-weight: 700; } @media (max-width: 700px) { .card__num { font-size: 70px; } } @media (max-width: 700px) { .card { width: 100%; height: 290px; margin-right: 0; float: none; } .card .card__front, .card .card__back { height: 290px; overflow: hidden; } } /* Demo */ main { text-align: center; } main h1, main p { margin: 0 0 12px 0; } main h1 { margin-top: 12px; font-weight: 300; } .fa-github { color: white; font-size: 50px; margin-top: 8px; /* Yukarıdaki boşluğu ayarlayın */ } .tm-container { display: flex; justify-content: center; align-items: center; /* Eğer dikey merkezleme de istiyorsanız */ /* Diğer gerekli stil tanımlamaları */ } .tm-letter { display:inline-block; font-size:30px; margin: 0 5px; margin-top: 10px; opacity: 0; transform: translateY(0); animation: letter-animation 6s ease-in-out infinite; } @keyframes letter-animation { 0%, 100% { opacity: 1; transform: translateY(0); } 10%, 40%, 60%, 90% { opacity: 1; transform: translateY(-10px); } 20%, 80% { opacity: 1; transform: translateY(0); } } #m-letter { animation-delay: 1.5s; } a { position: relative; display: inline-block; padding: 0px; } a::before { content: ''; position: absolute; top: 50%; /* Orta konumu */ left: 50%; /* Orta konumu */ transform: translate(-50%, -50%); /* Merkezden düzgün bir şekilde ayarlamak için */ width: 50px; height: 45px; border-radius: 50%; box-shadow: 0 0 8px 4px rgba(110, 110, 110, 0.8); filter: blur(4px) brightness(1.5); opacity: 0; transition: opacity 0.3s ease, transform 0.3s ease; z-index: -1; } a:hover::before { opacity: 1; } body.hoverEffect { background: radial-gradient(circle at center, #000000, #000033, #000066, #1a1a1a); } #gameCard { width: 300px; height: 450px; margin: 50px auto; padding: 20px; border-radius: 15px; box-shadow: 0 0 50px 10px #FFD700, /* Altın sarısı glow */ 0 0 100px 20px #0000FF, /* Mavi glow */ 0 0 150px 30px #000033; /* Koyu mavi shadow */ background: rgba(0,0,0,0.7); /* Slightly transparent black to make the ambilight effect visible behind the card */ color:#FFD700; /* Altın sarısı text */ text-align: center; border: 3px solid #FFD700; /* Altın sarısı border */ } #gameCardLink span { font-size: 18px; margin-right: 5px; /* Harf aralarına 10 piksel boşluk ekler */ font-weight: bold; /* Metni kalın yapar */ } #gameCardLink span:last-child { font-size: 0.79em; /* ® simgesini küçült */ vertical-align: super; /* ® simgesini yukarı taşı */ opacity: 0.9; font-weight: bold; /* Metni kalın yapar */ text-shadow: 2px 2px 2px rgba(0, 0, 0, 0.5); /* Siyah gölge ekler */ } #loading-animation { position: fixed; top: 0; left: 0; width: 100%; height: 100%; background-image: url("https://wallpapercrafter.com/desktop1/516243-black-holes-blue-black-holes-space-1080P.jpg"); background-repeat: no-repeat; background-size: cover ; display: flex; justify-content: center; align-items: center; z-index: 9999; } .loader { border-top: 9px solid #00a2ed; border-radius: 80%; width: 12vw; /* Genişliği viewport'un %25'i yapar */ height: 12vw; /* Yüksekliği de viewport'un %25'i yapar */ animation: spin 2s linear infinite; /* Burada spin animasyonunu kullanıyoruz */ position: absolute; /* Pozisyonu mutlaka absolute olarak ayarlamalısınız. */ left: 44%; /* X ekseninde ortalamak için sayfanın yarısı kadar sola kaydırın. */ top: 46%; /* Y ekseninde ortalamak için sayfanın yarısı kadar yukarı kaydırın. */ transform: translate(-50%, -50%) rotate(0deg); /* Yuvarlak halkanın tam ortasında olması için bu dönüşümü kullanın. */ } @keyframes spin { 0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); } } </style> </head> <body> <div id="loading-animation"> <div class="loader"></div> </div> <div id="main-content"> <div class="tm-container"> <div class="tm-letter" id="t-letter">T</div> <div class="tm-letter" id="m-letter">M</div> </div> <audio id="flipSound" preload="auto"> <source src="https://cdn.freesound.org/previews/321/321114_2776777-lq.ogg" type="audio/wav"> </audio> <main> <div id="gameCardLink"> <span>G</span> <span>a</span> <span>m</span> <span>e</span> <span> </span> <!-- Boşluk eklemek için span ekledik --> <span> </span> <span>C</span> <span> </span> <span>a</span> <span> </span> <span>r</span> <span> </span> <span>d</span> <span> </span> <span>s</span> <span>®</span> <!-- Registered trademark simgesi için span --> </div> <p><a href="https://github.com/murattasci06"><i class="fab fa-github"></i></a></p> </main> <ul> <li class="card" > <div class="card__flipper"> <div class="card__front"> <img src="https://gecbunlari.com/wp-content/uploads/2021/12/Spiderman-No-Way-Home.jpg" alt="Spiderman"> <p class="card__name"><span>Marvel</span><br>Spiderman</p> <p class="card__num">1</p> </div> <iframe class="frame" width="225" height="340" src="https://www.youtube.com/embed/JfVOs4VSpmA?autoplay=1&mute=1&vq=hd1080" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" allowfullscreen ></iframe> <div class="card__back"> <svg height="180" width="180"> <circle cx="90" cy="90" r="65" stroke="#514d9b" stroke-width="35" /> <!-- Dış dairenin kenarı (yeşil) --> <circle cx="90" cy="90" r="83" fill="none" stroke="rgba(7, 50, 22, 255)" stroke-width="1" /> </svg> <span>1.89 Bil. $</span> </div> </div> </li> <li class="card"> <div class="card__flipper"> <div class="card__front"> <img src="https://i.pinimg.com/736x/1e/f1/3d/1ef13dfa4b7b8c131302e242d1ec48d7.jpg" alt="Batman"> <p class="card__name"><span>DC</span><br>Batman</p> <p class="card__num">2</p> </div> <iframe class="frame" width="225" height="340" src="https://www.youtube.com/embed/mqqft2x_Aa4?autoplay=1&mute=1&vq=hd1080" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" allowfullscreen ></iframe> <div class="card__back"> <svg height="180" width="180"> <circle cx="90" cy="90" r="65" stroke="#35a541" stroke-width="35"/> <!-- Dış dairenin kenarı (yeşil) --> <circle cx="90" cy="90" r="83" fill="none" stroke="rgba(7, 50, 22, 255)" stroke-width="1" /> </svg> <span>771 Mil. $</span> </div> </div> </li> <li class="card"> <div class="card__flipper"> <div class="card__front"> <img src="https://wallpapercave.com/wp/wp12279011.jpg" alt="Guardians_of_the_Galaxy_Vol_3"> <p class="card__name"><span>Marvel</span><br>Guardians_of_the_Galaxy_Vol_3</p> <p class="card__num">3</p> </div> <iframe class="frame" width="225" height="340" src="https://www.youtube.com/embed/u3V5KDHRQvk?autoplay=1&mute=1&vq=hd1080" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" allowfullscreen ></iframe> <div class="card__back"> <svg height="180" width="180"> <circle cx="90" cy="90" r="65" stroke="#bdb235" stroke-width="35"/> <!-- Dış dairenin kenarı (yeşil) --> <circle cx="90" cy="90" r="83" fill="none" stroke="rgba(7, 50, 22, 255)" stroke-width="1" /> </svg> <span>845.4 Mil. $</span> </div> </div> </li> <li class="card"> <div class="card__flipper"> <div class="card__front"> <img src="https://wallpaperaccess.com/full/8940499.jpg" alt="Shazam"> <p class="card__name"><span>DC</span><br>Shazam2</p> <p class="card__num">4</p> </div> <iframe class="frame" width="225" height="340" src="https://www.youtube.com/embed/AIc671o9yCI?autoplay=1&mute=1&vq=hd1080" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" allowfullscreen ></iframe> <div class="card__back"> <svg height="180" width="180"> <circle cx="90" cy="90" r="65" stroke="#db6623" stroke-width="35"/> <!-- Dış dairenin kenarı (yeşil) --> <circle cx="90" cy="90" r="83" fill="none" stroke="rgba(7, 50, 22, 255)" stroke-width="1" /> </svg> <span>462.5 Mil. $</span> </div> </div> </li> <li class="card"> <div class="card__flipper"> <div class="card__front"> <img src="https://images2.alphacoders.com/131/1316679.jpeg" alt="Flash"> <p class="card__name"><span>DC</span><br>Flash</p> <p class="card__num">5</p> </div> <iframe class="frame" width="225" height="340" src="https://www.youtube.com/embed/hebWYacbdvc?autoplay=1&mute=1&vq=hd1080" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" allowfullscreen ></iframe> <div class="card__back"> <svg height="180" width="180"> <circle cx="90" cy="90" r="65" stroke="#3e5eb3" stroke-width="35"/> <!-- Dış dairenin kenarı (yeşil) --> <circle cx="90" cy="90" r="83" fill="none" stroke="rgba(7, 50, 22, 255)" stroke-width="1" /> </svg> <span>560.2 Mil. $</span> </div> </div> </li> <li class="card"> <div class="card__flipper"> <div class="card__front"> <img src=" https://images3.alphacoders.com/121/1213553.jpg" alt="Dr_Strange_2"> <p class="card__name"><span>Marvel</span><br>Dr_Strange_2</p> <p class="card__num">6</p> </div> <iframe class="frame" width="225" height="340" src="https://www.youtube.com/embed/aWzlQ2N6qqg?autoplay=1&mute=1&vq=hd1080" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" allowfullscreen ></iframe> <div class="card__back"> <svg height="180" width="180"> <circle cx="90" cy="90" r="65" stroke="#aa9e5c" stroke-width="35"/> <!-- Dış dairenin kenarı (yeşil) --> <circle cx="90" cy="90" r="83" fill="none" stroke="rgba(7, 50, 22, 255)" stroke-width="1" /> </svg> <span>955.8 Mil. $</span> </div> </div> </li> </ul> </div> </body> <script> var Flipper = (function() { var card = $('.card'); var flipper = card.find('.card__flipper'); var win = $(window); var flip = function() { var thisCard = $(this); var thisFlipper = thisCard.find('.card__flipper'); var offset = thisCard.offset(); var xc = win.width() / 2; var yc = win.height() / 2; var docScroll = $(document).scrollTop(); var cardW = thisCard.outerWidth() / 2; var cardH = thisCard.height() / 2; var transX = xc - offset.left - cardW; var transY = docScroll + yc - offset.top - cardH; // if (offset.top > card.height()) transY = docScroll - offset.top + cardH; if (win.width() <= 700) transY = 0; if (card.hasClass('active')) unflip(); thisCard.css({'z-index': '3'}).addClass('active'); thisFlipper.css({ 'transform': 'translate3d(' + transX + 'px,' + transY + 'px, 0) rotateY(180deg) scale(1)', '-webkit-transform': 'translate3d(' + transX + 'px,' + transY + 'px, 0) rotateY(180deg) scale(1)', '-ms-transform': 'translate3d(' + transX + 'px,' + transY + 'px, 0) rotateY(180deg) scale(1)' }).addClass('active'); return false; }; var unflip = function(e) { card.css({'z-index': '1'}).removeClass('active'); flipper.css({ 'transform': 'none', '-webkit-transform': 'none', '-ms-transform': 'none' }).removeClass('active'); }; var bindActions = function() { card.on('click', flip); win.on('click', unflip); } var init = function() { bindActions(); }; return { init: init }; }()); Flipper.init(); </script> <script> <!-- HOOVER FOR TRAILER --> let hoverTimeout; $('.card').hover(function() { const currentCard = $(this); // Store the current card element in a variable hoverTimeout = setTimeout(() => { currentCard.find('.card__front').hide(); currentCard.find('.iframe').show(); var src = currentCard.find('.iframe').attr("src"); currentCard.find('.iframe').attr("src", src); // Add fullscreen functionality currentCard.find('.iframe').on('click', function() { $(this).requestFullscreen(); }); }, 5000); // 5000 milliseconds (5 seconds) }, function() { clearTimeout(hoverTimeout); // Clear the timeout to prevent actions if the user moves away before 5 seconds $(this).find('.card__front').show(); $(this).find('.iframe').hide(); var src = $(this).find('.iframe').attr("src"); $(this).find('.iframe').attr("src", src.replace('?autoplay=1', '')); }); </script> <script> var cardFlags = {}; $(document).ready(function() { var flipSound = document.getElementById("flipSound"); // Sesin yalnızca kartın ön yüzüne tıklandığında çalmasını sağlayın. $(".card__front").click(function() { flipSound.currentTime = 0; flipSound.play(); }); $(".card").click(function() { var card = $(this); var cardId = card.find(".card__num").text(); console.log(cardId); // Check if the card is not already flipping to avoid multiple flips if (!card.hasClass('flipping')) { card.addClass('flipping'); // Check if the front side is facing the viewer if (!card.hasClass("flipped")) { console.log("is card flag true or false", cardId); if (!cardFlags[cardId]) { startAnimation(div); console.log("started"); cardFlags[cardId] = true; card.addClass("flipped"); } // Adding canvas to back-side var div = document.querySelector('.flipped .card__flipper.active .card__back'); var canvas = document.getElementsByClassName('p5Canvas')[0]; if (div && canvas) { div.appendChild(canvas); canvas.style.position = 'absolute'; } } else { console.log("stopped"); card.removeClass("flipped"); flipSound.play(); } setTimeout(function() { card.removeClass('flipping'); }, 1000); // Adjust the timeout to match your animation duration } }); // Prevent sound on back side click $(".card__back").click(function(e) { e.stopPropagation(); }); }); </script> <script> // Body's hoover effect </script> <script> // Portal effect </script> <script> function hideLoadingAnimation() { console.log("Yükleme animasyonu gizleniyor, ana içerik gösteriliyor"); var loadingAnimation = document.getElementById("loading-animation"); var mainContent = document.getElementById("main-content"); loadingAnimation.style.display = "none"; mainContent.style.display = "block"; } window.onload = function() { console.log("Sayfa tamamen yüklendi"); hideLoadingAnimation(); }; </script> </html> Hello friends, While the cards are turned to their back side, when you first click with the left mouse button on the green space behind them, the sound assigned to turn the card back is heard. Normally this sound shouldn't be heard here. This sound does not appear on subsequent clicks. In the code: $(".card__front").click(function() { flipSound.currentTime = 0; flipSound.play(); }); I am stating this situation, but I could not figure out why it is working incorrectly? I was hoping that the sound of the card rotating would only be heard when the card was rotating to the back. I probably have a mistake that experienced people can easily notice. [![enter image description here][1]][1] [1]: https://i.stack.imgur.com/LMh5T.jpg
The problem of making a card rotation sound when you click on the green space underneath the card while it is turned behind its back
|javascript|html|css|frontend|backend|
You will need to change a little your HTML as below (taking out the image and moving also the .buz class at fifth position inside .container_team). You can use then the columns:2; layout for your .container_team and display:inline-block for its children (named here ib) . <!-- begin snippet: js hide: false console: false babel: false --> <!-- language: lang-css --> .team { width: 688px; margin: 0 auto; margin-top: 29px; margin-bottom: 29px; display: flex; flex-direction: column; } .container_team { columns: 2; width: 744px; } .container_team > .ib{ display: inline-block; } .input { display: none; } .input:checked~.p { max-width: 100vw; max-height: 100vh; position: relative; white-space: normal; clip-path: none; margin-top: 15px; } .input:checked+.item_label::after { transform: rotate(315deg); } .h3 { font-family: 'Inter'; font-size: 18px; font-weight: 700; line-height: 25px; letter-spacing: 0em; text-align: center; } .im { margin-top: 20px; margin-bottom: 20px; } .team { max-width: 743px; } .team h3 { font-size: 18px; font-weight: 700; font-family: 'Inter'; line-height: 25px; } .team picture { width: 330px; height: 203px; } .team .le { width: 550px; display: flex; flex-direction: column; align-items: center; } .team .lea { display: flex; flex-direction: column; align-items: center; } .team .pZ { width: 550px; display: flex; flex-direction: column; align-items: center; } .team .zp { width: 550px; display: flex; align-items: center; flex-direction: column; } .team label { display: flex; justify-content: space-between; align-items: center; padding-left: 10px; padding-right: 10px; } .team label::after { content: '+'; width: 30px; height: 30px; font-size: 30px; font-weight: bolder; } .team input:checked~label::after { transform: rotateZ(315deg); } .team .men { width: 300px; font-size: 18px; } .team .buzne { width: 300px; } .team .tele { width: 300px; margin-top: 10px; background: #F5FFD9; } .team .Ar { width: 300px; margin-top: 10px; } .team .Di { width: 300px; margin-top: 10px; } .team .ro { width: 300px; margin-top: 10px; } .team .te { width: 300px; margin-top: 10px; } .team .su { width: 300px; margin-top: 10px; } .team .container_team .p { position: absolute; max-width: 1px; max-height: 1px; margin: -1px; border: 0; padding: 0; white-space: nowrap; clip-path: inset(100%); clip: rect(0 0 0 0); overflow: hidden; padding: 20px; } .team picture { order: 1; margin-left: 190px; } .team picture img { width: 330px; height: 203px; } .h2 { margin-left: 190px; } .team .container_team .input:checked~.p { max-height: 100vh; max-width: 100vw; position: relative; white-space: normal; clip-path: none; } .Ar>.team input:checked { z-index: 1; } <!-- language: lang-html --> <section class="team"> <h2 class="h2">Команда розробників</h2> <div class="container_team"> <div class="men ib"> <input class="input" type="checkbox" name="" id="checks1"> <label for="checks1"> <h3 class="h3">Менеджер проекту</h3> </label> <p class="p">Менеджер проекту розподіляє завдання між командою, планує хід роботи, мотивує команду, контролює процес та координує спільні дії. Також він несе відповідальність за тайм-менеджмент, управління ризиками та дії у разі непередбачених ситуацій. Основний обов’язок і відповідальність PM – довести ідею замовника до реалізації у встановлений термін, використовуючи наявні ресурси. В рамках цієї задачі PM’у необхідно створити план розробки, організувати команду, налаштувати процес роботи над проектом, забезпечити зворотній зв’язок між командами та замовником, усувати перешкоди для команд, контролювати якість і виконання термінів. Його основне завдання полягає в управлінні проектом. Як і бізнес-аналітик, менеджер проекту також може бути включений у комунікацію з клієнтом, проте головним завданням PM є робота безпосередньо з командою розробників програмного забезпечення. Середній вік в Україні- 30 років. Вирізняються високим рівнем освіти (тільки 6% не мають вищої освіти). Зарплата 1700-2500$.</p> </div> <div class="tele ib"> <input type="checkbox" name="" id="checks3"> <label for="checks3"> <h3 class="h3">Team Lead</h3> </label> <p class="p">Це IT-фахівець, який керує своєю командою розробників, володіє технічною стороною, бере участь у роботі над архітектурою проекту, займається рев'ю коду, а також розробкою деяких складних завдань на проекті. За статистикою ДНЗ, середній вік українських тімлідів – 28 років, середній досвід роботи – 6,5 років, середня зарплата – $2800.</p> </div> <div class="Ar ib"> <input type="checkbox" id="checks4"> <label for="checks4"> <h3 class="h3">Архітектор ПЗ</h3> </label> <p class="p"> Приймає рішення щодо внутрішнього устрою і зовнішніх інтерфейсів програмного комплексу з урахуванням проектних вимог і наявних ресурсів.Головна задача архітектора – пошук оптимальних (простих, зручних, дешевих) рішень, які будуть максимально відповідати потребам замовника і можливостям команди. За статистикою ДОУ, середньому українському архітектору 30 років, він має 9-річний досвід роботи і отримує $ 4000.</p> </div> <div class="Di ib"> <input type="checkbox" name="" id="checks5"> <label class="label_comamnd" for="checks5"> <h3 class="h3">Дизайнер</h3> </label> <p class="p">Спеціаліст, який займається проектуванням інтерфейсів користувача. В середньому українському дизайнеру – 26 років, він має досвід роботи від півроку (джуніор) до 5 років (сеньйор) і отримує зарплату $ 1000-200</p> </div> <div class="buzne ib"> <input class="input" type="checkbox" name="" id="checks2"> <label for="checks2"> <h3 class="h3">Бізнес аналітик</h3> </label> <p class="p">Це фахівець, який досліджує проблему замовника, шукає рішення і оформлює його концепцію в формі вимог, на які надалі будуть орієнтуватися розробники при створенні продукту. Середньому українському бізнес-аналітику 28 років, він має зарплату $ 1300-2500 і досвід роботи 3 роки.</p> </div> <div class="ro ib"> <input type="checkbox" name="" id="checks6"> <label for="checks6"> <h3 class="h3">Розробник</h3> </label> <p class="p">Фахівець, який пише вихідний код програм і в кінцевому результаті створює технології. Програмісти також мають різні галузі експертизи, вони пишуть різними мовами та працюють з різними платформами. Тому і існує така “різноманітність” розробників, залучених до одного проекту. На одному проекті переважно завжди є як мінімум два програмісти- перший, який займається back-end розробкою та інший, відповідальний за front-end. Існує два напрямки програмування - системне та прикладне. Системні програмісти мають справу з ОС, інтерфейсами баз даних, мережами. Прикладні – з сайтами, програмним забезпеченням, програмами, редакторами, соцмережами, іграми тощо. Програміст розробляє програми за допомогою математичних алгоритмів. Перед початком роботи йому необхідно скласти алгоритм або знайти оптимальний спосіб вирішення конкретного завдання. В середньому українському програмісту 27 років, його зарплата в середньому дорівнює $ 1500-2500, а досвід роботи становить 4,5 років.</p> </div> <div class="te ib"> <input type="checkbox" name="" id="checks7"> <label for="checks7"> <h3 class="h3">Тестувальник</h3> </label> <p class="p">Фахівець, необхідний для кожного процесу розробки для забезпечення високої якості продукту. Вони тестують його, проходять через усі додатки та визначають баги та помилки з подальшим наданням звіту команді розробки, яка проводить їх виправлення За даними ДОУ, середньому українському QA-інженеру 26 років. Він має досвід роботи від півроку (джуніор) до 5 років (сеньйор) і отримує зарплату $ 600-2700.</p> </div> <div class="su ib"> <input type="checkbox" name="" id="checks8"> <label for="checks8"> <h3 class="h3">Support</h3> </label> <p class="p">Ключове завдання support-фахівця (або Customer Support Representative) — відповідати на запитання і допомагати клієнтам у телефонному режимі, поштою або у чаті. Решта завдань залежать від процесів у конкретній компанії.</p> </div> </div> <picture> <source media="(min-width:1280px)" srcset="https://picsum.photos/200 1x,https://picsum.photos/200 2x,https://picsum.photos/200 3x"> <img class="im" src="https://picsum.photos/200" alt="Проект"> </picture> </section> <!-- end snippet -->
{"Voters":[{"Id":13434871,"DisplayName":"Limey"},{"Id":20002111,"DisplayName":"Friede"},{"Id":16217248,"DisplayName":"CPlus"}],"SiteSpecificCloseReasonIds":[11]}
I'm creating a subroutine in rust which converts a custom datatype which represents an object's attributes and it's values into that object, but I have no idea how to do so... I'm doing this because I want to create objects from the users input, my plan is to first take the input and parse it into the custom data type and then turn that data into the object. My problem is that, when iterating through the custom data type, I get to the string that represents the attribute and I don't know how to check if that string is a real attribute or how to assign the value to that attribute. This is what I've tried so far but now I'm stuck: ``` enum Value { String(String), Float(f64), Boolean(bool), Object(String, Vec<(String, Value)>), } // Vec<(String, Value)>, E.g. ["Kind", Object("Particle", [("energy", 4.3), ("shape", Object("Sphere", [("radius", 3.2)]))])] fn create_spell(properties: Vec<(String, Value)>) -> Spell { let mut spell = Spell::new(); fn create_spell_inner(properties: Vec<(String, Value)>, spell: &mut Spell) { for property in properties{ match property { // String = attribute name of current object // Value = attribtue value of current object } } } return spell; } ``` Create spell takes in the custom data type and returns the object, Spell, or at least that's what it's meant to do. If you would like to see the rest of the code as of writing this, here you go, but it is a mess of mostly unused functions, structs and enums: https://github.com/CocytusDEDI/MMSpellbook/blob/14a8b5ff31476b99cdec2ebbc28ec647367f2635/src/main.rs
Please, I'm trying to use Apache Camel to load routes during runtime. Version 4.0.4, Jdk17 and no spring-boot usage. ``` var routesLoader = camelContext.getCamelContextExtension().getContextPlugin(RoutesLoader.class); Resource resource = ResourceHelper.fromBytes(path, xml.getBytes()); routesLoader.loadRoutes(resource); ``` This is the content I'm using as xml for test purpose ` private static String camelValidStr = "<?xml version='1.0' encoding='UTF-8'?>" + " <beans " +" xmlns='http://www.springframework.org/schema/beans' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'" +" xsi:schemaLocation='" +" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd" +" http://camel.apache.org/schema/spring http://camel.apache.org/schema/spring/camel-spring.xsd'" +" >" +" <camelContext id='camel' xmlns='http://camel.apache.org/schema/spring'>" + " </camelContext>" +" </beans>";` But I got an error like this org.xml.sax.SAXException: Line: 1, Column: 478, error: cvc-complex-type.2.4.c: The matching wildcard is strict, but no declaration can be found for element 'camelContext'. Any suggestions? recommendations would be much appreciated.
org.xml.sax.SAXException: The matching wildcard is strict, but no declaration can be found for element 'camelContext'
|java|apache-camel|
null
I'm trying out CSES Subarray Sum II - https://cses.fi/problemset/task/1661 and I'm sure of the logic but I'm getting different TLEs in CPython and PyPy3 Here's my code: ``` from sys import stdin, stdout _, x = list(map(int,stdin.readline().split())) arr = list(map(int,stdin.readline().split())) d = {0: 1} curr_sum = 0 ans = 0 for num in arr: curr_sum += num ans += d.get(curr_sum - x, 0) d[curr_sum] = d.get(curr_sum, 0) + 1 stdout.write(str(ans)) ``` Here's my result in PyPy3: ![PyPy3 Result][1] And here's my result in CPython3: ![CPython3 Result][2] Description: - PyPy3 - TestCase 25 fails with TLE, but 26 and 27 pass with less than 0.2 seconds - CPython3 - TestCase 25 passes with 0.85 seconds, but 26 and 27 fail with TLE. All 3 TestCases have an input size of `2*10^5` I think the logic is correct, but I wanted to see if I've missed anything, or if there are any other optimizations I can try. Edit: Added code as block instead of image + image description of TLE [1]: https://i.stack.imgur.com/Yw3YK.png [2]: https://i.stack.imgur.com/BWctb.png
The character `'\r'` is _carriage return_. It returns the cursor to the start of the line. It is often used in Internet protocols in conjunction with newline (`'\n'`) to mark the end of a line (most standards specifies it as `"\r\n"`, but some allows the wrong way around). On Windows the carriage-return newline pair is also used as end-of-line. On the old Macintosh operating system (before OSX) a single carriage-return was used instead of newline as end-of-line, while UNIX and UNIX-like systems (like Linux and OSX) uses a single newline.
Use a set, aggregate with [`issuperset`](): ``` Type = {3,4,5} df['Date'] = pd.to_datetime(df['Date']) keep = df.groupby('Date')['Type'].agg(Type.issubset) out = df[df['Date'].isin(keep.index[keep])] ``` Variant: ``` Type = {3,4,5} df['Date'] = pd.to_datetime(df['Date']) out = df[df.groupby('Date')['Type'].transform(Type.issubset)] ``` Output: ``` Date Type Value 2 2024-03-12 3 3 3 2024-03-12 4 5 4 2024-03-12 5 5 5 2024-03-13 3 3 6 2024-03-13 4 5 ```
{"Voters":[{"Id":2372064,"DisplayName":"MrFlick"},{"Id":22180364,"DisplayName":"Jan"},{"Id":354577,"DisplayName":"Chris"}]}
I would like to be able to pass a parameter through two functions, but defining the parameter that is use with a variable. This would avoid having to specify every possibility of what the parameter could be. See the following example for what I'd like to achieve: ``` run_multiple <- function (parameter_name, parameter_values) { for (value in parameter_values) { run_function(parameter_name = value) } } run_function <- function (x = "a", y = "a", z = "a") { print(sprintf("X is %s, Y is %s, Z is %s", x, y, z)) } ``` Then implementation would ideally work using either of these formats: ``` run_multiple("x", c("a", "b")) run_multiple(x, c("a", "b")) # [1] X is a, Y is a, Z is a # [1] X is b, Y is a, Z is a ``` The above would call `run_function(x = "a")` and `run_function(x = "b")` within the loop of `run_multiple`. I don't think `...` notation in `run_multiple` would help as far as I can tell, as it would only allow me to pass through the single value, not multiple values in the loop. If it's useful, the wider context of this is to be used alongside microbenchmarking for a large function, to see how enabling different versions of sub-functions affects the overall performance. Example of how this works: ``` run_benchmarking <- function (parameter_name, parameter_values, run_names) { # currently setup with only two values allowed microbenchmark::microbenchmark( run_names[1] = run_function(parameter_name = parameter_values[1]), run_names[2] = run_function(parameter_name = parameter_values[2]), times = 1000 ) } run_function <- function (use_x = T, use_y = T, use_z = T) { x <- func1(use_x) y <- func2(use_y) z <- func3(use_z) list(x = x, y = y, z = z) } # example of func n func1 <- function (use_x) { if (use_x) { x <- round(runif(1, 1, 100)) } else { x <- 1 } } # example of benchmarking tests, which would output results from microbenchmark run_benchmarking(use_x, c(T, F), c("With X", "Without X")) run_benchmarking(use_y, c(T, F), c("With Y", "Without Y")) run_benchmarking(use_z, c(T, F), c("With Z", "Without Z")) ``` This currently only accepts two values into a parameter which is something that could be expanded, but should be sufficient for A/B testing initially. I'm also open to other suggestions if there's a better way to test over a number of A/B tests like this.
Its because of the `*` which is a quantifier that allows for zero occurrences, meaning it can also match empty strings, change it to `+` which is quantifier for one or more occurrences <!-- begin snippet: js hide: false console: true babel: false --> <!-- language: lang-js --> const stringPattern = "[a-zA-Z0-9]+"; const stringRegex = new RegExp(stringPattern, "g"); const str = "there are 33 states and 7 union territory in india."; const matches = str.match(stringRegex); console.log({ matches }); <!-- end snippet -->
A simple replacement with both, the old and the new values provided explicitly, would be to traverse to the desired item by iteration and selection, then using that as the LHS for an assignment: ```sh jq '(.run_list[] | select(. == "role[test09]")) = "role[hello]"' input.json ``` [Demo](https://jqplay.org/s/2BX75xeaUWZ) Going further, you can import the string values using the `--arg` option. You could also have an elaborated update, like `|= sub("test09"; "hello")`. If you provide more details to the circumstances of your desired replacement, you could get responses more tailored to your specific needs.
If you have similar enums which are all based on a single value, you can also let them implement a common interface: ```java public interface ValueAware<V> { V getValue(); } ``` And then use the following method to find instances based on a value: ```java public static <T extends Enum<T> & ValueAware<V>, V> Optional<T> findEnumByValue(Class<T> enumClass, V valueToMatch) { return EnumSet.allOf(enumClass).stream() .filter(element -> Objects.equals(element.getValue(), valueToMatch)) .findAny(); } ``` The example enum would look like this: ```java public enum Animal implements ValueAware<String> { DOG("bark"), CAT("meow"); private final String sound; Animal(String sound) { this.sound = sound; } @Override public String getValue() { return sound; } } ``` Example usage: ```java Optional<Animal> cat = findEnumByValue(Animal.class, "meow"); ```
I want to get the user for example to be able to register with Steam and be able to link his Discord account. So far I have managed to get a user to register with Steam (or any provider like Google) but I have not found any documentation on how to link accounts (Google =\> Discord). So far i have this: **Program.cs** ``` builder.Services.AddAuthentication(opt => { opt.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme; opt.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme; opt.DefaultChallengeScheme = DiscordAuthenticationDefaults.AuthenticationScheme; }) .AddCookie(opt => { opt.LoginPath = "/signin"; opt.LogoutPath = "/signout"; } ) .AddDiscord(x => { x.ClientId = builder.Configuration.GetSection("Keys")["ClientID"]; x.ClientSecret = builder.Configuration.GetSection("Keys")["SecretID"]; x.SaveTokens = true; }) .AddSteam(x => { x.ApplicationKey = builder.Configuration.GetSection("Keys")["SteamID"]; x.SaveTokens = true; }); ``` **AuthController.cs** ``` [HttpPost("~/signin")] public async Task<IActionResult> SignIn([FromForm] string provider) { if (string.IsNullOrWhiteSpace(provider)) { return BadRequest(); } if (!await HttpContext.IsProviderSupportedAsync(provider)) { return BadRequest(); } // Instruct the middleware corresponding to the requested external identity // provider to redirect the user agent to its own authorization endpoint. // Note: the authenticationScheme parameter must match the value configured in Startup.cs return Challenge(new AuthenticationProperties { RedirectUri = "/" }, provider); } [HttpGet("~/signout")] [HttpPost("~/signout")] public IActionResult SignOutCurrentUser() { // Instruct the cookies middleware to delete the local cookie created // when the user agent is redirected from the external identity provider // after a successful authentication flow (e.g Google or Facebook). return SignOut(new AuthenticationProperties { RedirectUri = "/" }, CookieAuthenticationDefaults.AuthenticationScheme); } ``` **HttpContextExtensions.cs** The functions present in this class is to determine what provider want to use the user and if supported. ``` public static class HttpContextExtensions { public static async Task<AuthenticationScheme[]> GetExternalProvidersAsync(this HttpContext context) { ArgumentNullException.ThrowIfNull(context); var schemes = context.RequestServices.GetRequiredService<IAuthenticationSchemeProvider>(); return (from scheme in await schemes.GetAllSchemesAsync() where !string.IsNullOrEmpty(scheme.DisplayName) select scheme).ToArray(); } public static async Task<bool> IsProviderSupportedAsync(this HttpContext context, string provider) { ArgumentNullException.ThrowIfNull(context); return (from scheme in await context.GetExternalProvidersAsync() where string.Equals(scheme.Name, provider, StringComparison.OrdinalIgnoreCase) select scheme).Any(); } } ``` **Finally, for auth i'm using AspNet.Security.OAuth.Discord and AspNet.Security.OpenId.Steam mostly of the code that I show can be found in the sample folder of the [github](https://github.com/aspnet-contrib/AspNet.Security.OAuth.Providers).**
ggplot & latex2exp don't show correct symbols
|r|ggplot2|latex2exp|
import scala.reflect.runtime.universe._ object CaseClassUtils { def productElementNames[T <: Product: TypeTag]: Set[String] = typeOf[T].members.collect { case m: MethodSymbol if m.isCaseAccessor => m.name.toString }.toSet }
I have the following three tables in a mysql database: grades: id st_id Q1 Q1 ------------------------------- 1 20001 93 89 2 20002 86 84 3 20003 89 92 4 20001 93 89 5 20002 86 84 6 20003 89 92 ------------------------------- subjects: id subject yr ------------------------------- 1 English 2023 2 Math 2023 3 Science 2023 ------------------------------- grades_subject: sbj_id st_id grd_id ---------------------------- 1 20001 20001 1 20002 20002 1 20003 20003 2 20001 20001 2 20002 20002 2 20003 20003 ---------------------------- The grades table containes an id (primary key) student_id and quiz scores. A student_id can appear multiple times in this table. The Subjects table is a simple list of subjects with a primary key. The grades_subject table links the two with a subject id, grade id (The st_id links another table with student information). All three are a primary keys. As you can see, a subject id can appear many times in this table as each student in the grades table can have multiple subjects. 20001 appears twice, once with subject id 1 and again with subject id 2 etc. Each subject id can also appear numerous times as numerous student_ids in the grades table can share one subject. Im tyring to get all records in the grades table, grouped by subject id. So the result would be: sbj_id 1...then all the students in that class with their respective grades. sbj_id 2... and so one for all subjects. I have tried various solutions from this site and many combinations of different types of joins, groupings and also used select distinct. I either get duplicate values, or the correct records in the grades table but only 2 subject_ids, or student grades getting repeated for each subject and other inaccurate results.I have also tried subqueries. This is the closest I have gotten to the correct results (I understand I do not neet the group by grades_subject.sbj_id in the below query, its just to demonstrate that it works): SELECT grades.*, grades_subject.sbj_id FROM grades JOIN grades_subject ON grades.st_id = grades_subject.grd_id where grades_subject.sbj_id = 49 group by grades_subject.sbj_id, grades_subject.grd_id It results in all the scores for all students in that class which demonstrates that with my current setup I should be able to get what I am looking for with the right query or grouping. When I remove the where clause, I should get each sbj_id, and then all students in that subject with their scores, then the next subject etc. However, it will retrieve the scores for the first student in the subject, then duplicate those results for all other students in that subject as shown below: sbj_Id | grd_id | Q1 | Q2 | .... '1', '20001', '50', '80', '1', '20001', '50', '80', '1', '20001', '50', '80', '2', '20002', '80', '85', '2', '20002', '80', '85', '2', '20002', '80', '85', Select Distinct does not work, various join types do not work, selecting and grouping by ids in the grades table does not work including the primary id. Instead of listing everything I have tried that does not work... How I can get my desired results with my current set up without changing my table setup as other tables and coding are built on it. The set up works well with all other types of queries that I need except when Im trying to get all student grades accross all subjects. If I must change the set up, please ellaborate on the simplest way. Thank you.
PS F:\SCALER\NODE JS\Module1\mongoose> npm install mongoose npm ERR! code EPERM npm ERR! syscall mkdir npm ERR! path F:\ npm ERR! errno -4048 npm ERR! Error: EPERM: operation not permitted, mkdir 'F:\' npm ERR! [Error: EPERM: operation not permitted, mkdir 'F:\'] { npm ERR! errno: -4048, npm ERR! code: 'EPERM', npm ERR! syscall: 'mkdir', npm ERR! path: 'F:\\' npm ERR! } npm ERR! npm ERR! The operation was rejected by your operating system. npm ERR! It's possible that the file was already in use (by a text editor or antivirus), npm ERR! or that you lack permissions to access it. npm ERR! npm ERR! If you believe this might be a permissions issue, please double-check the npm ERR! permissions of the file and its containing directories, or try running npm ERR! the command again as root/Administrator. npm ERR! A complete log of this run can be found in: npm ERR! C:\Users\Lab\AppData\Local\npm-cache\_logs\2024-03-28T11_14_21_900Z-debug-0.log PS F:\SCALER\NODE JS\Module1\mongoose> Not able to install mongoose in this particular folder
Can anyone help to solve this
|javascript|mongodb|npm|mongoose|installation|
null
[![enter image description here][1]][1]How about an Container with child and foreground decoration starting from the bottom? Please change the CupertinoColor or CupertinoIcons to Color or Icons if you use Material instead of Cupertino theme. Container( foregroundDecoration: const BoxDecoration( gradient: LinearGradient( colors: [ CupertinoColors.black, Color(0x00000000), // transparent color ], begin: Alignment.bottomCenter, end: Alignment.topCenter, stops: [0, 1], ), ), child: Image.network( loadingBuilder: (BuildContext context, Widget child, ImageChunkEvent? loadingProgress) { if (loadingProgress == null) return child; return const Center( child: Text("Loading ..."), ); }, "https://www.ephotozine.com/articles/71-amazing-examples-of-landscape-photography--26838/images/xlg_lrg_185834_1400173414.jpg", errorBuilder: (BuildContext context, Object exception, StackTrace? stackTrace) { return const Icon( CupertinoIcons.nosign, size: 30, color: CupertinoColors.systemGrey, ); },), ), [1]: https://i.stack.imgur.com/RO57O.png
Another possible solution: [[x for x in idx.get_level_values(level)] for level in range(idx.nlevels)] Output: [['A', 'A', 'B', 'B'], ['C', 'D', 'C', 'D']]
Creating TP/SL orders using `trading-stop` doesn't provide orderId, so when you don't have orderId you can't cancel it through their `cancel order` api. You can cancel the TP/SL order using [trading-stop][1] API, just pass `takeProfit='0' 'stopLoss='0'` > takeProfit: Cannot be less than 0, 0 means cancel TP. > > stopLoss: Cannot be less than 0, 0 means cancel SL [1]: https://bybit-exchange.github.io/docs/v5/position/trading-stop
How to implement account linking in Blazor Web App?
|authentication|oauth|blazor|openid|
null
Could yo try this: **/node_modules/ please. Example of .dockerignore file (Best Practice): **/node_modules/ **/dist .git npm-debug.log .coverage .coverage.* .env .aws
If I run the code below, xStep1 does not have an attribute named pivot. According to the doc's it should have this attribute. Any help would be appreciated. x=Diagonal(10000) x[1,3]=0.3 x[3,1]=0.3 xStep1=chol(x,pivot=TRUE)
chol(x,pivot=TRUE) does not have attribute pivot in R
|r|linear-algebra|matrix-factorization|
I'm a beginner to C++ and I'm trying to figure out how to generate random numbers within a certain range. I have the following code, however when run it outputs the same random number 5 times. If I run this without the for loop several times, one after the other, it seems as though there is a pattern where the number chosen increases by 1 each second. Is there a way to get truly random numbers? ``` #include <iostream> #include <ctime> using namespace std; int main() { for (int i = 0; i < 5; i++) { srand(time(nullptr)); const int maxValue = 6; const int minValue = 1; int randomNumber = (rand() % (maxValue - minValue + 1)) + minValue; cout << randomNumber << endl; } return 0; } ``` I hope to output sequences such as 1,3,6,2,4, however I get sequences such as 1,1,1,1,1 and 3,3,3,3,3,3.
How to get a truly random number in C++
|c++|random|
null
I'm working on a recommendation system using TensorFlow and TensorFlow Recommenders (TFRS), and I've run into a perplexing issue during the initialization of the FactorizedTopK metric within my RecommendationModel. Specifically, the error emerges when the model attempts to add a weight named "counter" in the Streaming layer of tfrs.metrics.FactorizedTopK. I am following this following documentation to make my reccomenation model: https://www.tensorflow.org/recommenders/examples/deep_recommenders Here's the relevant section of my model code: ``` programs = tf_dataset.map(lambda x: { "program_id": x["program_id"], "name": x["name"], "Country": x["Country"], "Studylvl": x["Studylvl"], "majors": x["majors"], }) desired_index = 20 desired_data = next(iter(programs.skip(desired_index).take(1))) print("Program ID:", desired_data["program_id"].numpy().decode()) print("Name:", desired_data["name"].numpy().decode()) print("Country:", desired_data["Country"].numpy().decode()) print("Study Level:", desired_data["Studylvl"].numpy().decode()) print("Majors:", desired_data["majors"].numpy().decode()) Program ID: 157027 Name: m.s.e in robotics Country: united states of america Study Level: postgraduate Majors: automation science and engineering, biorobotics, control and dynamical systems, medical robotics and computer integrated surgical , perception and cognitive systems, general robotics ``` ``` class ProgramModel(tf.keras.Model): def __init__(self): super().__init__() max_tokens = 10_000 embedding_dimension = 32 self.program_id_embedding = tf.keras.Sequential([ tf.keras.layers.StringLookup( vocabulary=unique_program_id, mask_token=None), tf.keras.layers.Embedding(len(unique_program_id) + 1, embedding_dimension), ]) self.name_embedding = tf.keras.Sequential([ tf.keras.layers.StringLookup( vocabulary=unique_program_name, mask_token=None), tf.keras.layers.Embedding(len(unique_program_name) + 1, embedding_dimension), ]) self.name_text_vectorizer = tf.keras.layers.TextVectorization(max_tokens=max_tokens, output_mode='int', output_sequence_length=32) self.name_text_embedding = tf.keras.Sequential([ self.name_text_vectorizer, tf.keras.layers.Embedding(max_tokens, embedding_dimension, mask_zero=True), tf.keras.layers.GlobalAveragePooling1D(), ]) self.name_text_vectorizer.adapt(unique_program_name) self.country_embedding = tf.keras.Sequential([ tf.keras.layers.StringLookup( vocabulary=unique_countries, mask_token=None), tf.keras.layers.Embedding(len(unique_countries) + 1, embedding_dimension), ]) self.study_lvl_embedding = tf.keras.Sequential([ tf.keras.layers.StringLookup( vocabulary=unique_study_lvl, mask_token=None), tf.keras.layers.Embedding(len(unique_study_lvl) + 1, embedding_dimension), ]) self.major_text_vectorizer = tf.keras.layers.TextVectorization(max_tokens=max_tokens, output_mode='int', output_sequence_length=32) self.major_text_embedding = tf.keras.Sequential([ self.major_text_vectorizer, tf.keras.layers.Embedding(max_tokens, embedding_dimension, mask_zero=True), tf.keras.layers.GlobalAveragePooling1D() ]) self.major_text_vectorizer.adapt(majors) def call(self, inputs): return tf.concat([ self.country_embedding(inputs["Country"]), self.study_lvl_embedding(inputs["Studylvl"]), self.name_embedding(inputs["name"]), self.name_text_embedding(inputs["name"]), self.major_text_embedding(inputs["majors"]), self.program_id_embedding(inputs["program_id"]), ], axis=1) ``` ``` class CandidateModel(tf.keras.Model): def __init__(self, layer_sizes): super().__init__() self.embedding_model = ProgramModel() self.dense_layers = tf.keras.Sequential() for layer_size in layer_sizes[:-1]: self.dense_layers.add(tf.keras.layers.Dense(layer_size, activation="relu")) self.dense_layers.add(tf.keras.layers.BatchNormalization()) for layer_size in layer_sizes[-1:]: self.dense_layers.add(tf.keras.layers.Dense(layer_size)) def call(self, inputs): feature_embedding = self.embedding_model(inputs) return self.dense_layers(feature_embedding) ``` ``` class RecommendationModel(tfrs.models.Model): def __init__(self, layer_sizes): super().__init__() self.query_model = QueryModel(layer_sizes) self.candidate_model = CandidateModel(layer_sizes) self.task = tfrs.tasks.Retrieval( metrics= tfrs.metrics.FactorizedTopK( candidates=programs.batch(128).map(self.candidate_model) ) ) def compute_loss(self, features, training=False): query_embeddings = self.query_model({ "Country": features["Country"], "Studylvl": features["Studylvl"], "name": features["name"], "majors": features["majors"], }) candidate_embeddings = self.candidate_model({ "Country": features["Country"], "Studylvl": features["Studylvl"], "name": features["name"], "majors": features["majors"], "program_id": features["program_id"], }) return self.task(query_embeddings, candidate_embeddings) model = RecommendationModel([128, 64, 32]) model.compile( optimizer=tf.keras.optimizers.Adam(learning_rate=0.0001), ) model.fit( x=train.batch(2000), epochs=20, verbose=True, validation_data=test.batch(500) ) ``` Upon attempting to initialize the RecommendationModel, I encounter the following ValueError: ``` ValueError: Cannot convert '('c', 'o', 'u', 'n', 't', 'e', 'r')' to a shape. Found invalid entry 'c' of type '<class 'str'>'. ``` Here is the full ErrorLog: ``` --------------------------------------------------------------------------- ValueError Traceback (most recent call last) Cell In[64], line 1 ----> 1 model = RecommendationModel([128, 64, 32]) 2 model.compile( 3 optimizer=tf.keras.optimizers.Adam(learning_rate=0.0001), 4 ) 6 # Train the model Cell In[63], line 7, in RecommendationModel.__init__(self, layer_sizes) 4 self.query_model = QueryModel(layer_sizes) 5 self.candidate_model = CandidateModel(layer_sizes) 6 self.task = tfrs.tasks.Retrieval( ----> 7 metrics= tfrs.metrics.FactorizedTopK( 8 candidates=programs.batch(128).map(self.candidate_model) 9 ) 10 ) File /usr/local/lib/python3.9/site-packages/tensorflow_recommenders/metrics/factorized_top_k.py:79, in FactorizedTopK.__init__(self, candidates, ks, name) 75 super().__init__(name=name) 77 if isinstance(candidates, tf.data.Dataset): 78 candidates = ( ---> 79 layers.factorized_top_k.Streaming(k=max(ks)) 80 .index_from_dataset(candidates) 81 ) 83 self._ks = ks 84 self._candidates = candidates File /usr/local/lib/python3.9/site-packages/tensorflow_recommenders/layers/factorized_top_k.py:376, in Streaming.__init__(self, query_model, k, handle_incomplete_batches, num_parallel_calls, sorted_order) 373 self._num_parallel_calls = num_parallel_calls 374 self._sorted = sorted_order --> 376 self._counter = self.add_weight("counter", dtype=tf.int32, trainable=False) File /usr/local/lib/python3.9/site-packages/keras/src/layers/layer.py:499, in Layer.add_weight(self, shape, initializer, dtype, trainable, regularizer, constraint, name) 497 initializer = initializers.get(initializer) 498 with backend.name_scope(self.name, caller=self): --> 499 variable = backend.Variable( 500 initializer=initializer, 501 shape=shape, 502 dtype=dtype, 503 trainable=trainable, 504 name=name, 505 ) 506 # Will be added to layer.losses 507 variable.regularizer = regularizers.get(regularizer) File /usr/local/lib/python3.9/site-packages/keras/src/backend/common/variables.py:74, in KerasVariable.__init__(self, initializer, shape, dtype, trainable, name) 72 else: 73 if callable(initializer): ---> 74 shape = self._validate_shape(shape) 75 value = initializer(shape, dtype=dtype) 76 else: File /usr/local/lib/python3.9/site-packages/keras/src/backend/common/variables.py:97, in KerasVariable._validate_shape(self, shape) 96 def _validate_shape(self, shape): ---> 97 shape = standardize_shape(shape) 98 if None in shape: 99 raise ValueError( 100 "Shapes used to initialize variables must be " 101 "fully-defined (no `None` dimensions). Received: " 102 f"shape={shape} for variable path='{self.path}'" 103 ) File /usr/local/lib/python3.9/site-packages/keras/src/backend/common/variables.py:426, in standardize_shape(shape) 424 continue 425 if not is_int_dtype(type(e)): --> 426 raise ValueError( 427 f"Cannot convert '{shape}' to a shape. " 428 f"Found invalid entry '{e}' of type '{type(e)}'. " 429 ) 430 if e < 0: 431 raise ValueError( 432 f"Cannot convert '{shape}' to a shape. " 433 "Negative dimensions are not allowed." 434 ) ValueError: Cannot convert '('c', 'o', 'u', 'n', 't', 'e', 'r')' to a shape. Found invalid entry 'c' of type '<class 'str'>'. ``` This error suggests an issue with interpreting parameters during weight initialization within TensorFlow or TFRS's internal code, but I'm at a loss for how to resolve it. I've confirmed that my inputs don't contain any NaN values or other obvious issues, and my learning rate seems reasonable. Has anyone encountered a similar issue or have suggestions on what might be going wrong? I'm using TensorFlow 2.x and TensorFlow Recommenders 0.x. Any insights or guidance would be greatly appreciated!
Using TypeORM for node/typescript: If we have this: ```typescript export const AppDataSource = new DataSource({ // ... synchronize: false, // Recommended for production migrations: ['path/to/your/migrations/*.ts'], // Specify your migrations directory }); ``` if the db is out of sync with the code, is there a way to get a warning? For mongodb, this would basically only be for indexes since collections don't have column types. But for SQL-based DBs, I guess it would require diffing the generated SQL? Which might not be straightforward.