instruction
stringlengths
0
30k
How to click the save or print button inside Google Chrome print window using selenium when the HTML page has shadow-root?
My opinion is try to Wrap your `SuperTextIconButton` with a `FittedBox`. Container( alignment: Alignment.center, // back icon height: Get.height * 0.0494, width: Get.width * 0.1, decoration: BoxDecoration( color: const Color(0xff2a2a2a), borderRadius: BorderRadius.circular(10), ), //edit this lines child: FittedBox( fit: BoxFit.cover, child:SuperTextIconButton( 'Back', onPressed: () => Get.back(), getIcon: Icons.arrow_back_ios_new, buttonColor: const Color(0xff7ED550), ), ) )
I am creating a flask project and I have to write this in my html: `onclick="location.href="/article/{{ article["id"] }}""` But I need three separate sets of quotes to do it, is there anyway to insert something like backslash quote in python? I've tried using "" and '', also using \" and \' but I can't get anything to work.
Multiple quote symbols in HTML code, Flask project
|html|
null
You can user wait for an event in below fashion as explained [here and it helps][1] var waitForRequestTask = page.WaitForRequestAsync("**/*logo*.png"); await page.ClickAsync(".foo"); var request = await waitForRequestTask; Alternatively expect can be used, then it will wait for it before moving forward Expect(Page.locator("Element on target page")).ToBeVisibleAsync() [1]: https://playwright.dev/dotnet/docs/events#waiting-for-event
I adjusted the for loop to make it a bit more easy to handle: for stage in df["Stage"].unique(): # for every unique stage subD = df[df["Stage"]==stage] # get the data for that specific case plt.scatter(x=subD["Cost"], # cost on x axis y=subD["Duration"], # duration on y aaxis marker=subD["Stage_encoded"].unique()[0], # marker from what you defined # color will be automatically changing, no need to specify it in this case label=subD['Stage_encoded'].unique()[0]) # add a label! plt.legend() # legend on the outside! otherwise it will turn on or off each loop! Here's the plot, with the legend ;) [![scatter][1]][1] [1]: https://i.stack.imgur.com/cNEQz.png
2 problems with the code: 1. Functional. By default, disk is closed when its corresponding handle is (which happens automatically when the program ends). So, the disk was opened (and shown in *Explorer*), but only for a very short period of time (after the *AttachVirtualDisk* call till program end), so you were not able to see it. To be able to use the disk, either: - Don't stop the program until you're done using the disk (add an *input* statement at the very end) - Detach the disk lifetime from its handle's one (use *ATTACH\_VIRTUAL\_DISK\_FLAG\_PERMANENT\_LIFETIME* flag from [\[MS.Learn\]: ATTACH\_VIRTUAL\_DISK_FLAG enumeration (virtdisk.h)](https://learn.microsoft.com/en-us/windows/win32/api/virtdisk/ne-virtdisk-attach_virtual_disk_flag)).<br> Needless to say that now, you'll have to detach the disk yourself, by either: - Eject it from *Explorer* - Enhancing code to call *DetachVirtualDisk* Also, not sure what are the implications of repeatedly attaching the disk (without detaching it) 2. Coding - *Undefined Behavior* generator. Check [\[SO\]: C function called from Python via ctypes returns incorrect value (@CristiFati's answer)](https://stackoverflow.com/a/58611011/4788546) for a common pitfall when working with *CTypes* (calling functions) *code00.py*: ``` #!/usr/bin/env python import ctypes as cts import sys from ctypes import wintypes as wts class GUID(cts.Structure): _fields_ = ( ("Data1", cts.c_ulong), ("Data2", cts.c_ushort), ("Data3", cts.c_ushort), ("Data4", cts.c_ubyte * 8), ) class VIRTUAL_STORAGE_TYPE(cts.Structure): _fields_ = ( ("DeviceId", wts.ULONG), ("VendorId", GUID), ) ERROR_SUCCESS = 0 VIRTUAL_STORAGE_TYPE_DEVICE_ISO = 1 VIRTUAL_DISK_ACCESS_READ = 0x000D0000 OPEN_VIRTUAL_DISK_FLAG_NONE = 0x00000000 ATTACH_VIRTUAL_DISK_FLAG_READ_ONLY = 0x00000001 ATTACH_VIRTUAL_DISK_FLAG_PERMANENT_LIFETIME = 0x00000004 VIRTUAL_STORAGE_TYPE_VENDOR_MICROSOFT = GUID(0xEC984AEC, 0xA0F9, 0x47E9, (0x90, 0x1F, 0x71, 0x41, 0x5A, 0x66, 0x34, 0x5B)) def main(*argv): path = r"l:\Kit\Linux\Ubuntu\pc064\20\ubuntu-20.04.1-desktop-amd64.iso" virtdisk = cts.WinDLL("VirtDisk") OpenVirtualDisk = virtdisk.OpenVirtualDisk OpenVirtualDisk.argtypes = (cts.POINTER(VIRTUAL_STORAGE_TYPE), cts.c_wchar_p, cts.c_int, cts.c_int, cts.c_void_p, wts.HANDLE) OpenVirtualDisk.restype = wts.DWORD AttachVirtualDisk = virtdisk.AttachVirtualDisk AttachVirtualDisk.argtypes = (wts.HANDLE, cts.c_void_p, cts.c_int, wts.ULONG, cts.c_void_p, cts.c_void_p) AttachVirtualDisk.restype = wts.DWORD kernel32 = cts.WinDLL("Kernel32.dll") GetLastError = kernel32.GetLastError GetLastError.argtypes = () GetLastError.restype = wts.DWORD CloseHandle = kernel32.CloseHandle CloseHandle.argtypes = (wts.HANDLE,) CloseHandle.restype = wts.BOOL vts = VIRTUAL_STORAGE_TYPE(VIRTUAL_STORAGE_TYPE_DEVICE_ISO, VIRTUAL_STORAGE_TYPE_VENDOR_MICROSOFT) handle = wts.HANDLE() res = OpenVirtualDisk(cts.byref(vts), path, VIRTUAL_DISK_ACCESS_READ, OPEN_VIRTUAL_DISK_FLAG_NONE, None, cts.byref(handle)) if res != ERROR_SUCCESS: print(f"OpenVirtualDisk error: {GetLastError()}") return -1 attach_flags = ATTACH_VIRTUAL_DISK_FLAG_READ_ONLY permanent = bool(argv) # Any argument was passed if permanent: attach_flags |= ATTACH_VIRTUAL_DISK_FLAG_PERMANENT_LIFETIME res = AttachVirtualDisk(handle, None, attach_flags, 0, None, None) if res != ERROR_SUCCESS: print(f"AttachVirtualDisk error: {GetLastError()}") CloseHandle(handle) return -2 input(f"Press <Enter> to continue{'' if permanent else ' (this also closes the ISO drive)'} ...") CloseHandle(handle) # Performed automatically if __name__ == "__main__": print( "Python {:s} {:03d}bit on {:s}\n".format( " ".join(elem.strip() for elem in sys.version.split("\n")), 64 if sys.maxsize > 0x100000000 else 32, sys.platform, ) ) rc = main(*sys.argv[1:]) print("\nDone.\n") sys.exit(rc) ``` **Output**: > ``` > [cfati@CFATI-5510-0:e:\Work\Dev\StackExchange\StackOverflow\q078246936]> sopr.bat > ### Set shorter prompt to better fit when pasted in StackOverflow (or other) pages ### > > [prompt]> "e:\Work\Dev\VEnvs\py_pc064_03.10_test0\Scripts\python.exe" ./code00.py > Python 3.10.11 (tags/v3.10.11:7d4cc5a, Apr 5 2023, 00:38:17) [MSC v.1929 64 bit (AMD64)] 064bit on win32 > > Press <Enter> to continue (this also closes the ISO drive) ... > > Done. > > > [prompt]> > [prompt]> "e:\Work\Dev\VEnvs\py_pc064_03.10_test0\Scripts\python.exe" ./code00.py perm > Python 3.10.11 (tags/v3.10.11:7d4cc5a, Apr 5 2023, 00:38:17) [MSC v.1929 64 bit (AMD64)] 064bit on win32 > > Press <Enter> to continue ... > > Done. > ``` In each of the 2 runs above, the effect is visible in *Explorer* (according to explanations from the beginning): [![Img00][1]][1] [1]: https://i.stack.imgur.com/S7vAH.png
I have some images and folders to rename. They are contained in the folder with the same filename as such. /abc123 /abc123/abc123.jpg None of the filenames or folder names have a dash which I want to add after the alphabet. And some of the filenames are already capitalised, but none of the folder names are capitalised. So I want to achieve the following: From current image name and folder name: abc123.jpg ABC123.jpg /abc123 wxyz123456.jpg /wxyz123456 to the desired: ABC-123.jpg /ABC-123 WXYZ-123456.jpg /WXYZ-123456 I used `rename 's/\(^[a-zA-Z]*\)/$1-/' *.jpg` to rename the images and `rename 's/\(^[a-zA-Z]*\)/$1-/' *` for the folders. This code is recognising the alphabets in front of the numbers, but I do not know how to output that same pattern space and add a dash after it. I thought either `\1` or `$1` would work, but it didn't. What am I missing?
- Create a variant array with `aTxt = Split(.Text, "; ")`, then populate the string array `ArrTxt()` with `aTxt()` ```vb Option Explicit Sub AlphaCites() Application.ScreenUpdating = False Dim ArrTxt() As String, i As Long, j As Long Dim aTxt As Variant With ActiveDocument.Content With .Find .ClearFormatting .Text = "\([!\(]@\)" .Format = False .Forward = True .MatchWildcards = True .Wrap = wdFindStop End With Do While .Find.Execute If InStr(.Text, "; ") > 0 Then .Start = .Start + 1 .End = .End - 1 aTxt = Split(.Text, "; ") ReDim ArrTxt(UBound(aTxt)) For j = 0 To UBound(aTxt) ArrTxt(j) = aTxt(j) Next j WordBasic.SortArray ArrTxt() .Text = Join(ArrTxt(), "; ") End If .Collapse wdCollapseEnd DoEvents Loop End With Application.ScreenUpdating = True End Sub ```
I like to implement data mapping using the [Spatie Laravel Data][1] package. The Spatie package uses classes to define data objects which are filled from arrays or json data. The names of the properties are the field names you want to use in your code and the package provides a [MapInputName][2] attribute modifier to automatically translate incoming data names. First we define the data classes and the field mapping: ``` use Spatie\LaravelData\Attributes\DataCollectionOf; use Spatie\LaravelData\Data; use Spatie\LaravelData\Attributes\MapInputName; use Spatie\LaravelData\DataCollection; class Company extends Data { public function __construct( #[MapInputName('razao_social')] public string $name, #[MapInputName('endereco')] public string $address ) { } } class Order extends Data { public function __construct( #[MapInputName('SKU')] public int $id, #[MapInputName('descricao')] public string $product, #[MapInputName('qtd')] public int $quantity ) { } } class Payload extends Data { public function __construct( #[MapInputName('identificador')] public int $id, #[MapInputName('nome_completo')] public string $name, #[MapInputName('empresa')] public Company $company, #[MapInputName('pedidos')] #[DataCollectionOf(Order::class)] public DataCollection $orders ) { } } ``` When you receive the payload data pass it to the static constructor `from(...)` or use [dependency injection][3] to get data from a Request: ``` $payload = [ [ "identificador" => 1, "nome_completo" => "John Doe", "email" => "j@email.com", "empresa" => [ "razao_social" => "ABC Company", "endereco" => "123 Main St" ], "pedidos" => [ [ "SKU" => 1, "descricao" => "Shoes", "qtd" => 2 ], [ "SKU" => 2, "descricao" => "Shirt", "qtd" => 1 ] ] ] ]; Payload::from($payload[0])->toArray(); ``` The `toArray` function gives the output: ``` [ "id" => 1, "name" => "John Doe", "company" => [ "name" => "ABC Company", "address" => "123 Main St", ], "orders" => [ [ "id" => 1, "product" => "Shoes", "quantity" => 2, ], [ "id" => 2, "product" => "Shirt", "quantity" => 1, ], ], ] ``` Not only does the package provide these mappings but it can also [validate][4] the data through attribute modifiers and be passed to `Model::create` to make Eloquent objects easily. [1]: https://spatie.be/docs/laravel-data/v4/introduction [2]: https://spatie.be/docs/laravel-data/v4/as-a-data-transfer-object/mapping-property-names [3]: https://spatie.be/docs/laravel-data/v4/as-a-data-transfer-object/request-to-data-object [4]: https://spatie.be/docs/laravel-data/v4/validation/introduction
{"OriginalQuestionIds":[4644860],"Voters":[{"Id":11082165,"DisplayName":"Brian61354270"},{"Id":12002570,"DisplayName":"user12002570","BindingReason":{"GoldTagBadge":"c++"}}]}
We have ways to solve the above bug. 1. If your test ng method has a non-void return type[Not void]. If we remove the non-void return type for the test method. 2. Instead of removing the non-void return type we can add a line to the testng.xml file that accepts any return type for testNg methods. Line <suite name="Suite" allow-return-values="true">
I've been using selenium to take screenshots of Reddit posts and comments, and I've run into an issue that I can't find a fix for online. My code gives selenium the ID of the object I want to take a screenshot of, and with the main reddit post itself, this works great. When it comes to the comment though, it always times out (when using WebDriverWait(EC.presence_of_element_located)) or says that it can't find it (when using Driver.FindElement). Here's the code: ``` `def getScreenshotOfPost(header, ID, url): driver = webdriver.Chrome() #Using chrome to define a web driver driver.get(url) #Plugs the reddit url into the web driver driver.set_window_size(width=400, height=1600) wait = WebDriverWait(driver, 30) driver.execute_script("window.focus();") method = By.ID #ID is what I've found to be the most reliable method of look-up handle = f"{header}{ID}" #The header will be of the form "t3_" for posts and "t1_" for comments, and the ID is the ID of the post of comment. element = wait.until(EC.presence_of_element_located((method, handle))) driver.execute_script("window.focus();") fp = open(f'Post_{header}{ID}.png', "wb") fp.write(element.screenshot_as_png) fp.close()` ``` I've tried searching by ID, CLASS, CSS_SELECTOR, and XPATH, and none of them work. I've double checked and the form t1_{the id of the comment} is the correct ID for the comment, regardless of the reddit post. Increasing the wait-time on my web driver doesn't work. I'm not sure what the issue would be. Thanks in advance for any help!
Selenium cannot find the ID of reddit comments, why?
|python|selenium-webdriver|reddit|
null
{"OriginalQuestionIds":[68209351],"Voters":[{"Id":7758804,"DisplayName":"Trenton McKinney","BindingReason":{"GoldTagBadge":"python"}}]}
You should use a dictionary for the Parameters. Parameters = new Dictionary<string, object> { { "Name", "/my-param" }, { "WithDecryption", true } } Ref: https://docs.aws.amazon.com/cdk/api/v2/dotnet/api/Amazon.CDK.CustomResources.AwsSdkCall.html
So i have a template that i'm using on wordpress and doing small adjustments to make it the way i want although now there is an animation on the header done with javascript and i wanted to "eliminate" i will post the code for the mentioned event: // Breadcrumb effect if ($(".dt_pagetitle .canvas").length) { let cnvs = document.getElementById("canvas"), c2d = cnvs.getContext("2d"); cnvs.width = window.innerWidth, cnvs.height = window.innerHeight; let particlesArray = []; window.addEventListener("resize", function() { cnvs.width = window.innerWidth, cnvs.height = window.innerHeight }); let cursor = { x: null, y: null }; cnvs.addEventListener("click", function(e) { cursor.x = e.x, cursor.y = e.y; for (let t = 0; t < 10; t++) particlesArray.push(new particles) }), cnvs.addEventListener("mousemove", function(e) { cursor.x = e.x, cursor.y = e.y; for (let t = 0; t < 10; t++) particlesArray.push(new particles) }); class particles { constructor() {this.x = cursor.x, this.y = cursor.y, this.size = 10 * Math.random() + 1, this.speedX = 3 * Math.random() - 1.5, this.speedY = 3 * Math.random() - 1.5, this.color = "#ffffff"} update() {this.x += this.speedX, this.y += this.speedY, this.size > .2 && (this.size -= .1)} draw() {c2d.strokeStyle = this.color, c2d.lineWidth = .4, c2d.beginPath(), c2d.arc(this.x, this.y, this.size, 0, 2 * Math.PI), c2d.stroke()} } let hndlParticles = () => { for (let e = 0; e < particlesArray.length; e++) particlesArray[e].update(), particlesArray[e].draw(), particlesArray[e].size <= .3 && (particlesArray.splice(e, 1), e--) } let anim = () => { c2d.clearRect(0, 0, cnvs.width, cnvs.height), hndlParticles(), requestAnimationFrame(anim) } anim(); } i was able to remove it using the development of the browser by turning off both events (mouseclick and mousemove), although wanted to make it in a permanent way things i have tried: 1) delete the code from the mentioned file, although i don't want this approach due to the fact if the templates does get some update i would had eventually to delete the code manually once again although it is important to refer that even though i eliminated this code from the file the animation still was running and inspecting the file on the browser i still could see the code (strange i know) thought initially was a cache issue, so cleared it and still ended with the same result 2) tried using a removeEventListener although to the lack of knowledge i have on javascript wasn't successfull either with this said i'm trying to look for some help on this matter, where i could implement some js code and import it on the functions.php child theme
discord.py - Oauth2 - join user to guild
|oauth-2.0|discord|discord.py|
null
As shown below, within the mqst environment, there are two different python binary files: python and python3. But they have the same version, being 3.12. If I do ``` which python ``` I get the python file path. And I will get the python3 file path if I do ``` which python3 ``` Does anyone knows why this is the case? [directory photo containing both python files](https://i.stack.imgur.com/WAue0.jpg) This doesn't affect my workflow. But I am just curious.
Overview ======== This is a very interesting question with a surprising number of answers. The "correct" answer is something you must decide for your specific application. With months, you can choose to do either *chronological computations* or *calendrical computations*. A chronological computation deals with regular units of time points and time durations, such as hours, minutes and seconds. A calendrical computation deals with irregular calendars that mainly serve to give days memorable names. The Chronological Computation --------------------------------- If the question is about some physical process months in the future, physics doesn't care that different months have different lengths, and so a chronological computation is sufficient: * The baby is due in 9 months. * What will the weather be like here 6 months from now? In order to model these things, it may be sufficient to work in terms of the *average* month. One can create a `std::chrono::duration` that has *precisely* the length of an average Gregorian (civil) month. It is easiest to do this by defining a series of durations starting with `days`: `days` is 24 hours: using days = std::chrono::duration <int, std::ratio_multiply<std::ratio<24>, std::chrono::hours::period>>; `years` is 365.2425 `days`, or <sup>146097</sup>/<sub>400</sub> `days`: using years = std::chrono::duration <int, std::ratio_multiply<std::ratio<146097, 400>, days::period>>; And finally `months` is <sup>1</sup>/<sub>12</sub> of `years`: using months = std::chrono::duration <int, std::ratio_divide<years::period, std::ratio<12>>>; Now you can easily compute 8 months from now: auto t = system_clock::now() + months{8}; This is the simplest, and most efficient way to add months to a `system_clock::time_point`. *Important note:* This computation *does not* preserve the time of day, or even the day of the month. The Calendrical Computation --------------------------- It is also possible to add months while preserving *time of day* and *day of month*. Such computations are *calendrical computations* as opposed to *chronological computations*. After choosing a calendar (such as the Gregorian (civil) calendar, the Julian calendar, or perhaps the Islamic, Coptic or Ethiopic calendars &mdash; they all have months, but they are not all the same months), the process is: 1. Convert the `system_clock::time_point` to the calendar. 2. Perform the months computation in the calendrical system. 3. Convert the new calendar time back into `system_clock::time_point`. You can use [Howard Hinnant's free, open-source date/time library][1] to do this for a few calendars. Here is what it looks like for the civil calendar: #include "date/date.h" int main() { using namespace date; using namespace std::chrono; // Get the current time auto now = system_clock::now(); // Get a days-precision chrono::time_point auto sd = floor<days>(now); // Record the time of day auto time_of_day = now - sd; // Convert to a y/m/d calendar data structure year_month_day ymd = sd; // Add the months ymd += months{8}; // Add some policy for overflowing the day-of-month if desired if (!ymd.ok()) ymd = ymd.year()/ymd.month()/last; // Convert back to system_clock::time_point system_clock::time_point later = sys_days{ymd} + time_of_day; } If you don't explicitly check `!ymd.ok()` that is ok too. The only thing that can cause `!ymd.ok()` is for the day field to overflow. For example if you add a month to Oct 31, you'll get Nov 31. When you convert Nov 31 back to `sys_days` it will overflow to Dec 1, just like `mktime`. Or one could also declare an error on `!ymd.ok()` with an `assert` or exception. The choice of behavior is completely up to the client. For grins I just ran this, and compared it with `now + months{8}` and got: now is 2017-03-25 15:17:14.467080 later is 2017-11-25 15:17:14.467080 // calendrical computation now + months{8} is 2017-11-24 03:10:02.467080 // chronological computation This gives a rough "feel" for how the calendrical computation differs from the chronological computation. The latter is perfectly accurate on average; it just has a deviation from the calendrical on the order of a few days. And sometimes the simpler (latter) solution is *close enough*, and sometimes it is not. Only *you* can answer *that* question. **The Calendrical Computation &mdash; Now with timezones** You might want to perform your calendrical computation in a specific timezone. The previous computation was with respect to UTC. > Side note: `system_clock` is not specified to be UTC, but the de facto standard is that it is [Unix Time][2] which is a very close approximation to UTC. And C++20 standardizes this existing practice. You can use [Howard Hinnant's free, open-source timezone library][3] to do this computation. This is an extension of the previously mentioned [datetime library][1]. The code is very similar, you just need to convert to local time from UTC, then to a local calendar, do the computation in the calendrical system, then convert back to local time, and finally back to `system_clock::time_point` (UTC): #include "date/tz.h" int main() { using namespace date; using namespace std::chrono; // Get the current local time zoned_time lt{current_zone(), system_clock::now()}; // Get a days-precision chrono::time_point auto ld = floor<days>(lt.get_local_time()); // Record the local time of day auto time_of_day = lt.get_local_time() - ld; // Convert to a y/m/d calendar data structure year_month_day ymd{ld}; // Add the months ymd += months{8}; // Add some policy for overflowing the day-of-month if desired if (!ymd.ok()) ymd = ymd.year()/ymd.month()/last; // Convert back to local time lt = local_days{ymd} + time_of_day; // Convert back to system_clock::time_point auto later = lt.get_sys_time(); } Updating our results I get: now is 2017-03-25 15:17:14.467080 later is 2017-11-25 15:17:14.467080 // calendrical: UTC later is 2017-11-25 16:17:14.467080 // calendrical: America/New_York now + months{8} is 2017-11-24 03:10:02.467080 // chronological computation The time is an hour later (UTC) because I preserved the local time (11:17am) but the computation started in daylight saving time, and ended in standard time, and so the UTC equivalent is later by 1 hour. The conversion from local time back to UTC is not guaranteed to be unique: // Convert back to local time lt = local_days{ymd} + time_of_day; For example if the resultant local time falls within a daylight saving transition where the UTC offset is decreasing, then there exist *two* mappings from this local time to UTC. The default behavior is to throw an exception if this happens. However one can also preemptively choose the first chronological mapping or the second in the event there are two mappings by replacing this: lt = local_days{ymd} + time_of_day; with: lt = zoned_time{lt.get_time_zone(), local_days{ymd} + time_of_day, choose::earliest}; (or `choose::latest`). If the resultant local time falls within a daylight saving transition where the UTC offset is *increasing*, then the result is in a gap where there are *zero* mappings to UTC. In this case both `choose::earliest` and `choose::latest` map to the same UTC time which borders the local time gap. An Alternative Time Zone Computation --- Above I used `current_zone()` to pick up my current location, but I could have also used a specific time zone (e.g. `"Asia/Tokyo"`). If a different time zone has different daylight saving rules, and if the computation crosses a daylight saving boundary, then this could impact the result you get. An Alternative Calendrical Computation --------------------------- Instead of adding months to 2017-03-25, one might prefer to add months to the 4th Saturday of March 2017, resulting in the 4th Saturday of November 2017. The process is quite similar, one just converts to and from a different "calendar": Instead of this: year_month_day ymd{ld}; ymd += months{8}; one does this: year_month_weekday ymd{ld}; ymd += months{8}; or even more concisely: auto ymd = year_month_weekday{ld} + months{8}; One can choose to do this computation in the `sys_time` system (UTC) or in a specific time zone, just like with the `year_month_day` calendar. And one can choose to check for `!ymd.ok()` in the case that you start on the 5th Saturday, but the resulting month doesn't have 5 Saturdays. If you don't check, then the conversion back to `sys_days` or `local_days` will roll over to the first Saturday (for example) of the next month. Or you can snap back to the *last* Saturday of the month: if (!ymd.ok()) ymd = year_month_weekday{ymd.year()/ymd.month()/ymd.weekday()[last]}; Or you could assert or throw an exception on `!ymd.ok()`. And like above, one could choose what happens if the resultant local time does not have a unique mapping back to UTC. There are lots of design choices to make. And they can each impact the result you get. And in hindsight, just doing the simple chronological computation may not be unreasonable. It all depends on *your* needs. C++20 Update ------------ As I write this update, technical work has ceased on C++20, and it looks like we will have a new C++ standard later this year (just administrative work left to do to complete C++20). The advice in this answer translates well to C++20: 1. For the chronological computation, `std::chrono::months` is supplied by `<chrono>` so you don't have to compute it yourself. 2. For the UTC calendrical computation, loose `#include "date.h"` and use instead `#include <chrono>`, and drop `using namespace date`, and things will just work. 3. For the time zone sensitive calendrical computation, loose `#include "tz.h"` and use instead `#include <chrono>`, drop `using namespace date`, and you're good to go. For Simplicity --- If all you want to do is calendrical computations with months and/or years, `system_clock::time_point` is probably the wrong data structure to start with. You can just work with `year_month_day`, never converting to or from `sys_days` or `local_days`. You can use `parse` and `format` directly with `year_month_day`. There is even a `year_month` data structure that can perform years and months arithmetic so you don't even have to worry about the day field. auto constexpr ymd = year{2024}/January/15 + months{15}; static_assert(ymd == year{2025}/April/15); auto constexpr ym = year{2024}/January + months{15}; static_assert(ym == year{2025}/April); static_assert(ym/15 == year{2025}/April/15); std::istringstream stream{"2024-01-15"}; year_month_day ymd2; stream >> parse("%F", ymd2); string s = format("%F", ymd2 + months{15}); // "2025-04-15" Gone are the differences between chronological and calendrical arithmetic, the danger of day-field overflow, differences between time zones, and worries about converting from local time to UTC not being a unique mapping. [1]: https://howardhinnant.github.io/date/date.html [2]: https://en.wikipedia.org/wiki/Unix_time [3]: https://howardhinnant.github.io/date/tz.html
I installed OpenVINO dependencies and converted the model to OpenVINO format. I have OpenCL device available: ``` $ clinfo -l Platform #0: Intel(R) OpenCL HD Graphics `-- Device #0: Intel(R) Graphics [0xa7a0] ``` Trying to run `yolo predict` on a GPU always results in `Invalid CUDA device requested`, e.g. ``` yolo predict model=openvino_model source='samples/*.jpg' device=gpu yolo predict model=openvino_model source='samples/*.jpg' device=0 ``` What parameter should I use for yolo to find and use OpenCL device #0?
What is the parameter for CLI YOLOv8 predict to use Intel GPU?
|gpu|opencl|intel|yolov8|
OP Here. Both of the following commands are working for me: curl -Lfs "https://motivatedsisters.com/2019/07/08/arabic-review-sr-rahat-basit/" | rg -o '<li>.*?href="(.*?)".*?</a> (.*?)<\/li>' -r 'echo $1 $(unescape_html "$2")' | bash | rg -o '(https?://\S+)\s(.*)' -r 'echo $1 $(unescape_html "$2")' -r '{"url": "$1", "title": "$2"}' | jq -s '.' and curl -Lfs "https://motivatedsisters.com/2019/07/08/arabic-review-sr-rahat-basit/" | rg '<li>.*?href="(.*?)".*?</a> (.*?)<\/li>' -or '$1 $2' | while read -r link title; do echo "$link" "$(unescape_html "$title")"; done | rg -o '(https?://\S+)\s(.*)' -r '{"url": "$1", "title": "$2"}' | jq -s '.'
this worked for me I'v created a atrigger with this insert INSERT INTO pr2_product_carrier (id_product, id_carrier_reference, id_shop) VALUES (NEW.id_product, '10', '1'); My id_carrier is 10. I could understand this solution is not acceptable for many cases that you could need. In my case it was enough so I just have one carrier and I dont need hangled with others. Best regards.
guard let url = URL(string:"https://blaaaajo.de/getHiddenUsers.php") else { return } let postString = "blockedUsers=245,1150" var request = URLRequest(url: url) request.httpMethod = "POST" request.httpBody = postString.data(using: String.Encoding.utf8); do{ let (responseString, _) = try await URLSession.shared.data(for: request) if let decodedResponse = try? JSONDecoder().decode([HiddenUsersModel].self, from: responseString){ gettingBlockedUsers = false blockedUsers = decodedResponse } }catch{ print("Error: \(error)") } the HiddenUsersModel: struct HiddenUsersModel: Codable { var userid: Int var nickname: String } I'm always getting `data not valid` The url and the POST key `blockedUsers` with the value `245,1150` is 100% correct, I'm also using this API for the web and Android app. The code on server side doesn't get executed though, not even at the beginning of the PHP script. So no JSON response is generated. The error I'm getting: Error: Error Domain=NSURLErrorDomain Code=-999 "Abgebrochen" UserInfo={NSErrorFailingURLStringKey=https://blaaaajo.de/do_getblockedusers.php, NSErrorFailingURLKey=https://blaaaajo.de/do_getblockedusers.php, _NSURLErrorRelatedURLSessionTaskErrorKey=( "LocalDataTask <33660134-3AEC-4416-A917-C0FC64934DB5>.<7>" ), _NSURLErrorFailingURLSessionTaskErrorKey=LocalDataTask <33660134-3AEC-4416-A917-C0FC64934DB5>.<7>, NSLocalizedDescription=Abgebrochen} according to the checked answer in https://stackoverflow.com/questions/16073519/how-to-fix-nsurlerrordomain-error-code-999-in-ios it's `another request is made before the previous request is completed` but it's not true, when I print something before `do` then it gets printed only once
Ok turns out all I had to do was upgrade flutter.
I'm studying into a Boot Camp and one of past challenge was create a Pokedex with pokeapi. I over the challenge and now i'm going to fix some thinks. I have a strange problem when i'm into details of the single pokemon. When into interpolation i put the various propriety i don't get a problem, into screen stamp it but console log give me and error. ``` detail.component.ts:79 ERROR TypeError: Cannot read properties of undefined (reading 'type') at DetailComponent_Template (detail.component.ts:26:12) at executeTemplate (core.mjs:11223:9) at refreshView (core.mjs:12746:13) at detectChangesInView$1 (core.mjs:12970:9) at detectChangesInViewIfAttached (core.mjs:12933:5) at detectChangesInComponent (core.mjs:12922:5) at detectChangesInChildComponents (core.mjs:12983:9) at refreshView (core.mjs:12796:13) at detectChangesInView$1 (core.mjs:12970:9) at detectChangesInViewIfAttached (core.mjs:12933:5) ``` ```Details Component @Component({ selector: 'app-detail', standalone: true, imports: [DetailComponent], template: ` <div> <h2>{{ this.pokemonDetails.name.toUpperCase() }}</h2> <img src="https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/other/home/{{ pokemonId }}.png" alt="https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/other/home/{{ pokemonId }}.png" height="100" /> <div> <p>Pokemon type:</p> <p>{{ this.pokemonDetails.types[0].type.name }}</p> <p>{{ this.pokemonDetails.types[1].type.name }}</p> </div> <div> <p> Description: {{ this.speciesDetail.flavor_text_entries[0].flavor_text }} </p> </div> <div> <p>BASE STAT:</p> <ul> <li> <p>HP:{{ this.pokemonDetails.stats[0].base_stat }}</p> </li> <li> <p>ATK:{{ this.pokemonDetails.stats[1].base_stat }}</p> </li> <li> <p>DEF:{{ this.pokemonDetails.stats[2].base_stat }}</p> </li> <li> <p>S. ATK:{{ this.pokemonDetails.stats[3].base_stat }}</p> </li> <li> <p>S. DEF:{{ this.pokemonDetails.stats[4].base_stat }}</p> </li> <li> <p>SPEED:{{ this.pokemonDetails.stats[5].base_stat }}</p> </li> </ul> </div> </div> `, styles: ``, }) export default class DetailComponent implements OnInit { pokemonId!: number; pokemonDetails!: Pokemon; speciesDetail!: Species; public service = inject(StateService); constructor(private route: ActivatedRoute) {} ngOnInit(): void { this.route.params.subscribe((params) => { this.pokemonId = params['id']; this.service.getPokemonById(this.pokemonId).subscribe((pokemon) => { this.pokemonDetails = pokemon; console.log(this.pokemonDetails); }); this.service .getPokemonSpeciesDetailsById(this.pokemonId) .subscribe((pokemon) => { this.speciesDetail = pokemon; console.log(this.speciesDetail); }); }); } } ``` ```this is the service import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { BehaviorSubject, Observable, forkJoin } from 'rxjs'; import { map, mergeMap } from 'rxjs/operators'; import { Pokemon, PokemonResults } from '../../model/pokemon'; @Injectable({ providedIn: 'root', }) export class StateService { private pokemonListSubject: BehaviorSubject<Pokemon[]> = new BehaviorSubject< Pokemon[] >([]); public pokemonList$: Observable<Pokemon[]> = this.pokemonListSubject.asObservable(); constructor(private http: HttpClient) {} fetchPokemonList(offset: number = 0, limit: number = 20): Observable<void> { const url = `https://pokeapi.co/api/v2/pokemon/?offset=${offset}&limit=${limit}`; return this.http.get<PokemonResults>(url).pipe( map((data: PokemonResults) => data.results), mergeMap((pokemonResults) => this.fetchDetailedPokemonData(pokemonResults) ), map((detailedPokemonList) => { this.pokemonListSubject.next(detailedPokemonList); }) ); } private fetchDetailedPokemonData( pokemonList: { name: string; url: string }[] ): Observable<Pokemon[]> { return forkJoin( pokemonList.map((pokemon) => this.http.get<Pokemon>(pokemon.url)) ); } getPokemonById(id: number): Observable<Pokemon> { const url = `https://pokeapi.co/api/v2/pokemon/${id}`; return this.http.get<Pokemon>(url); } getPokemonSpeciesDetailsById(id: number): Observable<any> { const url = `https://pokeapi.co/api/v2/pokemon-species/${id}`; return this.http.get<any>(url); } } ``` [enter image description here](https://i.stack.imgur.com/o3YQe.png) I hope someone can help me because some pokemon display and some no! i'm going crazy to found the problem! <h2>{{ this.pokemonDetails.name?.toUpperCase() }}</h2> I try somethings like this but orange alert appears. I'm newbie into the world of programmation.
Pokedex on Angular 17
null
I'm studying into a Boot Camp and one of past challenge was create a Pokedex with pokeapi. I over the challenge and now I'm going to fix some thinks. I have a strange problem when I'm into details of the single pokemon. When into interpolation I put the various propriety I don't get a problem, into screen stamp it but console log give me and error. ``` detail.component.ts:79 ERROR TypeError: Cannot read properties of undefined (reading 'type') at DetailComponent_Template (detail.component.ts:26:12) at executeTemplate (core.mjs:11223:9) at refreshView (core.mjs:12746:13) at detectChangesInView$1 (core.mjs:12970:9) at detectChangesInViewIfAttached (core.mjs:12933:5) at detectChangesInComponent (core.mjs:12922:5) at detectChangesInChildComponents (core.mjs:12983:9) at refreshView (core.mjs:12796:13) at detectChangesInView$1 (core.mjs:12970:9) at detectChangesInViewIfAttached (core.mjs:12933:5) ``` ```Details Component @Component({ selector: 'app-detail', standalone: true, imports: [DetailComponent], template: ` <div> <h2>{{ this.pokemonDetails.name.toUpperCase() }}</h2> <img src="https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/other/home/{{ pokemonId }}.png" alt="https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/other/home/{{ pokemonId }}.png" height="100" /> <div> <p>Pokemon type:</p> <p>{{ this.pokemonDetails.types[0].type.name }}</p> <p>{{ this.pokemonDetails.types[1].type.name }}</p> </div> <div> <p> Description: {{ this.speciesDetail.flavor_text_entries[0].flavor_text }} </p> </div> <div> <p>BASE STAT:</p> <ul> <li> <p>HP:{{ this.pokemonDetails.stats[0].base_stat }}</p> </li> <li> <p>ATK:{{ this.pokemonDetails.stats[1].base_stat }}</p> </li> <li> <p>DEF:{{ this.pokemonDetails.stats[2].base_stat }}</p> </li> <li> <p>S. ATK:{{ this.pokemonDetails.stats[3].base_stat }}</p> </li> <li> <p>S. DEF:{{ this.pokemonDetails.stats[4].base_stat }}</p> </li> <li> <p>SPEED:{{ this.pokemonDetails.stats[5].base_stat }}</p> </li> </ul> </div> </div> `, styles: ``, }) export default class DetailComponent implements OnInit { pokemonId!: number; pokemonDetails!: Pokemon; speciesDetail!: Species; public service = inject(StateService); constructor(private route: ActivatedRoute) {} ngOnInit(): void { this.route.params.subscribe((params) => { this.pokemonId = params['id']; this.service.getPokemonById(this.pokemonId).subscribe((pokemon) => { this.pokemonDetails = pokemon; console.log(this.pokemonDetails); }); this.service .getPokemonSpeciesDetailsById(this.pokemonId) .subscribe((pokemon) => { this.speciesDetail = pokemon; console.log(this.speciesDetail); }); }); } } ``` ```this is the service import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { BehaviorSubject, Observable, forkJoin } from 'rxjs'; import { map, mergeMap } from 'rxjs/operators'; import { Pokemon, PokemonResults } from '../../model/pokemon'; @Injectable({ providedIn: 'root', }) export class StateService { private pokemonListSubject: BehaviorSubject<Pokemon[]> = new BehaviorSubject< Pokemon[] >([]); public pokemonList$: Observable<Pokemon[]> = this.pokemonListSubject.asObservable(); constructor(private http: HttpClient) {} fetchPokemonList(offset: number = 0, limit: number = 20): Observable<void> { const url = `https://pokeapi.co/api/v2/pokemon/?offset=${offset}&limit=${limit}`; return this.http.get<PokemonResults>(url).pipe( map((data: PokemonResults) => data.results), mergeMap((pokemonResults) => this.fetchDetailedPokemonData(pokemonResults) ), map((detailedPokemonList) => { this.pokemonListSubject.next(detailedPokemonList); }) ); } private fetchDetailedPokemonData( pokemonList: { name: string; url: string }[] ): Observable<Pokemon[]> { return forkJoin( pokemonList.map((pokemon) => this.http.get<Pokemon>(pokemon.url)) ); } getPokemonById(id: number): Observable<Pokemon> { const url = `https://pokeapi.co/api/v2/pokemon/${id}`; return this.http.get<Pokemon>(url); } getPokemonSpeciesDetailsById(id: number): Observable<any> { const url = `https://pokeapi.co/api/v2/pokemon-species/${id}`; return this.http.get<any>(url); } } ``` ![Image](https://i.stack.imgur.com/o3YQe.png) I hope someone can help me because some pokemon display and some no! i'm going crazy to found the problem! ``` <h2>{{ this.pokemonDetails.name?.toUpperCase() }}</h2> ``` I try somethings like this but orange alert appears. I'm newbie into the world of programming.
If you want to use a `switch` statement for ranges, generally you need to map the ranges to specific values. They could be discrete integers, but in Java it makes sense to use `enum`s, because the `enum` definition can have a method that does the mapping. `enum`s can be public, but they can also be private, within a class, if you don't need to use them anywhere else. For example: ``` public class Something { private static enum RangeType { LOW(0, 10), MID(10, 20), HIGH(20, 30); private final int lowRange; private final int highRange; RangeType(int lowRange, int highRange) { this.lowRange = lowRange; this.highRange = highRange; } public RangeType getRange(int val) { for (RangeType rt : RangeType.values()) { if (rt.lowRange <= val && val < rt.highRange) { return rt; } } return null; } } public int doSomething(int s) { int newS; RangeType sRange = RangeType.getRange(s); switch (sRange) { case LOW: newS = 15; break; case MID: newS = 3; break; case HIGH: newS = 9; break; default: newS = 0; } return newS; } } ``` Using an enum might be overkill, but it does illustrate how the mapping can be done.
The error message suggests there might be an issue with the AuthenticationStateProvider being used. Make sure you are using the correct provider for Blazor WebAssembly. It should be RemoteAuthenticationStateProvider. builder.Services.AddScoped<AuthenticationStateProvider, RemoteAuthenticationStateProvider>();
If you are programming in C only, what i can recommend is [nuklear][1], it is a free open source GUI library that is surprisingly flexible to use and you can even create your own custom widgets. Initializing the library context/loading a single font & baking it into a texture: #include <nuklear.h> /* size of the font */ #define GUI_FONT_SIZE 16 /* ... */ struct nk_context gui_context = {0}; struct nk_font_atlas gui_font_atlas = {0}; struct nk_font *gui_font = NULL; struct nk_draw_null_texture gui_null_texture = {0}; GLuint gui_font_texture_id = 0; /* ... */ int initialize_gui(void) { struct nk_font_config cfg = {0}; const void *pixels = NULL; GLint texwidth = 0; int w = 0; int h = 0; /* initialize the font baker */ nk_font_atlas_init_default(&gui_font_atlas); nk_font_atlas_begin(&gui_font_atlas); /* set font baker's parameters */ memset(&cfg, 0, sizeof(cfg)); cfg.size = (float)GUI_FONT_SIZE; cfg.merge_mode = nk_false; cfg.pixel_snap = nk_false; cfg.oversample_h = 4; cfg.oversample_v = 4; cfg.range = nk_font_default_glyph_ranges(); cfg.coord_type = NK_COORD_UV; /* add fonts to bake */ gui_font = nk_font_atlas_add_from_file(&gui_font_atlas, "font/DroidSans.ttf", (float)GUI_FONT_SIZE, &cfg); if (!gui_font) { /* error handling */ } /* bake all the fonts into a single image */ pixels = nk_font_atlas_bake(&gui_font_atlas, &w, &h, NK_FONT_ATLAS_RGBA32); if (!pixels) { /* error handling */ } /* create a texture from the baked image and upload it to OpenGL */ glGenTextures(1, &gui_font_texture_id); glBindTexture(GL_TEXTURE_2D, gui_font_texture_id); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, w, h, 0, GL_RGBA, GL_UNSIGNED_BYTE, pixels); /* set texture filtering */ glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); /* clamp texture S,T coordinates in a range of 0.0~1.0 */ glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); /* release temporary memory used by the font baker */ nk_font_atlas_end(&gui_font_atlas, nk_handle_id(gui_font_texture_id), &gui_null_texture); nk_font_atlas_cleanup(&gui_font_atlas); /* initialize nuklear context */ if (!nk_init_default(&gui_context, &gui_font->handle)) { /* error handling */ } /* set default GUI theme */ nk_style_default(&gui_context); /* set GUI font */ nk_style_set_font(&gui_context, &gui_font->handle); /* ... */ return 1; } Now, once we have a valid nuklear context and have created a font atlas texture, we can create windows/buttons/custom widgets etc.. /* creates a window containing a button */ if (nk_begin(ctx, "Window title", nk_rect( 0, 0, 300, 300), NK_WINDOW_TITLE | NK_WINDOW_BORDER | NK_WINDOW_MOVABLE | NK_WINDOW_MINIMIZABLE | NK_WINDOW_CLOSABLE | NK_WINDOW_NO_SCROLLBAR)) { nk_layout_row_static(&gui_context, 24, 100, 1); if (nk_button_label(&gui_context, "Button")) { /* do stuff on click */ } } nk_end(&gui_context); After that is done you will need the library to convert your widget commands into draw commands (using a call to nk_convert()) that will be used to actually draw all the stuff. /* the maximum number of vertices allocated for use */ #define GUI_MAX_NUM_VERTICES 6000 /* the maximum number of indices allocated for use */ #define GUI_MAX_NUM_INDICES 6000 struct gui_vertex { struct vec2 position; /* vertex position */ struct vec2 texcoord; /* vertex texture coordinate */ struct color color; /* vertex RGBA color */ }; /* ... */ struct nk_buffer vbuf = {0}; struct nk_buffer ibuf = {0}; struct nk_buffer cbuf = {0}; struct nk_convert_config cfg = {0}; struct gui_vertex *vertices = NULL; unsigned short *indices = NULL; /* map your OpenGL vertex/index buffers to @vertices/@indices here */ /* initialize nuklear's vertex/index buffers for conversion */ nk_buffer_init_fixed(&vbuf, vertices, sizeof(*vertices) * GUI_MAX_NUM_VERTICES); nk_buffer_init_fixed(&ibuf, indices, sizeof(*indices) * GUI_MAX_NUM_INDICES); nk_buffer_init_default(&cbuf); /* initialize parameters for @nk_convert() */ memset(&cfg, 0, sizeof(cfg)); cfg.vertex_layout = layout; cfg.vertex_size = sizeof(struct gui_vertex); cfg.vertex_alignment = NK_ALIGNOF(struct gui_vertex); cfg.null = gui_null_texture; cfg.circle_segment_count = 22; cfg.curve_segment_count = 22; cfg.arc_segment_count = 22; cfg.global_alpha = 1.0f; cfg.shape_AA = NK_ANTI_ALIASING_ON; cfg.line_AA = NK_ANTI_ALIASING_ON; nk_convert(&gui_context, &cbuf, &vbuf, &ibuf, &cfg); /* unmap your OpenGL vertex/index buffers here */ Then how you will interpret these draw commands is up to you, you could draw them using immediate mode or use buffer orphaning maybe? if you are using modern OpenGL. Anyway, the syntax is the same you basically loop through every draw command and interpret it: const nk_draw_index *offset = NULL; /* ... */ nk_draw_foreach(cmd, &gui_context, &cbuf) { /* if the current command doesn't draw anything, skip it */ if (cmd->elem_count == 0) continue; /* bind each command's texture */ glBindTexture(GL_TEXTURE_2D, (GLuint)cmd->texture.id); /* set each command's scissor rectangle */ glScissor((GLint)cmd->clip_rect.x, (GLint)window_client_h - (GLint)(cmd->clip_rect.y + cmd->clip_rect.h), (GLint)cmd->clip_rect.w, (GLint)cmd->clip_rect.h); /* draw each command */ glDrawElements(GL_TRIANGLES, (GLsizei)cmd->elem_count, GL_UNSIGNED_SHORT, offset); offset += cmd->elem_count; } /* reset and prepare the context for the next frame */ nk_clear(&gui_context); /* free commands buffer */ nk_buffer_free(&cbuf); Also to render the GUI you can use this vertex shader: in vec2 position; in vec2 texcoord; in vec4 color; uniform mat4 transform; // orthographic projection matrix out vec2 frag_texcoord; out vec4 frag_colorRGBA; void main(void) { frag_texcoord = texcoord; frag_colorRGBA = color; gl_Position = transform * vec4(position, 0.0, 1.0); } And this fragment shader: precision highp float; uniform sampler2D gui_texture; in vec2 frag_texcoord; in vec4 frag_colorRGBA; out vec4 frag_color; // output fragment color void main(void) { frag_color = frag_colorRGBA * texture(gui_texture, frag_texcoord); } [1]: https://github.com/vurtun/nuklear
Can someone explain me why i get error " INSERT statement conflicted with the FOREIGN KEY constraint "FK_ArticleTag_Tags_ArticleId". The conflict occurred in database "Blog", table "dbo.Tags", column 'TagId'". ``` public class Article { public Article() { Comments = new HashSet<Comment>(); Tags = new HashSet<Tag>(); } [Key] public int ArticleId { get; set; } public int? CategoryId { get; set; } [StringLength(30)] public string ArticleName { get; set; } = null!; public string? ArticleDescription { get; set; } public bool Visibility { get; set; } [ForeignKey("CategoryId")] [InverseProperty("Articles")] public virtual Category Category { get; set; } [InverseProperty("Article")] public virtual ICollection<Comment> Comments { get; set; } [ForeignKey("TagId")] [InverseProperty("Articles")] public virtual ICollection<Tag> Tags { get; set; } } public class Tag { public Tag() { Articles = new HashSet<Article>(); } [Key] public int TagId { get; set; } [Required] [StringLength(50)] public string Title { get; set; } [ForeignKey("ArticleId")] [InverseProperty("Tags")] public virtual ICollection<Article>? Articles { get; set; } } ``` After migration, with 50 articles and 20 tags, I cannot add a new row to (autogenerated) ArticleTag table where ArticleId is greater than 20. I have no idea what this is about, can someone explain to me what I'm doing wrong?
In the following code, no matter where I attach the second `.actionSheet` I cannot make them work. My understanding was that as long as they were attached to different views, it would work but that theory doesn't seem to be true. struct ContentView: View { @State private var showFirstActionSheet = false @State private var showSecondActionSheet = false var body: some View { VStack{ VStack{ Button("Show Fist Action Sheet"){ showFirstActionSheet = true } .actionSheet(isPresented: $showFirstActionSheet) { ActionSheet(title: Text("First Action Sheet"), message: Text("Some message!"), buttons: [ .destructive(Text("Cancel")){ }, .default(Text("Yes")){ doSomething() }, .cancel() ]) } } } .actionSheet(isPresented: $showSecondActionSheet) { ActionSheet(title: Text("Second Action Sheet"), message: Text("Some message!"), buttons: [ .destructive(Text("Cancel")){ }, .default(Text("Yes")){ }, .cancel() ]) } } func doSomething(){ showSecondActionSheet = true } } I tried it with two different buttons and it worked but in my case, I only have one button that triggers the first one and the second one is triggered by the first actionSheet. Any idea what would be the best way to handle this?
null
The easiest change is to simply listen for the `input` (or `change` if you prefer) event, and then toggle a class on the `<body>` element based on the checked/unchecked state of the `<input>` as below, with explanatory comments in the code: <!-- begin snippet: js hide: false console: true babel: false --> <!-- language: lang-js --> // here we use document.querySelector() to get the first element on the page that // matches the supplied CSS selector; note that if you have multiple matching // elements you'll need to use document.querySelectorAll(), and then use a loop of // some kind to bind an event to each element (also this should also have been stated // in your question): document.querySelector('.toggle__check') // we then use EventTarget.addEventListener() to bind the anonymous Arrow function // as the event-handler of the 'input' event fired on the element: .addEventListener('input', // here we're using an Arrow function, as we have no requirement to use "this", // and we pass in a reference to the Event Object (here called "evt", but that's // a user-defined name, you can call it what you prefer) passed from the // EventTarget.addEventListener() method: // within the function body: // we find the <body> element (via document.body): (evt) => document.body // we utilise the Element.classList API: .classList // calling the toggle() method, and supply a class-name to add, or remove, // if the evaluation is true (or truthy) the class-name is added, and if // false (or falsey) it's removed. // within the assessment we retrieve the Event.currentTarget property-value // which returns the element to which the function was bound (the <input>) // and the 'checked' property of that Element returns a Boolean value, // true if it's checked and false if it's not checked: .toggle('alt-color', true === evt.currentTarget.checked)); <!-- language: lang-css --> :root { /*========== Colors ==========*/ /*Color mode HSL(hue, saturation, lightness)*/ --line-color: hsl(234deg 12% 35%); --active-color: hsl(234deg 100% 98%); --inactive-color: hsl(234deg 20% 68%); --body-color: hsl(189deg 49% 87%); --background-colour: hsl(189deg 84% 14%); } * { box-sizing: border-box; } body { height: 100vh; margin: 0; display: grid; place-items: center; background-color: var(--body-color); /* here we add a transition, in order that the background-color transitions between different colour-values: */ transition: background-color 300ms linear; } /* here we specify a different background-color for the <body> element if it has the class-name of 'alt-color': */ body.alt-color { /* as an aside, I strongly suggest that you use the same spelling of "colour" throughout your CSS; it's up to you how you spell it (color, colour, or even kolour) would all be perfectly valid but switching between spellings (above you have '--body-color' and here you have '--background-colour') increases the likelihood of unexpected errors/failures: */ background-color: var(--background-colour); } .toggle__content { display: grid; row-gap: 1.5rem; } .toggle__label { cursor: pointer; padding-block: .5rem; } .toggle__check { display: none; } .toggle__rail { position: relative; width: 52px; height: 4px; background-color: var(--line-color); border-radius: 2rem; } .toggle__circle { display: block; width: 24px; height: 24px; background-color: var(--body-color); box-shadow: inset 0 0 0 4px var(--inactive-color); border-radius: 50%; position: absolute; left: 0; top: 0; bottom: 0; margin: auto 0; transition: transform .4s, box-shadow .4s; z-index: 2; } .toggle__border { position: absolute; width: 32px; height: 32px; background-color: var(--body-color); border-radius: 50%; left: -4px; top: 0; bottom: 0; margin: auto 0; transition: transform .4s; } /* Toggle animation effects */ .toggle__check:checked~.toggle__rail .toggle__circle { transform: translateX(28px); box-shadow: inset 0 0 0 12px var(--active-color); } .toggle__check:checked~.toggle__rail .toggle__border { transform: translateX(28px); } <!-- language: lang-html --> <div class="toggle__content"> <label class="toggle__label"> <input type="checkbox" class="toggle__check"> <div class="toggle__rail"> <span class="toggle__circle"></span> <span class="toggle__border"></span> </div> </label> </div> <!-- end snippet -->
In the following Java code, `PropertyChangeListener` is implemented in two ways: 1) using a class that implements `PropertyChangeListener` interface, and 2) using a method reference. According to the API, the `addPropertyChangeListener` method takes, as argument, an object of type `PropertyChangeListener`. The first approach (Commented line in main method in PointTest class) is implemented in this way. But in the second approach, just a method reference is passed to the `addPropertyChangeListener` method (i.e. `handlePropertyChange`). Surprisingly, the method is void! So, my questions are "How does the second approach work? and why does the code compile in the first place?!" class Point { private int x, y; private PropertyChangeSupport pcs; public Point(int x, int y) { this.x = x; this.y = y; pcs = new PropertyChangeSupport(this); } public void addPropertyChangeListener(PropertyChangeListener listener) { pcs.addPropertyChangeListener(listener); } public void removePropertyChangeListener(PropertyChangeListener listener) { pcs.removePropertyChangeListener(listener); } public int getX() { return x; } public int getY() { return y; } public void setX(int x) { int oldX = this.x; this.x = x; pcs.firePropertyChange("x", oldX, x); } public void setY(int y) { this.y = y; } @Override public String toString() { return "(" + x + ", " + y + ")"; } } class PointTest { public static void main(String[] args) { Point p = new Point(1, 2); // p.addPropertyChangeListener(new myPropertyChangeListener()); // <--- first approach p.addPropertyChangeListener(PointTest::handlePropertyChange); // <--- second approach p.setX(10); p.setX(20); } public static void handlePropertyChange(PropertyChangeEvent e) { String propertyName = e.getPropertyName(); if("x".equals(propertyName)) { System.out.println("x has changed:"); System.out.println("\t old: " + e.getOldValue()); System.out.println("\t new: " + e.getNewValue()); } } } class myPropertyChangeListener implements PropertyChangeListener { @Override public void propertyChange(PropertyChangeEvent e) { String propertyName = e.getPropertyName(); if("x".equals(propertyName)) { System.out.println("x has changed:"); System.out.println("\t old: " + e.getOldValue()); System.out.println("\t new: " + e.getNewValue()); } } }
To access your data, you simply need to access the `0` (string, not number) key of the returned object, so you *could* just do: ``` this.job = job['0']; ``` However, since you always want your service to return the `Job` and not the full object, you should transform your response: ``` // service getJob(id: string) { const url = `${environment.apiUrl}/jobs.json?orderBy="job_id"&equalTo="${id}"`; return this.http.get<Record<string, Job>>(url).pipe( map(response => response['0']) ); } ``` --- I notice you have nested subscribes, which are not desirable, because without a reference to the subscription object, you have no way to unsubscribe. This means that when you leave your component, the subscription is still active, possibly running your logic after the component has been destroyed. There are a few ways to deal with this, but I'll mention what I find to be the simpliest code. The idea is to define an observable that emits exactly the data your view needs, in this case, the `Job`. Then, instead of explicitly subscribing in the component's controller, we can leverage the `async` pipe in the template which will subscribe to the observable and also unsubscribe when the component is destroyed. Here's an example: ```typescript export class JobDetailComponent { job$: Observable<Job> = this.activeRoute.params.pipe( switchMap(params => this.apiService.getJob(params.id)) ); constructor( private apiService: ApiService, private activeRoute: ActivatedRoute ) { } } ``` You'll notice in the above code we simply declare the `job$` observable. We start with the "active route params observable" and pipe it to the "get job observable". If you're not familiar with `switchMap`, it simply takes the incoming value and maps it to an observable (*in this case the call to `apiService.getJob()`*). The emissions from this "inner observable" are then emitted. Now that we have an `Observble<Job>`, we can simply use the async pipe in the template: ```html <div *ngIf="job$ | async as job"> {{ job.name }} ({{ job.id }}) </div> ```
I am new to React native i have a problem withe the expo DocumentPicker for some reason the DocumentPicker does not select any file, and it always shows that Selected Document: None ``` import React, { useState } from "react"; import { Button, StyleSheet, Text, View } from "react-native"; import * as DocumentPicker from "expo-document-picker"; export default function App() { const [document, setDocument] = useState(null); const pickDocument = async () => { const result = await DocumentPicker.getDocumentAsync({ type: 'application/pdf' }); if (result.type === "success") { setDocument(result); } }; return ( <View style={styles.container}> <Text style={styles.paragraph}> Selected Document: {document ? document.name : "None"} </Text> <Button title="Pick a file" onPress={pickDocument} /> </View> ); } const styles = StyleSheet.create({ container: { flex: 1, alignItems: "center", justifyContent: "center", padding: 20, }, paragraph: { marginTop: 24, fontSize: 18, fontWeight: "bold", textAlign: "center", }, }); ```
expo DocumentPicker is not selecting any document
|javascript|reactjs|react-native|expo|
remove particle animation on javascript
|javascript|wordpress|
> However, I'm wondering about the safest approach to utilize it for local testing without compromising security. Cryptography is an API that doesn't have any side effects. It operates on the key and data you provide, and for most functions the key and data isn't even altered. For instance, for a cipher, you put in a key, IV and plaintext and it outputs ciphertext. > However, I want to ensure that my use of Crypto.subtle doesn't introduce any potential security risks, especially when deploying the application to production environments. What kind of security risk are you afraid of? There is no such thing as generic security. Sometimes the CIA triangle consisting of confidentiality, integrity and availability is used to have a raw split down. But since CIA doesn't even cover the entire security spectrum (access control for critical functionality is where exactly?) I would not use that. All in all, either you need to know which assets you are protecting, which adversaries are expected, do a risk analysis (etc.) or you need to follow standard security practices like OWASP and try to protect against a spectrum. If you're not a security expert that later direction should probably be preferred. > Could anyone recommend a best practice or method for safely using Crypto.subtle in local testing environments while ensuring security remains intact when the application is deployed to production? Any insights, tips, or examples would be greatly appreciated. SubtleCrypto is a low level cryptographic library. That means it can be used to implement any protocol. For that you first need to create a protocol specification, even if it is just application specific. That way you have a central specification that can be evaluated. Cryptographic protocols are not as hard as creating your own cipher, but it is still extremely easy to shoot yourself in the foot if you don't know what you are doing. So you first eval the protocol and then the implementation of it. The main issue with SubtleCrypto is that it doesn't contain clear indications on how to perform **key management**. Key management is very important in any cryptographic protocol. Unfortunately SubtleCrypto does not - to my knowledge - give any access to e.g. a central key store containing trusted public keys or certificates. Fortunately TLS is commonly used nowadays, which means that at least the server is generally authenticated and the data is send over a secured connection. So the code using SubtleCrypto only needs to provide additional security on top of TLS. Unfortunately JavaScript is generally not able to get much information about the TLS connection nor of the certificate / private key used by the server to authenticate to the browser. Anyway, if you want to have any focus on security then key management should be a major concern. Personally I would not overly rely on SubtleCrypto or indeed JavaScript for my security solution. It should be secure regardless of the code running in the browser. If the browser is compromised then the user is likely in trouble regardless of any SubtleCrypto code running.
I am running locally a react app that i expose to the network with the the `--host` flag and a C# API, i added to the cors policy the ip address and port number that the app is exposed on. from my desktop all works fine, but when i attempt to access the site through my mobile phone thats connected to the same network the frontend loads correctly but when trying to make a POST request to login i get an error ``` XMLHttpRequest cannot load https://localhost:5000/someurl due to access control checks ``` and this error ``` POST https://localhost:5000/someurl Could not connect to the localhost:5000/someurl server. ``` here's my cors from the API ``` app.UseCors(policy => policy .WithOrigins("http://localhost:5173", "http://192.168.1.160:5173") .AllowAnyHeader() .AllowAnyMethod() .AllowCredentials()); ``` Any suggestions what am i missing here? NOTE: the order of the my middleware is UseCors, UseAuthentication, UseAuthorization
null
The `std::less` compare functor as used in [this answer](https://stackoverflow.com/a/71246646/1614903) does not yield the expected result. The reason is that it uses the **content** of the reference of type `MyType` instead of the **reference to the variable** of type `MyType` as index into the set. Try this: ````c++ template<typename T> void printReferenceContainer(T &container) { std::cout << "content of container:" << std::endl; for (auto item: container) { std::cout << "item: " << item.get() << std::endl; } std::cout << "done" << std::endl; std::cout << std::endl; } int main() { std::set<std::reference_wrapper<std::string>, std::less<std::string>> container; std::string a = "val 1"; std::string b = "val 2"; std::string c = "val 2"; // same value as b std::string d = "val 4"; container.emplace(a); container.emplace(b); container.emplace(c); container.emplace(d); printReferenceContainer(container); a = "val 10"; b = "val 11"; c = "val 12"; d = "val 13"; printReferenceContainer(container); return 0; } ```` While one expects 4 values in the set, because the references to 4 different variables have been added, there are only 3, because the value of variable `b` and `c` is the same, leading to `c` not being added, because its value is already contained in the set: ````text content of container: item: val 1 item: val 2 item: val 4 done content of container: item: val 10 item: val 11 item: val 13 done ```` The `std::less` functor in fact does not take the **reference** for comparison, but its **content**, by using the implicit *type cast operator* to `MyType`, in this case `std::string`. To solve this a closer look to what `std::reference_wrapper` really does is necessary. References do not really exist in a way that they occupy memory. In a very simplified way, they are just compiler aliases for the variable they are assigned with. See https://isocpp.org/wiki/faq/references for a more detailed explanation. The `std::reference_wrapper` mimics this behavior by holding an internal pointer to the variable it references. It supplies all the necessary member functions like an implicit constructor, assignment operator, type cast operator, etc. to *act* like a normal compiler generated reference. But it is in fact **just a struct** that holds a pointer. Being this it can be stored in a standard container, other than a real reference. The downside is that it does not have comparison operators, like *less than*, that compares the reference itself. As the `std::set` stores only unique values, whose uniqueness and order it determines by using the *less than* operator, it cannot naively store a `std::reference_wrapper`. It needs help, by providing a comparison functor. When using `std::less<std::string>`, the `std::reference_wrapper` now does exactly what it is expected to do. It *acts* like a real reference to its originally assigned variable and therefore the `std::less` functor compares the **content** of the reference, as stated above, leading to the undesired behavior. The solution is to provide a custom comparison functor that compares the `std::reference_wrapper` class instance itself, not its content. It can do so, by comparing the internal pointer of the `std::reference_wrapper` struct. As the internal pointer very likely is a private member, its value can be derived only by using the `get()` member, which returns a reference to the contained value and then taking its address. This in terms is of course the address of the originally assigned variable: ````c++ std::string myVar = "Hello World"; std::reference_wrapper<std::string> wrappedRef = myVar; std::string * pWrappedRefContent = &wrappedRef.get(); std::string * pMyVar = &myVar; std::cout << "&wrappedRef.get(): " << pWrappedRefContent << std::endl; std::cout << "&myVar : " << pMyVar << std::endl; std::cout << "&wrappedRef.get() and &myVar are " << (pWrappedRefContent==pMyVar? "equal" : "not equal") << std::endl; ```` Yields: ````text &wrappedRef.get(): 0x7fffffffe2e0 &myVar : 0x7fffffffe2e0 &wrappedRef.get() and &myVar are equal ```` With this knowledge a `ref_less` comparison functor can be defined like this: ````c++ template<typename T> struct ref_less { // use the 'take address' operator of the reference_wrappers get() for comparison bool operator()(const T &x, const T &y) const { return &x.get() < &y.get(); } }; int main() { std::set<std::reference_wrapper<std::string>, ref_less<std::reference_wrapper<std::string>>> container; std::string a = "val 1"; std::string b = "val 2"; std::string c = "val 2"; // same value as b std::string d = "val 4"; container.emplace(a); container.emplace(b); container.emplace(c); container.emplace(d); printReferenceContainer(container); a = "val 10"; b = "val 11"; c = "val 12"; d = "val 13"; printReferenceContainer(container); return 0; } ```` As can be seen this time it holds all variables: ````text content of container: item: val 1 item: val 2 item: val 2 item: val 4 done content of container: item: val 10 item: val 11 item: val 12 item: val 13 done ```` There's still one drawback or better possibly unexpected behavior. As the `std::set` is ordered by the given functor, the sets sort order is determined by the **address** of the referenced variables rather than by their **content**. The sort order is therefore meaningless and possibly compiler dependent. Of course it would be meaningless anyway, as the content can change at any time and the set has no means of knowing it. If the variable `d` is defined first, with this compilers implementation it is ordered first: ````c++ std::string d = "val 4"; std::string a = "val 1"; std::string b = "val 2"; std::string c = "val 2"; // same value as b ```` The output is: ````text content of container: item: val 4 item: val 1 item: val 2 item: val 2 done content of container: item: val 13 item: val 10 item: val 11 item: val 12 done ```` So this sort of container may serve the very particular purpose, that it holds a bunch of references to variables and makes sure a variable cannot be added twice, but looses the sorting property of the set.
Windows 11 Visual Studio 2015 I would like to filter double values. [enter image description here][1] [enter image description here][2] [1]: https://i.stack.imgur.com/ZckkI.png [2]: https://i.stack.imgur.com/ICCrr.png I can filter Strings Dim srchStr As String = Me.TextBox1.text Dim strFilter As String = "MyCol1 LIKE '*" & srchStr.Replace("'", "''") & "*'" dv.RowFilter = strFilter I can filter Integers Dim srchStr As String = Me.TextBox1.Text Dim id As Integer If Integer.TryParse(srchStr, id) Then dv.RowFilter = "code = " & id Else MessageBox.Show("Error: ........") End If Dim strFilter As String = "code = " & id dv.RowFilter = strFilter but I can not filter a double value. I actually use this code to filter strings in my DataGridView Private Sub MyTabDataGridView_DoubleClick(ByVal sender As Object, ByVal e As System.EventArgs) Handles MyTabDataGridView.DoubleClick Try 'MyRow Dim row As Integer = MyTabDataGridView.CurrentRow.Index 'MyColumn Dim column As Integer = MyTabDataGridView.CurrentCell.ColumnIndex 'MyColumn and MyRow Dim ColumnRow As String = MyTabDataGridView(column, row).FormattedValue.ToString 'Header Text Dim HeaderText As String = MyTabDataGridView.Columns(column).HeaderText 'I exclude the errors If HeaderText = "id" Or HeaderText = "MyCol3" Or HeaderText = "MyCol4" Or HeaderText = "MyCol5" Then Exit Sub End If 'Ready to filter Dim strFilter As String = HeaderText & " Like '*" & ColomnRow.Replace("'", "''") & "*'" dv.RowFilter = strFilter Catch ex As Exception End Try Any suggestion will be highly appreciated.
Filtering a double value
|filtering|
I have character code: ``` extends CharacterBody3D @onready var camera_mount = $camera_mount @onready var animation_player = $visuals/mixamo_base/AnimationPlayer @onready var visuals = $visuals @onready var camera_3d = $camera_mount/Camera3D @export var is_current:bool = true @export var is_main = true @export var SPEED = 5.0 @export var JUMP_VELOCITY = 4.5 @export var SENSIVITY = 0.05 var walk_speed = 3.0 var run_speed = 5.0 var is_running = false var gravity = ProjectSettings.get_setting("physics/3d/default_gravity") func _ready() -> void: if is_main: Input.set_mouse_mode(Input.MOUSE_MODE_CAPTURED) func _input(event): if is_main: if event is InputEventMouseMotion: rotate_y(deg_to_rad(-event.relative.x*SENSIVITY)) visuals.rotate_y(deg_to_rad(event.relative.x*SENSIVITY)) camera_mount.rotate_x(deg_to_rad(-event.relative.y*SENSIVITY)) func _physics_process(delta): if is_main: camera_3d.current = is_current if not is_on_floor(): velocity.y -= gravity * delta if Input.is_action_pressed("run"): SPEED = run_speed is_running = true else: is_running = false SPEED = walk_speed if Input.is_action_just_pressed("ui_accept") and is_on_floor(): velocity.y = JUMP_VELOCITY if Input.is_action_just_pressed("ui_cancel"): Input.set_mouse_mode(Input.MOUSE_MODE_VISIBLE) var input_dir = Input.get_vector("move_left", "move_right", "move_forward", "move_back") var direction = (transform.basis * Vector3(input_dir.x, 0, input_dir.y)).normalized() if direction: if animation_player.current_animation != "walking" && is_running == false: animation_player.play("walking") if animation_player.current_animation != "running" && is_running: animation_player.play("running") visuals.look_at(position+direction) velocity.x = direction.x * SPEED velocity.z = direction.z * SPEED else: if animation_player.current_animation != "idle": animation_player.play("idle") velocity.x = move_toward(velocity.x, 0, SPEED) velocity.z = move_toward(velocity.z, 0, SPEED) camera_mount.rotation.x = clamp(camera_mount.rotation.x, deg_to_rad(-90), deg_to_rad(70) ) move_and_slide() ``` And the script responsible for changing the character in the game using a button: ``` extends Node3D @onready var player_1 = $"../Player1" @onready var player_2 = $"../Player2" func _physics_process(_delta): if Input.is_action_just_pressed("switch_player"): if player_1.is_main: player_1.is_main = false player_2.is_main = true player_2.is_current = true player_1.animation_player.play("idle") else: player_1.is_main = true player_2.is_main = false player_1.is_current = true player_2.animation_player.play("idle") ``` The problem is that if you change the player while the one you were playing for before is in the air, then he freezes in this position. How can I make it so that as soon as I change a player, the one I played for before falls to the ground, i.e. began to succumb to the laws of physics?
XmlHttpRequest cannot load due to access control, but access is configured?
|reactjs|asp.net-web-api|cors|
The new operator in C++ performs the following actions: 1. Allocates Memory: It allocates memory on the heap for a single object or an array of objects. The amount of memory allocated is enough to hold the object(s) of the specified type. 2. Initializes Object(s): After allocating memory, new initializes the object(s) by calling their constructor(s). For a single object, it calls the constructor directly. For an array of objects, it calls the constructor for each object in the array. 3. Returns a Pointer: It returns a pointer of the object's type that points to the first byte of the allocated memory where the object is stored. For an array, it returns a pointer to the first element of the array. Whether a pointer has been returned, but the constructor has not fully executed with out-of-order execution of CPU ``` class Singleton { private: static Singleton * pinstance_; static std::mutex mutex_; protected: Singleton() { // } ~Singleton() {} public: Singleton(Singleton &other) = delete; void operator=(const Singleton &) = delete; static Singleton *GetInstance(); }; Singleton* Singleton::pinstance_{nullptr}; std::mutex Singleton::mutex_; Singleton *Singleton::GetInstance() { if (pinstance_ == nullptr) { std::lock_guard<std::mutex> lock(mutex_); if (pinstance_ == nullptr) { pinstance_ = new Singleton(); } } return pinstance_; } ``` Thread A executes the new operator after getting the lock, and does not complete the constructor function, but the pointer has pointed to the requested memory. At this time, thread B comes in and finds that the pointer is not NULL in the first if judgment, and uses the pointer for subsequent processing Is the above situation possible in the case of multithreading ?
I am using useContext to get user information in the login page and display it in the home page it displays the information at first but when i refresh the home page the information get lost why please i am a beginner in react this is where i'm setting the context ```reactjs const { setContext } = useContext(Context); const handleSubmit = async (event) => { event.preventDefault(); const log_in = await fetch("http://localhost:4040/api/v1/account/log_in", { method: "POST", credentials: "include", headers: { "Content-Type": "application/json", }, body: JSON.stringify(formData), }); if (log_in.ok) { alert("ok"); log_in.json().then((data) => { setContext({ data }); console.log(data); }); navigate("/"); } if (!log_in.ok) { if (log_in.status >= 400) { log_in.json().then((data) => { console.log(data); setErrorLogin(data.message); }); } } }; ``` and this where am using it ```reactjs const { data } = useContext(Context); return ( <nav> <div className='nav'> <span className='logo'> <h2> <Link to='/'>Money Video</Link> </h2> </span> <span className='search'> <ul> <input type='text' name='search' id='search' placeholder='Search video ' autoCorrect='' /> <button> <svg xmlns='http://www.w3.org/2000/svg' color='#26a89df8' height='24' viewBox='0 -960 960 960' width='24'> <path d='M782.87-98.52 526.913-354.478q-29.435 21.739-68.152 34.608-38.718 12.87-83.283 12.87-114.087 0-193.544-79.457Q102.477-465.913 102.477-580q0-114.087 79.457-193.544 79.457-79.457 193.544-79.457 114.087 0 193.544 79.457Q648.479-694.087 648.479-580q0 45.13-12.87 83.283-12.869 38.152-34.608 67.021l256.522 257.087-74.653 74.088ZM375.478-413.002q69.913 0 118.456-48.543Q542.477-510.087 542.477-580q0-69.913-48.543-118.456-48.543-48.543-118.456-48.543-69.913 0-118.456 48.543Q208.479-649.913 208.479-580q0 69.913 48.543 118.456 48.543 48.543 118.456 48.543Z' /> </svg> </button> </ul> </span> <span className='profile'> <ul> <Link className='a' to='/about'> About </Link> <div name='profile'> {data.profile ? ( <img src={profile} alt='profile picture' /> ) : data.profile === "" ? ( <span>{data.name.charAt().toUpperCase()}</span> ) : ( <span>N/P</span> )} </div> </ul> </span> </div> <SearchBox className='searchBox' /> <ProfileUp className='profileUp' /> <hr /> </nav> ); ``` i have not added the import stat meant so the code should not be much
{"Voters":[{"Id":777985,"DisplayName":"Ray"},{"Id":14868997,"DisplayName":"Charlieface"},{"Id":1043380,"DisplayName":"gunr2171"}],"SiteSpecificCloseReasonIds":[13]}
The problem is that the command specifies `1,6`, which will match only the first 6 lines. You could write a `sed` script that does what you want, but not a one-liner. On the other hand, this is easy to do with `awk`, like this: awk '/.*please.*/ {n++} !/.*please.*/ || n > 3 {print}' There are actually two "lines" here. The first one just matches lines that contain the word "please" and counts them. The second prints lines that do not (`!`) contain the word, or all lines after it finds 3 matches.
New to coding and getting this error message: ``` > "Cannot convert value of type 'Tab.Type' to expected argument type 'Binding<Tab>'" ``` What can I change to fix this? Here's my code: ```swift enum Tab: String, CaseIterable{ case house case person case message case gearshape } struct ContentView: View { @Binding var selectedTab: Tab private var fillImage: String { selectedTab.rawValue + ".fill" } var body: some View { VStack { HStack { } .frame(width: nil, height: 60) .background(.thinMaterial) .cornerRadius(10) .padding() } } } ```
How to correct "cannot convert value" error?
|swift|swiftui|
null
I am new to coding and get this error message: > "Cannot convert value of type 'Tab.Type' to expected argument type 'Binding<Tab>'" What can I change to fix this? Here's my code: ```swift enum Tab: String, CaseIterable{ case house case person case message case gearshape } struct ContentView: View { @Binding var selectedTab: Tab private var fillImage: String { selectedTab.rawValue + ".fill" } var body: some View { VStack { HStack { } .frame(width: nil, height: 60) .background(.thinMaterial) .cornerRadius(10) .padding() } } } ```
How to correct error: "Cannot convert value of type 'MyType.Type' to expected argument type 'Binding<MyType>'"?
I'm trying to create a simple R Shiny app that takes the chromosome, start, and end positions of CpGs as inputs and outputs boxplots for each CpG within the range. It works fine on the subset of data but fails for the real data ("all_data_reduced.RDS") because of its big size (almost 3 GB). I'm also not sure if the code written in the following way is the best, because even if the app works, it may take a lot of time to load from the user's end. Could you please suggest the best way to make an app when the data is big? Please note that the users want it at the individual level. So, aggregating data to show only the means over the conditions (we have four conditions, two genders, and two types) isn't an option. Also, I tried using the following option: > options(rsconnect.max.bundle.size = 4000000000) ################################################################# library(shiny) library(dplyr) library(ggplot2) ################################################################# # Load data all_data_reduced <- readRDS("all_data_reduced.RDS") ################################################################# # UI ui <- fluidPage( titlePanel("Methylation Data Visualization for Cleft Lip and Palate (CP) Project"), sidebarLayout( sidebarPanel( selectInput("chromosome", "Chromosome:", choices = as.character(1:19)), numericInput("start_pos", "Start Position:", value = NULL), numericInput("end_pos", "End Position:", value = NULL) ), mainPanel( plotOutput("boxplots") ) ) ) ################################################################# # Server server <- function(input, output) { output$boxplots <- renderPlot({ # Filtering dataset based on user defined inputs filtered_data <- subset(all_data_reduced, chr == input$chromosome & pos >= input$start_pos & pos <= input$end_pos) # Plot boxplots with facet_wrap for each chr_pos and overlay points ggplot(filtered_data, aes(x = Condition, y = methy_pct)) + geom_boxplot() + geom_point(position = position_jitter(width = 0.2), color = "red", size = 2) + # Overlay points with jitter facet_wrap(~pos, scales = "free") + labs(title = "Methylation Percentage Boxplots", y = "Methylation %") + theme( plot.margin = margin(1, 1, 2, 1, "cm"), # Adjust plot margin to increase plot size axis.text.x = element_text(angle = 45, hjust = 1) # Angle x-axis labels ) + coord_cartesian(ylim = c(0, 1)) # Set y-axis limits within each facet }) } ################################################################# # Run the application shinyApp(ui = ui, server = server)
I have a weather app that refreshes asynchronously. While I've never seen it crash myself, I do see about a crash per day in Apple's reports, and not from a specific device. The app does have a good amount of users and it refreshes every few minutes, but I have no idea what kind of percentage send reports to Apple, so don't really know how rare the crash really is. I've tried a few things, like making sure I the Async Downloader class that creates the datatask does not get destroyed etc. There are 2 kinds of reported crashes, the most common is at this code: ```objc -(void)startDownload { NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:fileURL] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:12]; NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]]; if (!session || !request || ![session respondsToSelector:@selector(dataTaskWithRequest:completionHandler:)]) return; // Stack trace points to line below crashing self.dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {...} // ... } ``` The "defensive" `if` is a sanity check as the crash stack trace looks like this: [![Stack trace][1]][1] That `self.dataTask` is just `@property NSURLSessionDataTask *dataTask;`. Any ideas on what to look into or try in order to avoid this? I seems quite rare overall so I am wondering if it's a case of the app is getting killed by the system or something like that which causes an unclean termination. Would welcome any suggestion though. [1]: https://i.stack.imgur.com/xdIew.png
I'm attempting to display a list of movies on a website using Jinja2 (a template engine for Python) and Bootstrap (a front-end framework). However, I'm having difficulty getting the movie cards to display correctly.When trying to display the movie cards using Jinja2 and Bootstrap, the cards aren't being displayed as expected. I'm facing difficulties in correctly displaying the background image of the card, as well as ensuring that the movie information is displayed clearly and organized. ``` <!--{% extends 'base.html' %} {% block conteudo %} <h2 style="text-align: center;">Teste de filmes</h2> <hr> <ul class="list-group"> {% for filme in filmes %} <li>{{filme.title}}</li> <p>{{ filme.overview }}</p> <p>Release Date: {{ filme.release_date }}</p> <p>Vote Average: {{ filme.vote_average }}</p> <p>Vote Count: {{ filme.vote_count }}</p> <hr> {% endfor %} </ul> {% endblock conteudo %}--> {% extends 'base.html' %} {% block conteudo %} <h2 style="text-align:center;">Lista de Filmes</h2> <hr> <div class="row"> {% for filme in filmes %} <div class="col-md-4"> <div class="card" style="width: 18rem;"> <img src="http://image.tmdb.org/t/p/w500{{filme.backdrop_path}}" class="card-img-top" alt="..."> <div class="card-body"> <h5 class="card-title">{{filme.title}}</h5> <p class="card-text">{{filme.overview}}</p> <hr> <h4>Nota média<span class="badge bg-secondary">{{filme.vote_average}}</span></h4> </div> </div> </div> {% if loop.index % 3 == 0 %} </div><div class="row"> {% endif %} {% endfor %} </div> {% endblock %} ``` Checking if the URL of the movie's background image is correct and accessible. Ensuring that all Bootstrap classes are being applied correctly. Verifying that the movies variable is being passed correctly to the template. Any help or suggestions would be greatly appreciated! Thank you!
If you don't use bootstrap components like me, you can use the **noninteractive** directive instead: <!-- language-all: html --> <div v-b-tooltip.noninteractive="{title: `I'm a tooltip`}">Hover me!</div> For futher reference: [tooltip directives][1] [1]: https://bootstrap-vue.org/docs/directives/tooltip
It seems that pydoc has a bug when It comes to files with DB models. I ended up using pdoc. pip isntall pdoc pdoc objects.py
> Will this impact the integrity of data? **No**. This exception was triggered in a `ReadStage` thread - This type of thread is responsible for local reads, which don't modify the dataset in any way. > And is there something I can do to avoid the error e.g. resize some param on Cassandra.yaml? **Yes**. I would start by finding the root cause and addressing it, rather than changing configuration. I can think of likely 2 scenarios where this exception would be triggered: 1. The client scanned through a **large partition** in a single query (exceeding ~128 MiB). To validate this you can verify what's the max partition uncompressed size by running the following: 1. Cassandra 4.1.X and above: `nodetool tablestats -s compacted_partition_maximum_bytes -t 1` 2. Previous versions: `nodetool tablestats | grep "Compacted partition maximum bytes" | awk '{print $5}' | sort -n | tail -1` If you see a partition over 128MiB, then it may be necessary to check if there is a query reading whole partitions in the correspondent table. And if there is one, rethink the data model in order to control partition size. One common solution to this problem is to bucket partitions by time or other arbitrary fields that can split the partitions in a balanced way. 2. A client is issuing a **range scan**. This includes read queries that read multiple partitions, such as queries that need `ALLOW FILTERING` and don't filter by partition key, and it's usually very expensive in Cassandra. Generally you'll be able to catch those in `debug.log` through **slow query logs**. If this is the case, I strongly recommend to consider [modeling a table for each of those queries][1] so that all reads are single-partition reads and the database performance scales well with the workload. ------------------ Finally, the quick configuration fix (in Cassandra 4.X) is to edit the following parameters in **cassandra.yaml** and restart nodes to apply changes: `internode_application_send_queue_reserve_endpoint_capacity_in_bytes` - defaults to 134217728 `internode_application_receive_queue_reserve_endpoint_capacity_in_bytes` - defaults to 134217728 Feel free to check the official documentation on internode messaging [here][2]. [1]: https://cassandra.apache.org/doc/stable/cassandra/data_modeling/data_modeling_rdbms.html#query-first-design [2]: https://cassandra.apache.org/doc/4.0/cassandra/new/messaging.html#resource-limits-on-queued-messages
I have an issue with the default month calendar control on Windows and Delphi 2007. By default, my dev environnemet is in French. I need to translate the texts into Flemish (`nl-BE`). No worries, I use the *“Localizer”* tool and it’s ok. On the other hand, with the [**TMonthCalendar** component][1], I have the character string *“aujourd'hui”* which is not displayed in Flemish; remaining in French as picture below : ![screen capture in nl-BE](https://i.stack.imgur.com/HzwUs.png) If you already noticed these behaviour, how did you fix the problem? [1]: https://docwiki.embarcadero.com/Libraries/Alexandria/en/Vcl.ComCtrls.TMonthCalendar
Flying chracter godot
|godot|gdscript|godot4|
null
Guys if you are using app folder structure in next 14 your api/auth/[...nextauth]/route.ts folder must be at same folder auth/signin page. and if you are using next 14 route grouping like (auth) carefull this folder leveling
i am currently facing an issue where i just hosted my react application on Netify(web hosting website) [enter image description here](https://i.stack.imgur.com/pQ6mc.png) the above pic show the code i used to route them, now when i refresh the page it show "Looks like you've followed a broken link or entered a URL that doesn't exist on this site." i am not sure why it showing this i deployed the application on github too but same thing happened there too please help.? i am expecting that route will start working properly and if i refresh the page it will reload the page at that route.
Route not working on refreshing the page in react deployed application
|reactjs|deployment|react-router|react-router-dom|
null
well in my case, i just avoid saving data to directly in state and add data inside an object instead. like before: const initialData = []; state.push(...); after: const initialData = { data: [] }; state.data.push(....);
`g++ test.c -o test.exe -lncursesw` this worked for me I installed ncurses using MSYS on windows 10 using ` pacman -S mingw-w64-x86_64-ncurses` command
{"Voters":[{"Id":207421,"DisplayName":"user207421"},{"Id":14732669,"DisplayName":"ray"},{"Id":466862,"DisplayName":"Mark Rotteveel"}]}
{"OriginalQuestionIds":[4086107],"Voters":[{"Id":266309,"DisplayName":"waldyrious"},{"Id":-1,"DisplayName":"Community","BindingReason":{"DuplicateApprovedByAsker":""}}]}
I use the inherited concept of the object. I am using the `TextEditingController`. 1. Assign this `TextEditingController` to the parent page. 2. Pass this controller into the child widget. 3. Put the child function into the `addListener` at the `initState`. 4. Using this controller in the parent function like `controller.text = '${controller.text}_'`. So, when this parent function works, the controller value will change and the child function will work.
So, i'm making site with spring boot, and i've decided to make base.html, that gets extended with other html files. ```<!DOCTYPE HTML> <html xmlns:th="http://www.thymeleaf.org"> <head> <!-- <title th:text="${title}"></title>--> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link href="../static/tailwind.css" rel="stylesheet"> <link rel="icon" type="image/x-icon" href="/siteimg/Sambona_logo_mini3.webp"> </head> <body class="relative"> <div class="flex flex-col min-h-screen"> <div th:insert="~{${#strings.concat(page_lang, '/parts/nav')}}"></div> <!--passing a page content, basically I use base.html as main page and extend that with page content that I need--> <div class="containter flex-1"> <div th:insert="~{${#strings.concat(page_lang, '/', page_content)}}"></div> </div> <div th:insert="~{${#strings.concat(page_lang, '/parts/footer')}}"></div> <div class="toast toast-top toast-end"> </div> </div> </body> </html> ``` Page that extends this base.html ``` <div th:fragment="page-content"> <div th:text="${page_text}" ></div> <!-- Make carousel--> </div> ``` If it's a starter page "sitename/RU", everything works right. If i get further in site like "sitename/RU/about", css path and image paths stop working So what i want is to know how to fix that or some info about how those paths work in Spring boot.
Rather than any of the above, I would use the [basic dispose pattern](https://learn.microsoft.com/en-us/dotnet/standard/design-guidelines/dispose-pattern#basic-dispose-pattern) to return some `IDisposable` that wraps the rented array and returns it when disposed. First define the following disposable wrapper: ``` public sealed class RentedArrayWrapper<T> : IList<T>, IDisposable { public T [] array; readonly ArrayPool<T>? pool; readonly int count; public static RentedArrayWrapper<T> Create(ArrayPool<T> pool, int count) => new RentedArrayWrapper<T>(pool.Rent(count), pool, count); RentedArrayWrapper(T [] array, ArrayPool<T>? pool,int count) { if (count < 0 || count > array.Length) throw new ArgumentException("count < 0 || count > array.Length"); this.array = array ?? throw new ArgumentNullException(nameof(array)); this.pool = pool; this.count = count; } public T [] Array => array ?? throw new ObjectDisposedException(GetType().Name); public Memory<T> Memory => Array.AsMemory().Slice(0, count); public T this[int index] { get { if (index < 0 || index >= count) throw new ArgumentOutOfRangeException(); return Array[index]; } set { if (index < 0 || index >= count) throw new ArgumentOutOfRangeException(); Array[index] = value; } } public IEnumerable<T> EnumerateAndDispose() { IEnumerable<T> EnumerateAndDisposeInner() { try { foreach (var item in this) yield return item; } finally { Dispose(); } } CheckDisposed(); return EnumerateAndDisposeInner(); } public IEnumerator<T> GetEnumerator() { IEnumerator<T> GetEnumeratorInner() { CheckDisposed(); for (int i = 0; i < count; i++) yield return this[i]; } CheckDisposed(); return GetEnumeratorInner(); } public int IndexOf(T item) => System.Array.IndexOf<T>(Array, item, 0, count); public bool Contains(T item) => IndexOf(item) >= 0; public void CopyTo(T[] array, int arrayIndex) => Memory.CopyTo(array.AsMemory().Slice(arrayIndex)); public int Count => count; void IList<T>.Insert(int index, T item) => throw new NotImplementedException(); void IList<T>.RemoveAt(int index) => throw new NotImplementedException(); void ICollection<T>.Add(T item) => throw new NotImplementedException(); void ICollection<T>.Clear() => throw new NotImplementedException(); bool ICollection<T>.Remove(T item) => throw new NotImplementedException(); bool ICollection<T>.IsReadOnly => true; // Indicates items cannot be added or removed IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } void CheckDisposed() { if (this.array == null) throw new ObjectDisposedException(GetType().Name); } void Dispose(bool disposing) { if (disposing) if (Interlocked.Exchange(ref this.array, null!) is {} array) pool?.Return(array); } } public static partial class ArrayPoolExtensions { public static RentedArrayWrapper<T> RentWrapper<T>(this ArrayPool<T> pool, int count) => RentedArrayWrapper<T>.Create(pool, count); } ``` And now you can write your parent and inner functions as follows: public IActionResult ParentFunction() { using var wrapper = InnerFunction(1000); // Take() uses deferred execution so we must materialize the rented array into a final non-disposable result so that // ObObjectResult.ExecuteResultAsync(ActionContext context) does not attempt to serialize the rented array after it has been returned. return Ok(wrapper.Take(1000).ToArray()); } public RentedArrayWrapper<int> InnerFunction(int count) { var wrapper = _defaultArrayPool.RentWrapper(count); // make operation on wrapper.Array return wrapper; } Mock-up fiddle #1 [here](https://dotnetfiddle.net/McczzY). That being said, there is a fundamental problem with all of your implementations: you return the rented array back to the array pool before your [`OkObjectResult`](https://learn.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.mvc.controllerbase.ok?view=aspnetcore-8.0#microsoft-aspnetcore-mvc-controllerbase-ok(system-object)) is actually executed and the value serialized to the response stream. Thus what you return may well be random if the same array pool memory is subsequently rented elsewhere in the interim. What are your options to work around this? A couple options come to mind. **Firstly**, you could consider returning some enumerable wrapper that disposes the `RentedArrayWrapper` after a single iteration, like so: public IActionResult ParentFunction() { var wrapper = InnerFunction(1000); return Ok(wrapper.EnumerateAndDispose()); } public RentedArrayWrapper<int> InnerFunction(int count) { var wrapper = _defaultArrayPool.RentWrapper(count); // make operation on wrapper.Array return wrapper; } While this works, it seems sketchy to me because my general feeling is that enumerators should not have [side-effects](https://stackoverflow.com/q/320396). Mock-up fiddle #2 [here](https://dotnetfiddle.net/McczzY). **Secondly**, you might consider subclassing [`OkObjectResult`](https://learn.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.mvc.okobjectresult) which is the type returned by [`ControllerBase.Ok(object)`](https://learn.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.mvc.controllerbase.ok) and making it dispose its value after being executed, like so: ``` public class OkDisposableResult : OkObjectResult { public OkDisposableResult(IDisposable disposable) : base(disposable) { } public override async Task ExecuteResultAsync(ActionContext context) { try { await base.ExecuteResultAsync(context); } finally { if (Value is IDisposable disposable) disposable.Dispose(); } } public override void ExecuteResult(ActionContext context) { // I'm not sure this is ever actually called try { base.ExecuteResult(context); } finally { if (Value is IDisposable disposable) disposable.Dispose(); } } } ``` And then returning your rented array wrapper like so: public IActionResult ParentFunction() { var wrapper = InnerFunction(1000); return new OkDisposableResult(wrapper); } public RentedArrayWrapper<int> InnerFunction(int count) { var wrapper = _defaultArrayPool.RentWrapper(count); // make operation on wrapper.Array return wrapper; } Mock-up fiddle #3 [here](https://dotnetfiddle.net/wDVT2r).
It appears that it's important to express that you want the 7 specific items extracted by calling for tokens=1-7. Token 1 will be %%G, with each successive, stipulated token using %%H, %%I, etc. Wanting to express one line for each token comes by echoing them 1 echo command at a time for each token's variable, either as one per line stacked or parenthetically grouped sequentially with &s: do (echo %%G) & (echo %%H) & (echo %%I)... etc In total, the following worked for me: `for /f "tokens=1-7" %G in ("1 2 7 16 21 26 688") do ( echo %G echo %H echo %I echo %J echo %K echo %L echo %M )`
i'm building the backend of an app in python and i wanted to use Django, the problem is, i installed pipenv with pip3 the first time and it run smoothly, now if i try to install with pip only it tells me: Requirement already satisfied: pipenv in c:\users\marco\appdata\roaming\python\python39\site-packages (2023.12.1) Requirement already satisfied: virtualenv>=20.24.2 in c:\python39\lib\site-packages (from pipenv) (20.25.1) Requirement already satisfied: certifi in c:\users\marco\appdata\roaming\python\python39\site-packages (from pipenv) (2024.2.2) Requirement already satisfied: setuptools>=67 in c:\users\marco\appdata\roaming\python\python39\site-packages (from pipenv) (69.2.0) Requirement already satisfied: platformdirs<5,>=3.9.1 in c:\python39\lib\site-packages (from virtualenv>=20.24.2->pipenv) (4.2.0) Requirement already satisfied: distlib<1,>=0.3.7 in c:\python39\lib\site-packages (from virtualenv>=20.24.2->pipenv) (0.3.8) Requirement already satisfied: filelock<4,>=3.12.2 in c:\python39\lib\site-packages (from virtualenv>=20.24.2->pipenv) (3.13.3) WARNING: You are using pip version 21.2.3; however, version 24.0 is available. You should consider upgrading via the 'C:\Python39\python.exe -m pip install --upgrade pip' command. but if i try to run pipenv --version powershell tells me: pipenv : Termine 'pipenv' non riconosciuto come nome di cmdlet, funzione, programma eseguibile o file script. Controllare l'ortografia del nome o verificare che il percorso sia incluso e corretto, quindi riprovare. In riga:1 car:1 + pipenv + ~~~~~~ + CategoryInfo : ObjectNotFound: (pipenv:String) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException (wich by the way is the "not recognized as the name of a cmdlet" error in italian), meaning that it seems unistalled. What should i do? I am new to python. I know this is probably a beginner error. Should i uninstall it? But how can i do it? If somebody can help me please thank you.
Can't install Pipenv on Windows
|python|django|powershell|pip|pipenv|
I trying to build account checker in python, when i run scripts to check the account is working or not like a u can sign in on website with that username and password or not. i getting always failed to login and when i try to put my real account in combo.json still cant login into website idk why i trying to my scripts can login into website with combo.json check the accont status if is working say u loggined or say login failed like that ``` import sys import requests import json def check_credentials(username, password): req = requests.session() param = {"username": username, "password": password} response = req.post("https://accounts.spotify.com/en/login", data=param) if response.status_code == 200 and "incorrect" not in response.text: return True else: return False def main(): try: with open("combo.json", "r") as file: combos = json.load(file) for combo in combos: username = combo["username"] password = combo["password"] if check_credentials(username, password): print(f"Login successful for: {username}:{password}") else: print(f"Login failed for: {username}:{password}") except FileNotFoundError: print("combo.json file not found.") if __name__ == "__main__": main() ``` ``` [ {"username": "user1", "password": "password1"}, {"username": "user2", "password": "password2"}, {"username": "ceyif30140@otemdi.com", "password": "deijvi123!"} ] ```
How to make an R Shiny app with big data?
|r|shiny|bigdata|