instruction
stringlengths
0
30k
I'm a basic developer working on a pet project and getting myself in knots on the best approach for displaying this in a React Native app via Flatlist. First off, this is the format of the JSON file. There are approx 7,000 of these records in the file and many are in a variety of different timezones. ``` name: "Meeting 1" timezone: "America/Los_Angeles" day: 2 time: "19:00" url: "https://teams.meetings.com/xyz321" ``` What I would like to do is; 1. Get the local timezone of the user and 2. filter all meetings occurring on the current day only and 3. filter these meetings that are happening within the next hour and 4. display these meeting details in the user's local date / time as individual items within a React Native Flatlist. I'd really appreciate if someone could offer some guidance. The DateTime functions are very difficult to get a handle on. ``` import React, { useEffect, useState } from 'react'; import { FlatList, StyleSheet, View, Text } from 'react-native'; import DeviceInfo from 'react-native-device-info'; // Assuming meetingsData is an array of objects parsed from the JSON file const meetingsData = require('../data/Meetings.json'); const MeetingList = () => { const [filteredMeetings, setFilteredMeetings] = useState([]); useEffect(() => { async function filterMeetings() { const userTimezone = DeviceInfo; // Get user's timezone const currentDate = new Date(); // Get current date/time const filtered = meetingsData.filter(meeting => { const meetingDate = new Date( `${meeting.day} ${meeting.time} ${meeting.timezone}` ); // Convert meeting time to user's timezone meetingDate.toLocaleString('en-US', { timeZone: userTimezone }); // Filter meetings occurring on the current day const isSameDay = meetingDate.getDate() === currentDate.getDate() && meetingDate.getMonth() === currentDate.getMonth() && meetingDate.getFullYear() === currentDate.getFullYear(); // Filter meetings happening within the next hour const isInNextHour = meetingDate.getTime() > currentDate.getTime() && meetingDate.getTime() <= currentDate.getTime() + 3600000; // 3600000 milliseconds = 1 hour console.log('x: ' + isSameDay); console.log('y: ' + isInNextHour); return isSameDay && isInNextHour; }); setFilteredMeetings(filtered); } filterMeetings(); }, []); const renderMeetingItem = ({ item }) => ( <View style={styles.item}> <Text style={styles.title}>Name: {item.name}</Text> <Text style={styles.title}>Time: {item.time}</Text> <Text style={styles.title}>URL: {item.url}</Text> </View> ); return ( <View style={styles.container}> <FlatList data={filteredMeetings} renderItem={renderMeetingItem} keyExtractor={(item, index) => index.toString()} /> </View> ); }; ```
Sub LastColumn() Dim LCol As Integer LCol = Range("C3").End(xlToRight).Column Columns(LCol).Select Columns(LCol).Copy Columns(LCol + 1).EntireColumn.Select Columns(LCol + 1).Insert Shift:=xlToRight End Sub
I could solve my problem with magical nutika python compilar tool. --windows-uac-admin parameter provides admin rights for app. Thanks Kay :)
In this example a SwiftUI view's identity depends on the value of its `@StateObject` member variable. I don't think this should be possible because if a view doesn’t have an explicit identity, it has a structural identity based on its type and position in the view hierarchy. In the example below the `ItemPopupView`'s identity depends on the value of its `itemsWrapper` member. Please help me to understand this and hopefully to change the view that its `itemsWrapper` member doesn't impact the view's identity. Please note that in this Minimal Reproducible Example the `itemsWrapper` `StateObject` isn't used, but the point of the MRE is to understand and address this identity issue. To reproduce: 1. Add a core data model named `TestApp` with an entity named `Item` that has 1 `Date` attribute named `updateTime`. 2. Run the app 3. Tap the row in the list 4. Tap the Edit button in the sheet that opens 5. Tap the Save button in the next sheet that opens 6. Observe that `ItemPopupView: @self changed.` **was** printed in the console 7. Comment out the `_itemsWrapper =` line in `ItemPopupView`'s `init()` 8. Rerun the app, tap the row, tap Edit, tap Save 9. Observe that `ItemPopupView: @self changed.` **wasn't** printed in the console Apologies this code is so long, I couldn't find a way to minimize it further: import SwiftUI import CoreData @main struct TestAppApp: App { @StateObject private var manager: DataManager = DataManager() var body: some Scene { WindowGroup { ItemListContentView() .environmentObject(manager) .environment(\.managedObjectContext, manager.container.viewContext) .onAppear() { let item = Item(context: manager.container.viewContext) item.updateTime = Date() try? manager.container.viewContext.save() } } } } struct ChildContextAndObject<Object: NSManagedObject>: Identifiable { let id = UUID() let childContext: NSManagedObjectContext var childObject: Object? init(withExistingObject object: Object?, in parentContext: NSManagedObjectContext ) { self.childContext = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType) childContext.parent = parentContext self.childObject = childContext.object(with: object!.objectID) as! Object } } class DataManager: NSObject, ObservableObject { private var containerImpl: NSPersistentContainer? = nil var container: NSPersistentContainer { if containerImpl == nil { containerImpl = NSPersistentContainer(name: "TestApp") containerImpl!.loadPersistentStores(completionHandler: { (storeDescription, error) in if let error = error as NSError? { fatalError("Unresolved error \(error), \(error.userInfo)") } }) containerImpl!.viewContext.automaticallyMergesChangesFromParent = true } return containerImpl! } } struct ItemPopupItem: Identifiable { let id = UUID() var item: Item? } struct ItemListContentView: View { @FetchRequest(sortDescriptors: []) private var items: FetchedResults<Item> @State var popupItem : ItemPopupItem? var body: some View { List { ForEach(items) { item in Text("\(item.updateTime!)") .onTapGesture { popupItem = ItemPopupItem(item: item) } } } .overlay( EmptyView() .sheet(item: $popupItem) { popupItem in ItemPopupView(popupItem: popupItem) } ) } } class ItemsWrapper : ObservableObject { public var items : [Item] = [] init() { } init(items: [Item]) { self.items = items } } struct ItemPopupView: View { @Environment(\.managedObjectContext) private var viewContext var popupItem : ItemPopupItem @StateObject var itemsWrapper = ItemsWrapper() @State public var updateOperation: ChildContextAndObject<Item>? init(popupItem : ItemPopupItem) { self.popupItem = popupItem _itemsWrapper = StateObject(wrappedValue: ItemsWrapper(items: [popupItem.item!])) // effects identity } var body: some View { let _ = Self._printChanges() VStack { Button("Edit") { updateOperation = ChildContextAndObject(withExistingObject: popupItem.item!, in: viewContext) } Text("\(popupItem.item!.updateTime!)") } .overlay( EmptyView() .sheet(item: $updateOperation) { updateOperation in EditItemView(item: updateOperation.childObject!) .environment(\.managedObjectContext, updateOperation.childContext) } ) } } struct EditItemView: View { @Environment(\.managedObjectContext) private var viewContext @Environment(\.dismiss) var dismiss @ObservedObject var item : Item var body: some View { Button("Save") { print("save") item.updateTime = Date() try? viewContext.save() try? viewContext.parent!.save() dismiss() } } }
using flex and minWidth make datGrid flicker on page loading. look like it is rendered multiple times
In my ASP.NET Core-6 Web API, I have these two fields FromDate and ToDate [Required] [MaxLength(8)] [MinLength(8)] public string FromDate { get; set; } [Required] [MaxLength(8)] [MinLength(8)] public string ToDate { get; set; } I want to display to the user in the Swagger Web API that the format for **FromDate** and **ToDate** should be like this yyyyMMdd e.g. 20220920 using Data Annotation How do I achieve this?
I'm trying to store 5000 data elements on an array. This 5000 elements are stored on an existinng file (therefore it's not empty). But I'm getting an error. Code def array(): name = 'puntos.df4' m = open(name, 'rb') v = []*5000 m.seek(-5000, io.SEEK_END) fp = m.tell() sz = os.path.getsize(name) while fp < sz: pt = pickle.load(m) v.append(pt) m.close() return v Output: ```none line 23, in array pt = pickle.load(m) _pickle.UnpicklingError: invalid load key, ''. ```
You can achive this using woocommerce_package_rates filter /** * Hide shipping rates when free shipping is available. * Change the Free Shipping label to 'Saved X' * * @param array $rates Array of rates found for the package. * @return array */ function my_hide_shipping_when_free_is_available( $rates ) { $free = array(); // here you set the saved amount $saved_amount = 10; foreach ( $rates as $rate_id => $rate ) { if ( 'free_shipping' === $rate->method_id ) { $free[ $rate_id ] = $rate; $free[ $rate_id ]->label = sprintf("Saved %d",strip_tags( wc_price( $saved_amount ) )); break; } } return ! empty( $free ) ? $free : $rates; } add_filter( 'woocommerce_package_rates', 'my_hide_shipping_when_free_is_available', 100 );
I was trying to add a p5.js sketch to my website, so as first try, I grabbed a sketch from Daniel Shiffman's 3D terrain generation with Perlin Noise video ([link 1][1], [link 2][2]) to my [Svelte](https://svelte.dev/) project, when I noticed that the sketch seemed to be running much slower than it was in the p5.js [web editor](https://editor.p5js.org/). To test my suspicions, I timed the execution of the draw call with `performance.now()`. Results in the p5.js web editor yielded an average execution time of `~10`ms. In my svelte project, execution time took about `80ms`. To confirm whether this was just a one-off problem, I threw together [a codepen](https://codepen.io/kemmel-dev/pen/LYvzXqp?editors=1111), and saw the execution times remained poor compared to the [web editor](https://editor.p5js.org/codingtrain/sketches/OPYPc4ueq). To clear any doubts that this was Svelte or Codepen related, I created a new directy, threw in a boilerplate `html` file and imported p5.min.js from the CDN, and finally linked the `sketch.js`: ```html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.9.2/p5.min.js"></script> </head> <body> <script src="./sketch.js"></script> </body> </html> ``` Then, I ran my project using (npm) `serve`, and observed that the execution times were still the same. It's not `frameRate` related, (that should only dictate how often the draw call is called, but I tried experimenting with setting different framerates anyway, and the time it took for the draw call to execute stayed consistent throughout). [This](https://editor.p5js.org/codingtrain/sketches/OPYPc4ueq) is the sketch I was experimenting with. My suspicion (although it is kind of a stab in the dark) is that it has to do with the `WebGL` mode used in that sketch (`createCanvas(600, 600, WEBGL);`), and that the web editor version is hardware accelerated, but my local project version is not. That's kind of a weird idea though, as to my understanding hardware acceleration should be enbaled browser-wide? If anyone could elaborate as to why there is such a massive discrepancy between performance, and how I can make the sketch on my website run as smooth as the web editor one, it'd be hugely appreciated. The contents of the particular `sketch.js` I was testing, originally written by Daniel Shiffman: ```js // Daniel Shiffman // http://codingtra.in // https://youtu.be/IKB1hWWedMk // https://thecodingtrain.com/CodingChallenges/011-perlinnoiseterrain.html // Edited by SacrificeProductions var cols, rows; var scl = 20; var w = 1400; var h = 1000; var flying = 0; var terrain = []; function setup() { createCanvas(600, 600, WEBGL); cols = w / scl; rows = h / scl; for (var x = 0; x < cols; x++) { terrain[x] = []; for (var y = 0; y < rows; y++) { terrain[x][y] = 0; //specify a default value for now } } } function draw() { flying -= 0.1; var yoff = flying; for (var y = 0; y < rows; y++) { var xoff = 0; for (var x = 0; x < cols; x++) { terrain[x][y] = map(noise(xoff, yoff), 0, 1, -100, 100); xoff += 0.2; } yoff += 0.2; } background(0); translate(0, 50); rotateX(PI / 3); fill(200, 200, 200, 150); translate(-w / 2, -h / 2); for (var y = 0; y < rows - 1; y++) { beginShape(TRIANGLE_STRIP); for (var x = 0; x < cols; x++) { vertex(x * scl, y * scl, terrain[x][y]); vertex(x * scl, (y + 1) * scl, terrain[x][y + 1]); } endShape(); } } ``` [1]: https://thecodingtrain.com/challenges/11-3d-terrain-generation-with-perlin-noise [2]: https://www.youtube.com/watch?v=IKB1hWWedMk
Your letters `M` and `N` give a problem in the `TEXT` function they are characters that need to be escaped to be used literally in that function. You can escape those characters by preceding them with a `\`, which escapes only the single character following that token, or by enclosing them within quotes. so `"\V\U\A\M0000"` or `"""VUAM""0000"` should work OK.   <br><br>If your serial numbers are sorted ascending as you show in your example, and they all start with the same four letters, you can use, in most versions of Excel: =LOOKUP(2,1/(A2=$A$2:$A$7),$B$2:$B$7) If you have `365`, you could use the more understandable: =CHOOSEROWS(SORT(FILTER($B$2:$B$7,$A$2:$A$7=A2),1,-1),1)
I'm working with a game called "Pixels". My goal is to programmatically monitor when trees respawn within the game. A developer provided me with Java code for this, and I've attempted to convert it to Python. I'm able to successfully retrieve my session ID, room ID, and other relevant server details.When I attempt to establish a WebSocket connection, I consistently receive a 502 error. I'm not sure what's causing this. public void openWebSocketAndProcessMessages(String server, String roomId, String sessionId) { ReactorNettyWebSocketClient client = new ReactorNettyWebSocketClient(); client.setMaxFramePayloadLength(2621440); URI uri = URI.create( String.format("wss://pixels-server.pixels.xyz/%s/%s?sessionId=%s", server, roomId, sessionId)); AtomicBoolean firstMessageReceived = new AtomicBoolean(false); // Capture the start time of the session Instant sessionStart = Instant.now(); client.execute(uri, session -> session.receive() .doOnNext(message -> { // Check if the first message has been received and send a confirmation message if (firstMessageReceived.compareAndSet(false, true)) { System.out.println("First message received, sending confirmation..."); byte[] confirmationBytes = {'\n'}; // Newline character as the confirmation message session.send( Mono.just(session.binaryMessage(factory -> factory.wrap(confirmationBytes)))) .subscribe(); } // Convert the received WebSocketMessage to a byte array (requires proper handling based on actual message type and content) ByteBuffer buffer = message.getPayload().asByteBuffer(); byte[] messageBytes = new byte[buffer.remaining()]; buffer.get(messageBytes); String encodedString = new String(Base64.getDecoder().decode(Base64.getEncoder().encodeToString(messageBytes))); ``` Websocket connection python code that I am getting 502 error: ''' async def connect_websocket(server, roomid, sessionid): uri = f"wss://pixels-server.pixels.xyz/{server}/{roomid}?sessionId={sessionid}" print(uri) headers = { "Host": "pixels-server.pixels.xyz", "Connection": "Upgrade", "Upgrade": "websocket", "Origin": "https://play.pixels.xyz", "Sec-WebSocket-Version": "13", "Sec-WebSocket-Key": "lAVNhobAP9AaShcdp/BegA==", "Sec-WebSocket-Extensions": "permessage-deflate; client_max_window_bits", "User-Agent": "Mozilla/5.0 (Linux; Android 10; K) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/123.0.0.0 Mobile Safari/537.36", "Pragma": "no-cache", "Cache-Control": "no-cache", "Accept-Encoding": "gzip, deflate, br, zstd", "Accept-Language": "en-GB,en-US;q=0.9,en;q=0.8", "Cookie": "intercom-id-grzhbhyr=e4b3442d-7fbd-4660-b003-9796901fb523; intercom-device-id-grzhbhyr=48118693-0661-4e43-b3b9-e140ae8a692d; _ga=GA1.1.523002009.1710326782; _ga_QGP383C71B=GS1.1.1711873973.8.1.1711874126.0.0.0" } async with websockets.connect(uri, extra_headers=headers) as websocket: while True: message = await websocket.recv() print(f"Received message: {message} ")''' I'm unsure if there are any specific authentication requirements for the WebSocket connection that I might be missing.
|c#|.net|sql-server|entity-framework-core|
It's because you've set 1000px width to the parent (.row) ```css .row {width: 1000px;} ``` Try to change this value to 100%. It allows the div to take up the full width of its container. ```css .row {width: 100%;} ``` Don't hesitate to inspect your project with the dev tools within your browser to see how DOM's elements behave with each other. To open your browser's inspector: <kbd>Ctrl</kbd>+<kbd>Shift</kbd>+<kbd>I</kbd> (Windows/Linux) or <kbd>⌘ Cmd</kbd>+<kbd>⌥ Option</kbd>+<kbd>I</kbd> (macOS)
null
I'm using PostgreSQL in my project. The primary key column in my table is a Character type with length of 36. I generate guids in backend and store them in the table. Do I need to change the column type as uuid? Can it have the save performance?
Is it the same to set id column as uuid or character with length of 36 in PostgreSQL?
|postgresql|
I have an html that has content over multiple pages that has to be printed. I have attached a sample below. <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Dynamically Generated HTML with Header for PDF</title> <style> /* Header styles for print */ @media print { .header { position: fixed; top: 0; left: 0; right: 0; height: 50px; /* Adjust height as needed */ color: white; text-align: center; line-height: 50px; /* Adjust line height as needed */ } } /* Content styles */ .content { margin-top: 60px; /* Ensure content starts below the header */ } </style> </head> <body> <div class="header">Header Content</div> <div class="content"> <!-- Your dynamically generated HTML content here --> <p>This is a sample dynamically generated content.</p> <!-- More content --> </div> </body> </html> This has a header at a fixed position. When the html is printed to pdf the content overlaps with the header from the 2nd page onwards. The margin-top css of the content is applied only for the first page. Even I tried setting @page css with a margin, in this case the fixed position header is also moved down by the margin. I tried with different css techniques but none of them worked. The main problem is css is getting applied only to the first printed page and not in the subsequent pages.
Printing HTML with fixed header and footer
|html|css|
I am working on a Vue.js application and facing an issue with events and event listeners among my components. I have a child component that emits an event 'refresh', but the parent component doesn't seem to capture this event. Here is the relevant code in my child component where the event is emitted. This is actually inside an asynchronous method where I delete an image: ``` const removeImage = (id: number) => { $dialog.confirm("delete", $translate.$t('generic.delete'), async () => { await $fetch._delete("files/remove_file/" + id); $emit('refresh'); $toast.success("The image has been deleted"); }); } ``` In my parent component, I have a listener for this event which calls a get() method: ``` <DialogCrudItem v-model:visible="displayCrudItem" :item="item" @refresh="get()" @finished:delete="displayCrudItem= false; get()" @finished:create="displayCrudItem= false; get()" @finished:update="displayCrudItem= false; get()"/> ``` The removeImage method works perfectly and the image is correctly deleted as I expected. However, the parent doesn't seem to capture the 'refresh' event and hence doesn't call the get function. It's worth mentioning that this parent component listens for the same 'refresh' event from several other components, and when these components emit the event, the get method is invoked correctly. But from this particular child component, the event is not captured. Additionally, if I emit an event called 'finished:create' or 'finished:delete' that are also used and listened for in this child component, the parent component captures them correctly and react as expected. I've also tried changing the name of the event from 'refresh' to something else, thinking there may be a naming conflict, but this didn't resolve the problem. Any help is appreciated to fix this issue.
Executing below code: ```python from selenium import webdriver from webdriver_manager.chrome import ChromeDriverManager browser = webdriver.Chrome browser.get('https://soysocio.bocajuniors.com.ar/index.php') ``` Error: ``` [line 7] TypeError: get() missing 1 required positional argument: 'url' ``` How can i solve it? Thank you
I want to import SimpleNodeParser from llama_index.node parser. from llama_index.node_parser import SimpleNodeParser But when I run this I'm getting an error: ModuleNotFoundError: No module named 'llama_index.node_parser' Help me to solve this. I want to import SimpleNodeParser from llama_index.node parser.
You can reduce your set of interfaces as `{ a: A; } | { a: A; b: B; }` is `{ a: A; b?: B; }`: interface ButtonOnlyText extends React.ButtonHTMLAttributes<HTMLButtonElement> { text: string; } interface ButtonOnlyIcon extends React.ButtonHTMLAttributes<HTMLButtonElement> { Icon: React.FunctionComponent<React.SVGProps<SVGSVGElement>>; iconProps?: React.SVGProps<SVGSVGElement>; } interface ButtonTextAndIcon extends React.ButtonHTMLAttributes<HTMLButtonElement> { text: string; Icon: React.FunctionComponent<React.SVGProps<SVGSVGElement>>; iconProps?: React.SVGProps<SVGSVGElement>; } Then you can't declare `Button` as function Button({ text, Icon, iconProps, ...buttonProps }: ButtonProps) Simply because there are interfaces in your disjunction that don't have the props you're trying to access. Typescript will tell you that these properties are not defined. All you can do is declare it as function Button(props: ButtonProps) And then have some code that'd work like this: const buttonProps = restrict(props).toAllBut(["text", "Icon", "iconProps"]); And query for the props you want to access like this: if ("text" in props && "Icon" in props) // ButtonTextAndIcon And handle all cases as you please. You might want to expose these components instead: declare function TextButton({ text, ...buttonAttributes }: ButtonOnlyText): React.FC; declare function IconButton({ Icon, iconProps, ...buttonAttributes }: ButtonOnlyIcon): React.FC; declare function TextIconButton({ text, Icon, iconProps, ...buttonAttributes }: ButtonTextAndIcon): React.FC; That all delegate to the main `Button`.
I found the answer. You can solve this using from llama_index.core.node_parser import SimpleNodeParser
We can specify the GOROOT in `settings.json` as below: [![enter image description here][1]][1] [1]: https://i.stack.imgur.com/ELblR.png
Angular's Ahead-of-Time (AOT) compilation process converts TypeScript, HTML, and CSS code into JavaScript during build time, the DOCTYPE declaration in HTML remains essential for defining the document type, ensuring standards compliance, improving browser compatibility, and facilitating error handling and validation.
The onclick event.target.value should return SELECT while opening a select Dropdown by mouse click and OPTION when click on an option. This is the correct behavior like Firefox do. Chrome gives back "SELECT" in both cases. In chrome it is impossible (or i found no way until now) to reset a list to the first option while opening the Dropdown. In both cases a a SELECT is fired and the list will always stay on first option. <!-- begin snippet: js hide: false console: true babel: false --> <!-- language: lang-js --> let myelement = document.getElementById("myid"); myelement.setAttribute("onclick","revertBack(this, event)"); myelement.setAttribute("onchange","mylementSelect(myelement)"); function revertBack(myelement, event){ console.log(myelement.nodeName + "-" + event.target.tagName); if (event.target.tagName == "SELECT") { myelement.selectedIndex = 0; myelement.style.color = 'gray'; myelement.style.backgroundColor = 'white'; } } function mylementSelect(myelement){ if (myelement.selectedIndex <= 0) { myelement.style.color = 'gray'; myelement.style.backgroundColor = 'white'; } else { myelement.style.color ='black'; myelement.style.backgroundColor = 'yellow'; } } <!-- language: lang-html --> <!-- try this in Chrome and Firefox and compare Log Result On firefox a selected option will be reset to the first option on chrome not --> <select id="myid"> <option value="1">Option 1</option> <option value="2">Option 2</option> <option value="3">Option 3</option> <option value="4">Option 4</option> <option value="5">Option 5</option> <option value="6">Option 6</option> <option value="7">Option 7</option> </select> <!-- end snippet -->
Troubleshooting WebSocket 502 Error in Python Code
|python|java|api|websocket|
null
This will works: ```html <div class="min-h-screen grid grid-rows-[48px,1fr,48px]"> <div class="bg-gray-400 h-12 header">Header</div> <div class="bg-gray-300 content">Content</div> <div class="bg-gray-400 footer">Footer</div> </div> ```
`ngx-countdown` expects `leftTime` to be a number representing seconds left. So to make it work you need to find a difference between `auctionEnd` which is a UTC string and the current Date and convert it into seconds. Here is how your component could do this: ```ts export class TimerComponent { config: CountdownConfig = { leftTime: 0, format: 'd:H:M:ss' }; // Turn this into a setter so it updates the config if input changes // make sure you use ChangeDetectionStrategy.OnPush to avoid redundant updates // or change this as you wish @Input() set childTimer(utcDate: string) { this.config = { ...this.config, leftTime: this.calculateSecondsLeft(utcDate) }; } private calculateSecondsLeft(utcDate: string): number { // Both `parse` and `now` return a timestamp const diff = Date.parse(utcDate) - Date.now(); return diff / 1000; } } ``` ---------- **Update** I digged into documentation of `ngx-countdown` and there is `stopTime` option in the config that makes it even simpler as it accepts "end time" as timestamp, so the example could be simplified to: ``` export class TimerComponent { config: CountdownConfig = { format: 'd:H:M:ss' }; @Input() set childTimer(utcDate: string) { this.config = { ...this.config, stopTime: Date.parse(utcDate) }; } } ``` ---------- Regarding `d` in a format showing 1 when `timeLeft` > 24h. It seems that the library uses formatting for Date, while the data is more like `Duration`. When a `diff` is calculated it is a date relative to `Jan 1 1970` and `d` is a "day of month" so it shows `1`. It is better explained [here][1]. As we cannot subtract 1 day from `Jan 1 1970` there is no easy fix for it that could handle leap days and other Date related edge cases. Here is an example of how you can add a custom formatter via `formatDate` configuration, and `intervalToDuration` from `date-fns` library: ``` config: CountdownConfig = { formatDate: ({ date }) => { const { days, hours, minutes, seconds } = intervalToDuration({ start: 0, end: date }); return `${days ?? 0}:${hours ?? 0}:${minutes ?? 0}:${seconds ?? 0}`; }, }; ``` [1]: https://github.com/cipchk/ngx-countdown/issues/49#issuecomment-547019133
Good evening, I am trying to parallelize a code that sums plus one to all the elements of a vector `M`, with a ThreadPool (the pool is standard and it is implemented in the book Parallel Programming Concepts Snd Practice). So I defined a function `sum_plus_one(x,M)` that takes as arguments `x`: the position of the vector, and the vector `M`. The code is the following: #include <iostream> #include <vector> #include <thread> #include <hpc_helpers.hpp> #include <threadPool.hpp> int main(int argc, char *argv[]) { // define a Thread Pool with 8 Workers ThreadPool TP(5); auto sum_plus_one = [](const uint64_t x, const std::vector<uint64_t> &M) { return M[x]+1; }; uint64_t N = 10; // dimension of the vector // allocate the vector std::vector<uint64_t> M(N); std::vector<std::future<uint64_t>> futures; // init function auto init=[&]() { for(uint64_t i = 0; i< N; ++i) { M[i] = 1; } }; init(); // enqueue the tasks in a linear fashion for (uint64_t x = 0; x < N; ++x) { futures.emplace_back(TP.enqueue(sum_plus_one, x, &M)); } // wait for the results for (auto& future : futures) std::cout << future.get() << std::endl; return 0; } But I get the following error ```none error: no matching member function for call to 'enqueue' futures.emplace_back(TP.enqueue(somma, x, &M)); candidate template ignored: substitution failure [with Func = (lambda at UTWavefrontTP.cpp:20:15) &, Args = <unsigned long long &, std::vector<unsigned long long> *>]: no type named 'type' in 'std::result_of<(lambda at UTWavefrontTP.cpp:20:15) &(unsigned long long &, std::vector<unsigned long long> *)>' auto enqueue(Func && func, Args && ... args) -> std::future<Rtrn> { ``` I am approaching this type of things as a beginner and I am a bit struggling finding the solution. Seems like the pointers are all okay, and that `enqueue` cannot find the function that sums to one all the elements.
{"Voters":[{"Id":1883316,"DisplayName":"Tim Roberts"}]}
**Promise resolution** The technical explanation is that pairs of `resolve`/`reject` functions are "one shots" in that once you call one of them, further calls to either function of the pair are ignored without error. If you resolve a promise with a promise or thenable object, Promise code internally creates a new, second pair of resolve/reject functions for the promise being resolved and adds a `then` clause to the resolving promise to resolve or reject the promise being resolved, according to the settled state of the resolving promise. Namely, in ```js const test = new Promise((resolve, reject) => { resolve(Promise.resolve(78)) }) ``` `resolve(Promise.resolve(78))` conceptually becomes Promise.resolve(78).then(resolve2,reject2) where `resolve2`/`reject2` are a new pair of resolve/reject functions created for the promise `test`. If and when executed, one of the `then` clause's handlers will be called by a Promise Reaction Job placed in the microtask queue. Jobs in the microtask queue are executed asynchonously to calling code, where `test` will remain pending at least until after the synchronous code returns. **Promise Rejection** Promise rejection is certain if a promise's `reject` function is called. Hence you can reject a promise with any JavaScript value, including a Promise object in any state. Namely in ```js const test2 = new Promise((resolve, reject) => { reject(Promise.resolve(78)) }) ``` the rejection can be performed synchronously, and the the rejection reason of `test2` is the _promise oject_ `Promise.resolve(78)`, not the number 78.
m encountering an alignment issue with checkboxes in a Vue.js application. I'm attempting to center the checkboxes within their respective table cells. By default, they appear left-aligned. Upon applying CSS styling to the cell, all the checkboxes unexpectedly align vertically to the center of the leftmost column of the table, rather than staying centered within their cells. How can I resolve this alignment discrepancy? ``` <tbody> <!-- Loop over roles --> <template v-for="(characters, role) in categorizedCharacters" :key="role"> <tr @click="toggleRoleVisibility(role)"> <td>{{ role }}</td> <!-- Placeholder cells for alignment with the header; hidden but keeps the structure --> <td v-for="event in state.events" :key="`role-${event.title}-${role}`"></td> </tr> <!-- Loop over characters within each role --> <template v-if="state.roleVisibility[role]" v-for="character in characters" :key="character.name"> <tr> <td>{{ character.name }}</td> <!-- Generate a cell for each event --> <td v-for="event in state.events" :key="`signup-${event.title}-${character.name}`" class="checkbox-cell"> <input type="checkbox" :checked="characterSignedUp(character, event)" /> </td> </tr> </template> </template> </tbody> ``` ``` .checkbox-cell { display: flex; justify-content: center; align-items: center; } ``` [![Before](https://i.stack.imgur.com/jhVrW.png)](https://i.stack.imgur.com/jhVrW.png) [![After](https://i.stack.imgur.com/JpttO.png)](https://i.stack.imgur.com/JpttO.png) Thanks for any help
Vue.js Checkbox Alignment Issue: Centering Checkboxes Within Table Cells
**What is this error?** As posted, the supplied code will raise a SyntaxError: as @Frodon's comment says, you would need to use """ (or ''') to have the string span multiple lines like that. For example, this code: s = "abc def" print(s) Causes the interpreter to report: > python test.py File "test_files/test.py", line 1 s = "abc ^ SyntaxError: EOL while scanning string literal The reported error from *vobject* means that the string you're actually trying to parse has no "END:VCARD" line. For example >>> import vobject >>> s = "BEGIN:VCARD\r\nVERSION:3.0\r\nUID:abcdef\r\nN:Smith;John;Quinlan;Dr;Jr\r\nFN:Dr John Quinlan Smith Jr\r\nEND:VCARD" >>> vcard = vobject.readOne(s) >>> vcard.prettyPrint() VCARD VERSION: 3.0 UID: abcdef N: Dr John Quinlan Smith Jr FN: Dr John Quinlan Smith Jr >>> but >>> import vobject >>> # Note: no END:VCARD in the card data! >>> s = "BEGIN:VCARD\r\nVERSION:3.0\r\nUID:abcdef\r\nN:Smith;John;Quinlan;Dr;Jr\r\nFN:Dr John Quinlan Smith Jr\r\n" >>> vcard = vobject.readOne(s) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/xxx/vobject/vobject/base.py", line 1155, in readOne return next(readComponents(stream, validate, transform, ignoreUnreadable, File "/xxx/vobject/vobject/base.py", line 1141, in readComponents raise ParseError("Component {0!s} was never closed".format( vobject.base.ParseError: At line 9: Component VCARD was never closed >>> **How can I transform a string to a vcard object?** To your second question, for parsing a vCard, you're doing the right thing: use `vobject.readOne()` or `vobject.readComponents()`. If your input data doesn't have the END:VCARD line truncated, it should parse correctly, returning you a vCard object.
``` interface Test { a: string; b: number; c: boolean; } let arr: string[] = [] function test<S extends Pick<Test, 'a' | 'b'>, T extends keyof S>(val: T[]) { arr = val // it's not ok } ``` [![enter image description here][1]][1] PlayGround: https://www.typescriptlang.org/play?ssl=19&ssc=27&pln=15&pc=1#code/JYOwLgpgTgZghgYwgAgCoQM5mQbwFDKHJwBcyWUoA5gNwFEBGZIArgLYPR1HIJkMB7AQBsIcEHQC+eGaOxwoUMhWoBtALrIAvMg0yYLEAjDABIZJCwAeAMrIIAD0ggAJhmQAFYAgDWV9FgANMgA5HAhyAA+oQwhAHzBqPZOEK7uPhAAngIwyDZxABQAbnDCZKgaAJS49IQKUNrIJcLIAPStyIaOSAAOkC72igJQAIR40jJgmT0odjpevv6YYMFhEdEhsXF0UzNojRnZuTYyCGZYTaXlGo169Y3NbR0A7gAWmcjA2MDuAj4A-EA But, if I don't use function, it's ok: ``` type S = Pick<Test, 'a' | 'b'>; type T = keyof S const val: T[] = [] arr = val // why it is ok? ``` And, When I declare the generic S separately, there is also no error: ``` type S = Pick<Test, 'a' | 'b'>; function test<T extends keyof S>(val: T[]) { arr = val // it is ok } ``` [1]: https://i.stack.imgur.com/Kim8d.png
This is my `truffle-config.js` <!-- begin snippet: js hide: false console: true babel: false --> <!-- language: lang-js --> require("babel-register"); const HDWalletProvider = require("truffle-hdwallet-provider"); require("dotenv").config(); module.exports = { networks: { Sepolia: { provider: function() { return new HDWalletProvider( process.env.MNEMONIC, process.env.PROJECT_ENDPOINT, address_index=0, num_addresses=2 ); }, network_id: 11155111 , gas: 4500000, gasPrice: 10000000000, }, development: { host: process.env.LOCAL_ENDPOINT.split(":")[1].slice(2), port: process.env.LOCAL_ENDPOINT.split(":")[2], network_id: "*", }, compilers: { solc: { version: "^0.4.24", }, }, }, }; <!-- end snippet --> I am unable to get the network ID for a Sepolia test network. Below is the link of the error I am getting [ERROR IMAGE][1] [1]: https://i.stack.imgur.com/gBDPN.png
|html|css|vue.js|
null
{"Voters":[{"Id":6752050,"DisplayName":"273K"},{"Id":207421,"DisplayName":"user207421"},{"Id":839601,"DisplayName":"gnat"}],"SiteSpecificCloseReasonIds":[13]}
RDF: when a property is used the thing in the object position is a literal of datatype X
I have made a few settings but each time you refresh your page or go to another page on the website, those settings go back to default. How do i store the users settings in cookies so that they stay as they are when the user refreshes or enters another page? The settings are an option to switch to dark mode and an option to switch languages. languages: ``` //html code// <div class="language"> <div class="langWrap"> <a href="#" language='dutch' class="lang active">NL</a> <a href="#" language='english' class="lang">EN</a> <a href="#" language='spanish' class="lang">ES</a> <a href="#" language='indonesian' class="lang">ID</a> </div> </div> //javascript code// const langEl = [...document.querySelectorAll(".lang")]; let chosenLanguage = 'NL'; langEl.forEach((el) => { el.addEventListener("click", () => { langEl.map(item => item.classList.contains("active") ? item.classList.remove("active") : false); el.classList.add("active"); chosenLanguage = el.innerText; search(); const attr = el.getAttribute("language"); }); }); ``` dark mode theme: ``` //html code// <img src="../images/moon.png" id="icon"> //javascript code// var icon = document.getElementById("icon"); icon.onclick = function() { document.body.classList.toggle("dark-theme"); if(document.body.classList.contains("dark-theme")){ icon.src = "images/sun.png"; } else { icon.src = "images/moon.png"; } } ```
Storing settings in cookies
|javascript|html|cookies|darkmode|
null
I think a good and simple solution is to use an adorner to render the masking symbols as an overlay of the original input. Show the adorner to render the masking characters while hiding the password by setting the foreground brush to the background brush. The following example shows how to use an `Adorner` to decorate the `TextBox`. I have removed some code to reduce the complexity (the original library code also contained validation of input characters and password length, event logic, routed commands, `SecureString` support, low-level caret positioning to support any font family for those cases where the font is not a monospace font and password characters and masking characters won't align correctly etc. and a much more complex default `ControlTemplate`). The current version therefore only supports monospace fonts. The supported fonts have to be registered in the constructor. You could implement monospace font detection instead. However, it's a fully working example (happy easter!). **UnsecurePasswodBox.cs** ```c# public class UnsecurePasswodBox : TextBox { public bool IsShowPasswordEnabled { get => (bool)GetValue(IsShowPasswordEnabledProperty); set => SetValue(IsShowPasswordEnabledProperty, value); } public static readonly DependencyProperty IsShowPasswordEnabledProperty = DependencyProperty.Register( "IsShowPasswordEnabled", typeof(bool), typeof(UnsecurePasswodBox), new FrameworkPropertyMetadata(default(bool), OnIsShowPasswordEnabledChaged)); public char CharacterMaskSymbol { get => (char)GetValue(CharacterMaskSymbolProperty); set => SetValue(CharacterMaskSymbolProperty, value); } public static readonly DependencyProperty CharacterMaskSymbolProperty = DependencyProperty.Register( "CharacterMaskSymbol", typeof(char), typeof(UnsecurePasswodBox), new PropertyMetadata('●', OnCharacterMaskSymbolChanged)); private FrameworkElement? part_ContentHost; private AdornerLayer? adornerLayer; private UnsecurePasswordBoxAdorner? maskingAdorner; private Brush foregroundInternal; private bool isChangeInternal; private readonly HashSet<string> supportedMonospaceFontFamilies; private FontFamily fallbackFont; static UnsecurePasswodBox() { DefaultStyleKeyProperty.OverrideMetadata( typeof(UnsecurePasswodBox), new FrameworkPropertyMetadata(typeof(UnsecurePasswodBox))); TextProperty.OverrideMetadata( typeof(UnsecurePasswodBox), new FrameworkPropertyMetadata(OnTextChanged)); ForegroundProperty.OverrideMetadata( typeof(UnsecurePasswodBox), new FrameworkPropertyMetadata(propertyChangedCallback: null, coerceValueCallback: OnCoerceForeground)); FontFamilyProperty.OverrideMetadata( typeof(UnsecurePasswodBox), new FrameworkPropertyMetadata(propertyChangedCallback: null, coerceValueCallback: OnCoerceFontFamily)); } public UnsecurePasswodBox() { this.Loaded += OnLoaded; // Only use a monospaced font this.supportedMonospaceFontFamilies = new HashSet<string>() { "Consolas", "Courier New", "Lucida Console", "Cascadia Mono", "Global Monospace", "Cascadia Code", }; this.fallbackFont = new FontFamily("Consolas"); this.FontFamily = fallbackFont; } private void OnLoaded(object sender, RoutedEventArgs e) { this.Loaded -= OnLoaded; FrameworkElement adornerDecoratorChild = this.part_ContentHost ?? this; this.adornerLayer = AdornerLayer.GetAdornerLayer(adornerDecoratorChild); if (this.adornerLayer is not null) { Rect contentBounds = LayoutInformation.GetLayoutSlot(adornerDecoratorChild); this.maskingAdorner = new UnsecurePasswordBoxAdorner(adornerDecoratorChild, this) { Foreground = Brushes.Black }; HandleInputMask(); } } private static void OnIsShowPasswordEnabledChaged(DependencyObject d, DependencyPropertyChangedEventArgs e) { var unsecurePasswordBox = (UnsecurePasswodBox)d; unsecurePasswordBox.HandleInputMask(); Keyboard.Focus(unsecurePasswordBox); } private static void OnCharacterMaskSymbolChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) => ((UnsecurePasswodBox)d).RefreshMask(); private static void OnTextChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) => ((UnsecurePasswodBox)d).RefreshMask(); private static object OnCoerceForeground(DependencyObject d, object baseValue) { var unsecurePasswordBox = (UnsecurePasswodBox)d; // Reject external font color change while in masking mode // as this would reveal the password. // But store new value and make it available when exiting masking mode. if (!unsecurePasswordBox.isChangeInternal && !unsecurePasswordBox.IsShowPasswordEnabled) { unsecurePasswordBox.foregroundInternal = baseValue as Brush; } return unsecurePasswordBox.isChangeInternal ? baseValue : unsecurePasswordBox.IsShowPasswordEnabled ? baseValue : unsecurePasswordBox.Foreground; } private static object OnCoerceFontFamily(DependencyObject d, object baseValue) { var unsecurePasswordBox = (UnsecurePasswodBox)d; var desiredFontFamily = baseValue as FontFamily; return desiredFontFamily is not null && unsecurePasswordBox.supportedMonospaceFontFamilies.Contains(desiredFontFamily.Source) ? baseValue : unsecurePasswordBox.FontFamily; } public override void OnApplyTemplate() { base.OnApplyTemplate(); this.part_ContentHost = GetTemplateChild("PART_ContentHost") as FrameworkElement; } private void HandleInputMask() { this.isChangeInternal = true; if (this.IsShowPasswordEnabled) { this.adornerLayer?.Remove(this.maskingAdorner); SetCurrentValue(ForegroundProperty, this.foregroundInternal); } else { this.foregroundInternal = this.Foreground; SetCurrentValue(ForegroundProperty, this.Background); this.adornerLayer?.Add(this.maskingAdorner); } this.isChangeInternal = false; } private void RefreshMask() { if (!this.IsShowPasswordEnabled) { this.maskingAdorner?.Update(); } } private class UnsecurePasswordBoxAdorner : Adorner { public Brush Foreground { get; set; } private readonly UnsecurePasswodBox unsecurePasswodBox; private const int DefaultTextPadding = 2; public UnsecurePasswordBoxAdorner(UIElement adornedElement, UnsecurePasswodBox unsecurePasswodBox) : base(adornedElement) { this.IsHitTestVisible = false; this.unsecurePasswodBox = unsecurePasswodBox; } public void Update() => InvalidateVisual(); protected override void OnRender(DrawingContext drawingContext) { base.OnRender(drawingContext); ReadOnlySpan<char> maskedInput = MaskInput(this.unsecurePasswodBox.Text); var typeface = new Typeface( this.unsecurePasswodBox.FontFamily, this.unsecurePasswodBox.FontStyle, this.unsecurePasswodBox.FontWeight, this.unsecurePasswodBox.FontStretch, this.unsecurePasswodBox.fallbackFont); double pixelsPerDip = VisualTreeHelper.GetDpi(this).PixelsPerDip; var maskedText = new FormattedText( maskedInput.ToString(), CultureInfo.CurrentCulture, this.unsecurePasswodBox.FlowDirection, typeface, this.unsecurePasswodBox.FontSize, this.Foreground, pixelsPerDip); maskedText.MaxTextWidth = ((FrameworkElement)this.AdornedElement).ActualWidth + UnsecurePasswordBoxAdorner.DefaultTextPadding; maskedText.Trimming = TextTrimming.None; var textOrigin = new Point(0, 0); textOrigin.Offset(this.unsecurePasswodBox.Padding.Left + UnsecurePasswordBoxAdorner.DefaultTextPadding, 0); drawingContext.DrawText(maskedText, textOrigin); } private ReadOnlySpan<char> MaskInput(ReadOnlySpan<char> input) { if (input.Length == 0) { return input; } char[] textMask = new char[input.Length]; Array.Fill(textMask, this.unsecurePasswodBox.CharacterMaskSymbol); return new ReadOnlySpan<char>(textMask); } } } ``` **Generic.xaml** ```xaml <Style TargetType="local:UnsecurePasswodBox"> <Setter Property="BorderBrush" Value="{x:Static SystemColors.ActiveBorderBrush}" /> <Setter Property="BorderThickness" Value="1" /> <Setter Property="Background" Value="White" /> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="local:UnsecurePasswodBox"> <Border Background="{TemplateBinding Background}" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}"> <Grid> <Grid.ColumnDefinitions> <ColumnDefinition /> <ColumnDefinition Width="Auto" /> </Grid.ColumnDefinitions> <AdornerDecorator Grid.Column="0"> <ScrollViewer x:Name="PART_ContentHost" /> </AdornerDecorator> <ToggleButton Grid.Column="1" IsChecked="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=IsShowPasswordEnabled}" Background="Transparent" VerticalContentAlignment="Center" Padding="4,0"> <ToggleButton.Content> <TextBlock Text="&#xE890;" FontFamily="Segoe MDL2 Assets" /> </ToggleButton.Content> <ToggleButton.Template> <ControlTemplate TargetType="ToggleButton"> <ContentPresenter Margin="{TemplateBinding Padding}" VerticalAlignment="{TemplateBinding VerticalContentAlignment}" HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" /> </ControlTemplate> </ToggleButton.Template> </ToggleButton> </Grid> </Border> </ControlTemplate> </Setter.Value> </Setter> </Style> ```
Tossing in the expectations communicates the intent of the test better, even if you're correct that they're not strictly necessary. I don't see any apparent performance penalty to including them, either. You may prefer to use `queryByText` which will return an element or null and let you write "normal" expects that are called on both success and failure cases. However, `query` doesn't wait for the predicate as `find` does, so you could use `waitFor` to build your own `find`. See [About Queries](https://testing-library.com/docs/queries/about/) for details on the differences. If you `expect` an element queried by text _not_ to exist, I've found that this can trigger large component object tree diffs that can slow down testing considerably (and serializing circular structures can crash it). You might use `expect(!!queryByText("this shouldn't exist")).toBe(false);` to avoid this scenario by converting the found element to a boolean, with the drawback that the assertion message will be less clear.
{"Voters":[{"Id":14853083,"DisplayName":"Tangentially Perpendicular"},{"Id":238704,"DisplayName":"President James K. Polk"},{"Id":839601,"DisplayName":"gnat"}],"SiteSpecificCloseReasonIds":[18]}
Vue.js Event Emitted in Child Component Not Detected by Parent Component
|typescript|vue.js|vuejs3|vue-composition-api|
I'm facing a challenge while working on the student automation system. After selecting the department field in the form, I want to display only the departments associated with the selected unit in the department field. Currently, I can see that the units are listed correctly in the unit selection dropdown, but all departments are listed in the department selection dropdown and not filtered. I'm struggling to find a solution for this. How can I display only the departments associated with the selected unit in the department field after selecting a unit? Do I need to edit my existing code or develop a new approach for this? `Controller.cs`: [HttpGet] public IActionResult AddStudent() { ViewBag.departments = _context.departments.ToList(); ViewBag.units = _context.units.ToList(); ViewBag.cities = _context.cities.ToList(); return View(); } `AddStudent.cshtml`: @model Student <form asp-action="AddStudent" method="post" class="m-5"> <div> <select class="form-control" asp-for="Department.Unit.unitId" asp-items="@(new SelectList(ViewBag.units, "unitId", "unitName"))" required="true"> <option value="">Pick Unit</option> </select> </div> <div> <select class="form-control" asp-for="unitId" asp-items="@(new SelectList(ViewBag.units, "departmentId", "departmentName"))" required="true"> <option value="">Pick Department</option> </select> </div> <div> <select class="form-control" asp-for="cityId" asp-items="@(new SelectList(ViewBag.cities, "cityId", "cityName"))" required="true"> <option value="">Pick City</option> </select> </div> <button type="submit" class="btn btn-primary">Save</button> </form> Thank you.
How to display only department fields associated with a selected department in student automation system?
I would use a simple loop: ``` out = (np.array([mapping[l] for l in map(tuple, input_array.reshape(-1, 2))]) .reshape(input_array.shape[:-1]) ) ``` Output: ``` array([[0.7, 0.8], [0.7, 0.9]]) ```
def function1(ss:pd.Series): date4curr=df1.loc[ss.max(),'date'] dd1=df1.loc[ss].loc[df1.date!=date4curr] df1.loc[ss.max(),'fraud_count']=dd1.fraud.sum() df1.loc[ss.max(),'fraud_sum']=dd1.query("fraud==1").amount.sum() return 1 df1.assign(col1=df1.index).groupby(['customer_id']).apply(lambda dd:dd.col1.expanding().apply(function1)) df1 : date customer_id transaction_id amount fraud fraud_count fraud_sum 2020-01-01 1 10 25 0 0 0 2020-01-01 2 11 14 1 0 0 2020-01-02 1 12 48 1 0 0 2020-01-02 2 13 12 1 1 14 2020-01-02 2 14 41 1 1 14 2020-01-03 1 15 30 0 1 48 2020-01-03 2 16 88 0 3 67
I am working on a website(MERN) which has a newsletter as well as a contact form both of my forms are sent on different routes, '/subscribe' and '/contact' respectively. I have hosted the server and client side on different domains. The contact form is working perfectly but in subscribe form I am facing a CORS error which says request denied by the server. The specific error is "official-site-version-2-0-8tjp.vercel.app/:1 Access to fetch at 'https://official-site-version-2-0.vercel.app/subscribe' from origin 'https://official-site-version-2-0-8tjp.vercel.app' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled." My server side code is ``` // Allow requests from your frontend domain const corsOptions = { origin: ["https://official-site-version-2-0-8tjp.vercel.app","https://official-site-version-2-0.vercel.app"], optionsSuccessStatus: 200 // some legacy browsers (IE11, various SmartTVs) choke on 204 }; app.use(cors(corsOptions)); app.use(express.json()); app.listen(5000, () => console.log("Server Running")); console.log(process.env.EMAIL_USER); console.log(process.env.EMAIL_PASS); const contactEmail = nodemailer.createTransport({ service: 'gmail', auth: { user: <email>, pass: <password> }, }); contactEmail.verify((error) => { if (error) { console.log(error); } else { console.log("Ready to Send"); } }); // Endpoint handler for handling contact form submissions app.post("/contact", (req, res) => { const name = req.body.firstName + req.body.lastName; const email = req.body.email; const message = req.body.message; const phone = req.body.phone; const mail = { from: name, to: "admin@devlooper.me", subject: "Contact Form Submission - Portfolio Devlooper", html: `<p>Name: ${name}</p> <p>Email: ${email}</p> <p>Phone: ${phone}</p> <p>Message: ${message}</p>`, }; contactEmail.sendMail(mail, (error) => { if (error) { res.json(error); } else { res.json({ code: 200, status: "Message Sent" }); } }); }); app.post("/subscribe", async (req, res) => { try { if (!req.body.email) { return res.status(400).json({ error: 'Email is required' }); } const db = client.db(dbName); const emailsCollection = db.collection('emails'); const result = await emailsCollection.insertOne({ email: req.body.email }); console.log('Email saved:', req.body.email); res.status(201).json({ message: 'Subscription successful', insertedId: result.insertedId }); } catch (error) { console.error('Error subscribing:', error); res.status(500).json({ error: 'Internal server error' }); } }); app.get('/', (req, res) => { res.send('Server is running! Click <a href="https://official-site-version-2-0-8tjp.vercel.app">here</a>'); }); ``` And my Client side code is ``` const handleSubmit = async (e) => { e.preventDefault(); if (!email || email.indexOf('@') === -1) { return; } try { const response = await fetch('https://official-site-version-2-0.vercel.app/subscribe', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ email }), }); const data = await response.json(); // Handle response if (response.ok) { // If subscription is successful, call onValidated with success status onValidated('success', data.message); // Clear email field after successful subscription setEmail(''); } else { // If subscription fails, call onValidated with error status onValidated('error', data.message); } } catch (error) { console.error('Error:', error); // Handle network errors onValidated('error', 'Network error. Please try again later.'); } }; ```
Why I am facing an Origin error despite having included the header in the code?
|javascript|node.js|cors|mern|
null
I'm trying to check if people were able to indicate "being in two different places at the same time". [https://docs.google.com/spreadsheets/d/1Z9I_5jvgrKKs0ejqJ-PF7FnA6LwHsWUou6xagtaxe3M/edit?usp=sharing][1] For that : - I import the presence data of role 1 into a first tab: role1 - I import the presence data of role 2 into a second tab: role2 In this data (which I do not control), attendance is given in days (J01, J02, J03, ...) except that the day numbers do not correspond to the same dates! So I have to find a trick to achieve my goals. To resolve this first problem, I have access to the schedule so that I can import the schedules and determine the days corresponding to each group (tabs R1, R2, R3, D1, D2, D3): in the tab days, I therefore collect the dates per group and per day. This information allows me to retrieve the "hen - day" pairs by date (tab journee_par_date) thanks to the help found here. So far, no problem. And that’s where it gets bad! I tried something probably complicated which means that I am at an impasse. To find duplicates of the same person in two different roles, I told myself that it was first necessary to transform the attendances which are noted in number of days (in my example, on the role1 tab, the information noted A1 or A2 (cells C2 to H14)) in corresponding dates. My idea was first to replace A1 and A2 with "hen - day" pairs, which I did in the yellow boxes of the role1 tab. Then then find this same correspondence in the table from the data in the day_by_date tab where I "calculate" the hen-day couple (boxes in orange). But the problem is that I can't figure out how I can search for a value (for example the value of cell L2 of the role1 tab) in a table with several rows and columns (in my example, cells J1 to P14 of the day_by_date tab. I hope I was clear enough in explaining my problem. If anyone could give me a hand. Perhaps a solution that has nothing to do with what I imagined would be more relevant in which case, I will be happy to take it! THANKS [1]: https://docs.google.com/spreadsheets/d/1Z9I_5jvgrKKs0ejqJ-PF7FnA6LwHsWUou6xagtaxe3M/edit?usp=sharing
Find a value in a range of cells (multiple rows and columns)
|google-sheets|google-sheets-formula|
|windows|32bit-64bit|createfile|
The load balancer suggestion won't work at all. Load balancers are only for **incoming** traffic. The question is entirely about **outgoing** traffic. A load balancer would not be involved in any way in the network traffic of the Fargate task's outgoing connection to an external database.
null
{"Voters":[{"Id":1145388,"DisplayName":"Stephen Ostermiller"}]}
In my case (windows pc) the extension_dir folder was set default to ext. However i got the same error "could not find driver". So i replaced the path to extension directoy with absolute path as below, and it worked. php.ini ;extension_dir = ext extension_dir = "C:\dev\php-8.3.4-Win32-vs16-x64\ext"
I have a Vite-based React library, currently structured like this: ``` import { Button, Typography, Box, Flex, Color, TypographyVariant } from '@placeholder-library'; ``` I want to separate the imports to add submodules so that components and shared are imported from different paths: ``` import { Button, Typography, Box, Flex } from '@placeholder-library/components’; import { Color, TypographyVariant } from ‘@placeholder-library/shared’; ``` **index.ts** import './index.scss'; export * from './components'; export * from './shared'; **vite.config.ts:** ``` import react from '@vitejs/plugin-react'; import path from 'path'; import { defineConfig } from 'vite'; import dts from 'vite-plugin-dts'; import svgr from 'vite-plugin-svgr'; import tsconfigPaths from 'vite-tsconfig-paths'; import commonjs from 'vite-plugin-commonjs'; export default defineConfig({ resolve: { alias: { src: path.resolve(__dirname, './src'), }, }, build: { outDir: 'build', lib: { entry: './src/index.ts', name: 'Placeholder Library', fileName: 'index', }, rollupOptions: { external: ['react', 'react-dom'], output: [ { globals: { react: 'React', 'react-dom': 'ReactDOM', }, }, { dir: 'build/cjs', format: 'cjs', globals: { react: 'React', 'react-dom': 'ReactDOM', }, }, { dir: 'build/esm', format: 'esm', globals: { react: 'React', 'react-dom': 'ReactDOM', }, }, ], }, sourcemap: true, emptyOutDir: true, }, plugins: [ svgr(), react(), commonjs(), tsconfigPaths(), dts({ outDir: ['build/cjs', 'build/esm', 'build'], include: ['./src/**/*'], exclude: ['**/*.stories.*'], }), ], }); ``` package.json: ``` { "name": "@placeholder-library", "version": "0.0.26", "description": "Placeholder Library components library", "license": "ISC", "main": "build/cjs/index.js", "module": "build/index.mjs", "files": ["*"], "scripts": { "build": "tsc && vite build", "build-storybook": "storybook build", "build-storybook-docs": "storybook build --docs", "dev": "vite", "format": "prettier --write .", "lint:fix": "eslint . --fix --ignore-path .gitignore", "prepare": "husky install", "preview": "vite preview", "storybook": "storybook dev -p 6006", "storybook-docs": "storybook dev --docs" }, "dependencies": { "..." }, "devDependencies": { "..." }, "peerDependencies": { "react": "^18.2.0" } } ``` my folder structure: My folder structure src index.ts components index.ts Button index.ts shared hooks index.ts How can I configure Vite and my package structure to achieve this separation of components and shared/utils? Any advice or examples would be greatly appreciated. I attempted to modify the **`vite.config.ts`** file to include separate entries for components and shared/utils, but I couldn't figure out how to properly configure the paths. I also tried to adjust the **`package.json`** file to specify different entry points for components and shared/utils, but I wasn't sure how to structure it correctly. `import { Button, Typography, Box, Flex } from '@placeholder-library/components’;` `import { Color, TypographyVariant } from ‘@placeholder-library/shared’;` However, I couldn't find a clear example or documentation on how to set this up in a Vite-based React library. Any guidance or examples on how to achieve this would be greatly appreciated.
In my case, inside the file **alembic/env.py** I mistakenly used ```py config.get_main_option ``` instead of ``` config.set_main_option ``` PS: ```py config = context.config ```
With Dockerfile you can build Docker images, and the Docker Compose creates containers from existing images. Or you can combine the two commands in the compose file (with the build option) and round the `docker compose up -d --build` command. This command first builds the image - same when you run the `docker build --tag image_name .` command. Finally, create the containers. So if you want to run `npm install` on build time you need to add the required files to the image with COPY or ADD command in the Dockerfile
{"Voters":[{"Id":466862,"DisplayName":"Mark Rotteveel"},{"Id":16217248,"DisplayName":"CPlus"},{"Id":10871073,"DisplayName":"Adrian Mole"}]}
I am trying to understand the internal workings of RowSet. How does it set the properties data and create a connection? ``` RowSetFactory factory = RowSetProvider.newFactory(); JdbcRowSet jdbcRowSet = factory.createJdbcRowSet(); jdbcRowSet.setUrl(".................."); jdbcRowSet.setUsername("............."); jdbcRowSet.setPassword(".............."); jdbcRowSet.setCommand("..............."); jdbcRowSet.execute(); ```
How RowSet works java?
|java|jdbc|resultset|rowset|
null
If you create the plot in two steps, you can definitely retrieve the x aesthetic from the aesthetic object. One option is to create the aesthetic object first, then generate the plot and retrieve the x aesthetic from the aes object: my_aes<-aes( x = xval, y = after_stat(density) ) ggplot(data = df) + geom_histogram(mapping=my_aes, bins=bin_number(df[,as_label(my_aes$x)])) Another option is to map the aesthetics inside ggplot(), and again retrieve the x aesthetic when adding the geom_histogram layer (you can also retrieve the data from the ggplot object): p<-ggplot(data=df, aes(x=xval, y=after_stat(density))) p+geom_histogram(bins=bin_number(p$data[,as_label(p$mapping$x)]))
Im slowly learning .net Core 8, and Im using Identity with individual user accounts. I've recently learned how to add custom properties to the user account such as FirstName and LastName. I would like to add a property called departments, however, each user may belong to several departments and so the AspNetUsers database table structure will not do. Ideally, I would have a separate table for departements (Deptid, DeptName) and another table for users in those departements (userId, DeptId) that can have multiple entries. I know how to create such tables manually using SQL server management studio and how to write the queries, but I am wondering if there is a way to add this with migrations and also have the usermanger return a list of departments for the user. Can someone point me in the right direction. Im not exactly sure what to even search for. I am looking for information on this topic
Net Core 8, how can I add properties to user account that contains multiple values?
I want to parse my api response into desired type and i don't want to loop/map the results to desired type or destruct the props after retrieval of response. Please do the response parse while receiving api response itself. API response in desired format: ``` import Items from "./DetailsResponse"; export default interface MinimalApiResponse { Items: Items[]; status: number; statusText: string; } ``` API call: ``` async getPolicies(detail: Detail): Promise<MinimalApiResponse> { try { const response: AxiosResponse<MinimalApiResponse> = await axios.post(this.searchUrl, policy); console.log(response); } catch (error) { throw error; } } ``` I have specified the minimalapiresponse there but still not result parsed to that type i do see other props as well apart from what i specified in minimalapiresponse. Please suggest.
Parse the API response into desired type using axios or any other helpful methods in JavaScript/React.js
|javascript|reactjs|axios|mapping|response|
null
As it stands, I have a game I writing, utilizing PCG (Procedural Content Generation). I was wondering if there was a better way to store the vertices of my polygon with certain library restrictions (Box2D is my chosen physics engine). Currently, I have this: ``` std::vector<b2Vec2> topChain; std::vector<b2Vec2> bottomChain; std::vector<b2Vec2> eastCap; std::vector<b2Vec2> westCap; ``` Box2D has a limitation ( as far as I'm aware ) that polygon fixtures can contain at most 8 vertices. Given I have sloping terrain, 8 vertices isn't enough for the smooth terrain I'm looking for. The solution was to slice each sloping section into a quad. However, my concern here is efficiency, and one thing I noticed is the time and memory it requires to fill these vectors. Hovering over each class name in Visual Studio, shows that `b2Vec2` is a whopping 8 bytes per. The container class of `std::vector` takes another 32 bytes. What would be the most efficient data structure for this problem?
I'm writing a middleware to validate a jwt token and add current authicated user to the request instance for protected routes in Actix web. here is my code use std::{ future::{ready, Ready}, rc::Rc }; use actix_web::{ body::EitherBody, dev::{forward_ready, Service, ServiceRequest, ServiceResponse, Transform}, http::header::AUTHORIZATION, Error, HttpMessage, HttpResponse, }; use futures_util::{future::LocalBoxFuture, FutureExt}; use serde_json::json; struct AuthUser { id: usize, email: Option<String> } pub struct JwtAuthChecker; impl<S, B> Transform<S, ServiceRequest> for JwtAuthChecker where S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = Error> + 'static, // update here S::Future: 'static, B: 'static, { type Response = ServiceResponse<EitherBody<B>>; type Error = Error; type InitError = (); type Transform = AuthenticationMiddleware<S>; type Future = Ready<Result<Self::Transform, Self::InitError>>; fn new_transform(&self, service: S) -> Self::Future { ready(Ok(AuthenticationMiddleware { service: Rc::new(service), // convert S to Rc<S> })) } } pub struct AuthenticationMiddleware<S> { service: Rc<S>, } impl<S, B> Service<ServiceRequest> for AuthenticationMiddleware<S> where S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = Error> + 'static, // update here S::Future: 'static, B: 'static, { type Response = ServiceResponse<EitherBody<B>>; type Error = Error; type Future = LocalBoxFuture<'static, Result<Self::Response, Self::Error>>; forward_ready!(service); fn call(&self, req: ServiceRequest) -> Self::Future { // Do something with the request here let auth = req.headers().get(AUTHORIZATION); if auth.is_none() { let response = json!({ "status": false, "message": "Unauthorized" }); let http_res = HttpResponse::Unauthorized().json(response); let (http_req, _) = req.into_parts(); let res = ServiceResponse::new(http_req, http_res); // Map to R type return (async move { Ok(res.map_into_right_body()) }).boxed_local(); } let jwt_token = get_jwt_token_from_header(auth.unwrap().to_str().unwrap()); // Clone the service to keep reference after moving into async block let service = self.service.clone(); async move { // Getting some data here (just demo code for async function) let user = get_some_data(jwt_token).await; req.extensions_mut().insert(user); // Continue with the next middleware / handler let res = service.call(req).await?; // Map to L type Ok(res.map_into_left_body()) }.boxed_local() } } async fn get_some_data(token: &str) -> AuthUser { // will fetch user data from token payload here let user = AuthUser { id: 1, email: Some(String::from("dev@gmail.com")) }; return user; } fn get_jwt_token_from_header(jwt_token: &str) -> &str { let bytes = jwt_token.as_bytes(); let token_len = jwt_token.len(); for (i, &item) in bytes.iter().enumerate() { if item == b' ' { let next_index = i + 1; return &jwt_token[next_index..token_len]; } } return &jwt_token[0..token_len]; } i'm getting confused inside the async block in the call() method how i can validate the jwt token here and put the user instance in the current request instance? I have followed this tutorial but didn't get it properly [https://ginkcode.com/post/implement-a-middleware-in-actix-web][1] [1]: https://ginkcode.com/post/implement-a-middleware-in-actix-web
Can't add user info to current request instance after validate the jwt token in actix web middleware in rust
|rust|rust-cargo|actix-web|
the next page button doesn't change the url when it's pressed, so i have problem with scrapy. ''' ``` import scrapy class LegonSpider(scrapy.Spider): name = "legon" def start_requests(self): yield scrapy.Request( url="https://mylegion.org/PersonifyEbusiness/Find-a-Post", callback=self.parse ) def parse(self, response): # Select distance and country yield scrapy.FormRequest.from_response( response, formid='aspnetForm', formdata={'dnn$ctr2802$DNNWebControlContainer$ctl00$DistanceList': '100', '@IP_COUNTRY': 'USA', '@IP_DEPARTMENT': '00000000001L'}, callback=self.parse_post_page ) def parse_post_page(self, response): # Extract and yield requests for post detail pages post_elements = response.xpath("//div[@class='membership-dir-result-item']") for post_element in post_elements: post_num = post_element.xpath(".//div[contains(@class,'POST_NAME')]/text()").get().strip() post_link = post_element.xpath("./a/@href").get() yield response.follow(post_link, callback=self.parse_post_detail, meta={'post_num': post_num}) next_page_button = response.xpath("/input[@id='dnn_ctr2802_DNNWebControlContainer_ctl00_Next']") if next_page_button: # Extract form data for next page submission formdata = { '__EVENTTARGET': 'dnn$ctr2802$DNNWebControlContainer$ctl00$Next', '__EVENTARGUMENT': '' } yield scrapy.FormRequest.from_response(response, formdata=formdata, callback=self.parse_post_page) def parse_post_detail(self,response): leader1 = response.xpath("(//div[contains(@class,'Leadership')]/div[2]/text())[1]").get() leader2 = response.xpath("(//div[contains(@class,'Leadership')]/div[2]/text())[2]").get() address = response.xpath("//div[contains(@class,'Address')]/div[2]/text()").get() typ = response.xpath("//div[contains(@class,'Type')]/div[2]/text()").get() yield { "post_num": response.meta['post_num'], "leader1": leader1, "leader2": leader2, "address": address, "type" : typ } ``` i think scrapy didn't even go the next page he's going to the base url which is not changing at all when i press next page or i try to use new search method .
> Why does the function need a window as an argument? It ensures that the function has a reference to the global window object in scope (it doesn't have to use global scope). Common pattern in JavaScript to pass globals into an IIFE. Also when running in environments where `window` might not exist. > What does this variable declaration mean: var App = window.App || { }; If `window.App` exists, assign it to `App`, otherwise initialize `App` to an empty object `{}`. > why is it that at the bottom line there is a declaration: window.App = > App It assigns `App` (*local*) to `window.App` (*global*). Ensures modifications made to `App` inside the function are preserved in the global scope (not in the function).
{"Voters":[{"Id":19639413,"DisplayName":"pmacfarlane"},{"Id":584518,"DisplayName":"Lundin"},{"Id":9214357,"DisplayName":"Zephyr"}],"SiteSpecificCloseReasonIds":[13]}
a little back story about my situation. I don't know how to code, and have very little knowledge in the general field. I recently hired someone on upwork to complete an automation tool for me. In a recent demo that we had over Zoom, the tool/code worked on her computer. So she sent me the files and when I ran it on my computer, it completed about half of the automation process and then stopped. From what I saw, the code is the exact same thing that she is running. She doesn't know what the issue is and I haven't a clue what is wrong but have been trying to trouble shoot myself. Is there anything that I can look into that could be the cause? This is the error that keeps popping up: ``` ERROR - Reason of failure {} java.lang.NullPointerException: Cannot invoke "org.openqa.selenium.WebElement.click()" because "newPostBtn" is null ``` Not sure if this is helpful, but the files that run this code are a PROPERTIES file, batch file, and jar file. I thought it could be a syntax issue with the font or something but after retyping the code it doesn't seem to have changed anything.
Might be network issues. Or try deleting `C:\Users\Muhammad_Kamran\.gradle\wrapper\dists\gradle-4.10.2-all\9fahxiiecdb76a5g3aw9oi8rv`. - If its unix platform try `rm -rf C:\Users\Muhammad_Kamran\.gradle\wrapper\dists\gradle-4.10.2-all\9fahxiiecdb76a5g3aw9oi8rv` Try and check the permissions on the directory. You can also try upgrading gradle-wrapper.properties. Lastly, you can also download the gradle distribution manually from the website and place it in `C:\Users\Muhammad_Kamran\.gradle\wrapper\dists\`
This seems to be a msvc bug. The program is well-formed. Here is the newly reported bug: [MSVC rejects valid program involving template paramter pack taking array by reference ](https://developercommunity.visualstudio.com/t/MSVC-rejects-valid-program-involving-tem/10628323)
Lets say I am building an interface with the following command: ```lang-bash $ run --display (file/env/db) # default to file if invalid is entered ``` What I am looking for specifically is how to obtain an enum value with the following: Given: ``` data type = File | Env | Db ``` When the command `run --display file` is entered, the enum `File` is returned. As far as I know, the `strOption` and `strArgument` functions are used for any arbitrary string argument. I have read the complete documentation but couldn't figure out any easy solution for this. Any help would be appreciated.
How to calculate Matrix exponential with Tailor series PARALLEL using MPI c++
|c++|parallel-processing|mpi|
null