instruction
stringlengths
0
30k
|laravel|mongodb|mql|laravel-mongodb|
I believe `settings.gradle` file is not meant to do what you're looking for. You can include all the submodules in the `settings.gradle` file and then link as dependency the module you need in the app's `build.gradle` file, dependencies section: dependencies { ... marketOneImplementation(project(":SubModule2")) marketTwoImplementation(project(":SubModule8")) } In this way, when the `marketOne` flavor is selected then submodule 2 will be included (but not submodule 8). Same thing when the `marketTwo` flavor is selected.
> I wanted to ask how I can use this schema to create a database file and prepopulate it. The simplest way, rather than trying to interpret the saved schema, is to let Room do the interpretation by: 1. Successfully compiling the project 1. From the Android View of Android Studio locate the java (generated) folder/directory 1. Within the java (generated) folder find the class that is the same name as the `@Database` annotated class (*LocationDatabase in you case*) BUT is suffixed with _Impl (*In your case **`LocationDatabase_Impl`***). 1. Find the `createAllTables` method, this will have a line of code that executes the SQL to create all the tables. This SQL is exactly what Room expects and can be copied to whatever tool you are using to build the pre-packaged database. 1. Once populated and saved as a single file you can copy the file into the assets folder (which you may have to create) 1. (if the is a -wal file then database has not been closed and you need to properly close the database e.g. with Navicat you have to close the application) 1. You then include the [`createFromAsset`][1] method in the databaseBuilder call You may wish to refer to https://stackoverflow.com/questions/71954872/how-to-prepopulate-database-using-room-i-dont-see-tutorials-that-explains-in-d/71960555#71960555 which covers the steps in more detail. [1]: https://developer.android.com/reference/kotlin/androidx/room/RoomDatabase.Builder#createfromasset
Can adapter.notifyItemRangeChanged(0, itemCount) replace adapter.notifyDataSetChanged()?
|java|android|
{"Voters":[{"Id":7758804,"DisplayName":"Trenton McKinney"},{"Id":466862,"DisplayName":"Mark Rotteveel"},{"Id":1071630,"DisplayName":"nikoshr"}]}
|csv|jmeter|jmeter-plugins|
[Undefined method 'safe'.intelephense(P1013)](https://i.stack.imgur.com/34DNQ.png) ``` $user_input = $request->only(["name", "email", "password"]); $profile_input = $request->except(["name", "email", "password", "password_confirmation"]); ``` but when I used it, my postman gave an error: Illuminate\Database\QueryException: SQLSTATE[HY000]: General error: 1364 Field 'last_name' doesn't have a default value (Connection: mysql, SQL: insert into `profiles`
I want to plot two plots with `make_subplots` with different times. How should I do that? ``` fig = make_subplots(rows=2, cols=1,row_heights=[0.5, 0.5], shared_xaxes=True) fig.add_trace(go.Candlestick(x=dfpl.index, open=dfpl['open'], high=dfpl['high'], low=dfpl['low'], close=dfpl['close']), row=1, col=1) fig.add_trace(go.Candlestick(x=dfDiv.index, open=dfDiv['open'], high=dfDiv['high'], low=dfDiv['low'], close=dfDiv['close']), row=2, col=1) ``` My indexes are different `datetime`s. The chart is shown as below: [![plot][1]][1] [1]: https://i.stack.imgur.com/vgx6v.png
Different X axes with Plotly's make_subplots
I know it's an old post but, for those who came here looking for an answer, I found this plugin "Context Menu Toggle Comments", you can install it directly from the plugin section in visual studio code.<br><br> It adds at the bottom of the context menu:<br> "Toggle Block Comment"<br> "Toggle Line Comment"<br> Here is the link:<br> https://marketplace.visualstudio.com/items?itemName=henryclayton.context-menu-toggle-comments
|r|windows|rscript|
I currently have a `Chat` model which has an array named `deletedUsers` containing objects with the following format: `{deletionDate: Date, userId: Id}`. I want to delete a `Chat` document if the `_id` matches the specified `id` and if **all** the `deletedUsers.deletionDate` values are greater than the current date. This is the query I currently have: await Chat.findOneAndDelete({ $and: [{ _id: req.params.chatid }, {"deletedUsers.deletionDate": {$gt: Date.now()}}] }) The problem with this query is that it will **delete** a document even if the `deletionDate` is greater than the current date for **only one array element**. I only want the document to be deleted if this is **true** for all array elements, not just one. I attempted to use the `$all` operator with this query, however, I got an error perhaps due to an incorrect use case of this operator. This is an example of what a `deletedUsers` array would look like for a typical `Chat` document: deletedUsers array - [{userId: Id, deletionDate: Date}, {userId: Id2, deletionDate: Date2}] Any ideas on how to adjust this query to perform as expected? Thank you.
I am quite new to ANtlr and writing expression. I have a table with two columns of string ColA and ColB. Im tryng to run this expression using ANtlr: [ColA] == [ColB] Doing so gives an expression error. Is comparing two columns possible using ANtlr if so can someone please show me how.
Antlr Expression comparing two columns in a table
|antlr|
I'm trying to reproduce an article on medium in order to move further based on it. Particularly I'm interesting in graph neural networks and I would to go deeper into them. What I want is the output for a node of my network in a tensor form, that is to say: ``` [0.3242,0.5346,1.5643,.....] ``` so If I take the network and I ask for a node, this I expect to be the output. I want to share the code: ``` zip_file = keras.utils.get_file( fname="cora.tgz", origin="https://linqs-data.soe.ucsc.edu/public/lbc/cora.tgz", extract=True, ) data_dir = os.path.join(os.path.dirname(zip_file), "cora") citations = pd.read_csv( os.path.join(data_dir, "cora.cites"), sep="\t", header=None, names=["target", "source"], ) papers = pd.read_csv( os.path.join(data_dir, "cora.content"), sep="\t", header=None, names=["paper_id"] + [f"term_{idx}" for idx in range(1433)] + ["subject"], ) class_values = sorted(papers["subject"].unique()) class_idx = {name: id for id, name in enumerate(class_values)} paper_idx = {name: idx for idx, name in enumerate(sorted(papers["paper_id"].unique()))} papers["paper_id"] = papers["paper_id"].apply(lambda name: paper_idx[name]) citations["source"] = citations["source"].apply(lambda name: paper_idx[name]) citations["target"] = citations["target"].apply(lambda name: paper_idx[name]) papers["subject"] = papers["subject"].apply(lambda value: class_idx[value]) ``` ``` # Obtain random indices random_indices = np.random.permutation(range(papers.shape[0])) # 50/50 split train_data = papers.iloc[random_indices[: len(random_indices) // 2]] test_data = papers.iloc[random_indices[len(random_indices) // 2 :]] # Obtain paper indices which will be used to gather node states # from the graph later on when training the model train_indices = train_data["paper_id"].to_numpy() test_indices = test_data["paper_id"].to_numpy() # Obtain ground truth labels corresponding to each paper_id train_labels = train_data["subject"].to_numpy() test_labels = test_data["subject"].to_numpy() # Define graph, namely an edge tensor and a node feature tensor edges = tf.convert_to_tensor(citations[["target", "source"]]) node_states = tf.convert_to_tensor(papers.sort_values("paper_id").iloc[:, 1:-1]) ``` ``` class GraphAttention(layers.Layer): def __init__( self, units, kernel_initializer="glorot_uniform", kernel_regularizer=None, return_attention_scores=True, **kwargs, ): super().__init__(**kwargs) self.units = units self.kernel_initializer = keras.initializers.get(kernel_initializer) self.kernel_regularizer = keras.regularizers.get(kernel_regularizer) def build(self, input_shape): self.kernel = self.add_weight( shape=(input_shape[0][-1], self.units), trainable=True, initializer=self.kernel_initializer, regularizer=self.kernel_regularizer, name="kernel", ) self.kernel_attention = self.add_weight( shape=(self.units * 2, 1), trainable=True, initializer=self.kernel_initializer, regularizer=self.kernel_regularizer, name="kernel_attention", ) self.built = True def call(self, inputs): node_states, edges = inputs # Linearly transform node states node_states_transformed = tf.matmul(node_states, self.kernel) # (1) Compute pair-wise attention scores node_states_expanded = tf.gather(node_states_transformed, edges) node_states_expanded = tf.reshape( node_states_expanded, (tf.shape(edges)[0], -1) ) attention_scores = tf.nn.leaky_relu( tf.matmul(node_states_expanded, self.kernel_attention) ) attention_scores = tf.squeeze(attention_scores, -1) # (2) Normalize attention scores attention_scores = tf.math.exp(tf.clip_by_value(attention_scores, -2, 2)) attention_scores_sum = tf.math.unsorted_segment_sum( data=attention_scores, segment_ids=edges[:, 0], num_segments=tf.reduce_max(edges[:, 0]) + 1, ) attention_scores_sum = tf.repeat( attention_scores_sum, tf.math.bincount(tf.cast(edges[:, 0], "int32")) ) attention_scores_norm = attention_scores / attention_scores_sum # (3) Gather node states of neighbors, apply attention scores and aggregate node_states_neighbors = tf.gather(node_states_transformed, edges[:, 1]) out = tf.math.unsorted_segment_sum( data=node_states_neighbors * attention_scores_norm[:, tf.newaxis], segment_ids=edges[:, 0], num_segments=tf.shape(node_states)[0], ) return out ``` ``` class MultiHeadGraphAttention(layers.Layer): def __init__(self, units, num_heads=8, merge_type="concat", return_attention_scores=True, **kwargs): super().__init__(**kwargs) self.num_heads = num_heads self.merge_type = merge_type self.attention_layers = [GraphAttention(units) for _ in range(num_heads)] def call(self, inputs): atom_features, pair_indices = inputs # Obtain outputs from each attention head outputs = [ attention_layer([atom_features, pair_indices]) for attention_layer in self.attention_layers ] # Concatenate or average the node states from each head if self.merge_type == "concat": outputs = tf.concat(outputs, axis=-1) else: outputs = tf.reduce_mean(tf.stack(outputs, axis=-1), axis=-1) # Activate and return node states return tf.nn.relu(outputs) ``` ``` class GraphAttentionNetwork(keras.Model): def __init__( self, node_states, edges, hidden_units, num_heads, num_layers, output_dim, **kwargs, ): super().__init__(**kwargs) self.node_states = node_states self.edges = edges self.preprocess = layers.Dense(hidden_units * num_heads, activation="relu") self.attention_layers = [ MultiHeadGraphAttention(hidden_units, num_heads) for _ in range(num_layers) ] self.output_layer = layers.Dense(output_dim) def call(self, inputs): node_states, edges = inputs x = self.preprocess(node_states) for attention_layer in self.attention_layers: x = attention_layer([x, edges]) + x outputs = self.output_layer(x) return outputs def train_step(self, data): indices, labels = data with tf.GradientTape() as tape: # Forward pass outputs = self([self.node_states, self.edges]) # Compute loss loss = self.compiled_loss(labels, tf.gather(outputs, indices)) # Compute gradients grads = tape.gradient(loss, self.trainable_weights) # Apply gradients (update weights) optimizer.apply_gradients(zip(grads, self.trainable_weights)) # Update metric(s) self.compiled_metrics.update_state(labels, tf.gather(outputs, indices)) return {m.name: m.result() for m in self.metrics} def predict_step(self, data): indices = data # Forward pass outputs = self([self.node_states, self.edges]) # Compute probabilities return tf.nn.softmax(tf.gather(outputs, indices)) def test_step(self, data): indices, labels = data # Forward pass outputs = self([self.node_states, self.edges]) # Compute loss loss = self.compiled_loss(labels, tf.gather(outputs, indices)) # Update metric(s) self.compiled_metrics.update_state(labels, tf.gather(outputs, indices)) return {m.name: m.result() for m in self.metrics} ``` ``` # Define hyper-parameters HIDDEN_UNITS = 100 NUM_HEADS = 8 NUM_LAYERS = 3 OUTPUT_DIM = len(class_values) NUM_EPOCHS = 10 BATCH_SIZE = 256 VALIDATION_SPLIT = 0.1 LEARNING_RATE = 3e-1 MOMENTUM = 0.9 loss_fn = keras.losses.SparseCategoricalCrossentropy(from_logits=True) optimizer = keras.optimizers.SGD(LEARNING_RATE, momentum=MOMENTUM) accuracy_fn = keras.metrics.SparseCategoricalAccuracy(name="acc") early_stopping = keras.callbacks.EarlyStopping( monitor="val_acc", min_delta=1e-5, patience=5, restore_best_weights=True ) # Build model gat_model = GraphAttentionNetwork( node_states, edges, HIDDEN_UNITS, NUM_HEADS, NUM_LAYERS, OUTPUT_DIM ) # Compile model gat_model.compile(loss=loss_fn, optimizer=optimizer, metrics=[accuracy_fn]) gat_model.fit( x=train_indices, y=train_labels, validation_split=VALIDATION_SPLIT, batch_size=BATCH_SIZE, epochs=NUM_EPOCHS, callbacks=[early_stopping], verbose=2, ) _, test_accuracy = gat_model.evaluate(x=test_indices, y=test_labels, verbose=0) print("--" * 38 + f"\nTest Accuracy {test_accuracy*100:.1f}%") ``` I know that in this case the model has been implemented to detect at which class the topic is linked, but starting from that I would be able to understand how keep the hidden state of the multigraph attention layer for each node. Thank you for your time and your patience.
How can I get the tensor output of an attention layer?
|python|tensorflow|deep-learning|charts|graph-neural-network|
null
The sample data contains two "2023-09-26". The dates are supposed to be unique, right? I guess this solution gives you more control over the window. library(purrr) library(lubridate) # ----------------- dat$arm <- map_dbl( .x = dat$date, .f = \(x) mean(dat$values[dat$date %in% (x-days(1:365))], na.rm = TRUE))
In my case I was getting `SIGABRT` with code `SI_QUEUE` when allocating memory in loop. I think I was doing it properly and safely using **nothrow**: uint8_t* ptr = new(std::nothrow) uint8_t[allocationSize]; if (ptr == nullptr) { break; } but system didn't like it and killed my app. Behavior might depend on system, in my case I was running this code on Android emulator.
You can use [$sortArray](https://www.mongodb.com/docs/manual/reference/operator/aggregation/sortArray/) to sort `fields.employees` based on `first_name` using the [aggregate](https://www.mongodb.com/docs/manual/reference/command/aggregate/) method like so: ````js db.collection.aggregate([ { $match: { "fields.uuid": "some_uuid" } }, { $set: { "fields.employees": { $sortArray: { input: "$fields.employees", sortBy: { "first_name": 1 } } } } } ]) ```` See [HERE](https://mongoplayground.net/p/xDaqrRro9MU) for a working example. The `$match` stage is synonymous with the query used in a regular `find` or `findOne` method. Using a `1` or `-1` for the sort reverses the order.
> Is there a way to move all the dependencies folders to a subfolder and still have Python (embedded version) work? Yes. Dependencies can in principle be installed anywhere, as long as the folder that contains them is on the PYTHONPATH (see: [PYTHONPATH](https://docs.python.org/3/using/cmdline.html#envvar-PYTHONPATH)). By default dependencies should be installed in the Python "site-packages" directory: `%APPDATA%\Python\PythonXY\site-packages` or under `{some_dir}\PythonXY\Lib\site-packages` (see: [site.USER_SITE](https://docs.python.org/3/library/site.html#site.USER_SITE)). Unless you have a special Python executable there is usually also no need to package up extra dependencies. The main docs you need to consult for your question are: [How does Python find modules?](https://docs.python.org/3/tutorial/modules.html#the-module-search-path).
Description: > Given a series of the height of buildings, for each building, please > calculate the number of unblocked buildings it can see ahead. We say > that the i-th building with the height h_i is blocked by the j-th > building with the height h_j only if i \< j and h_i \<= h_j. The > unblocked building (the j-th building) that the i-th building can see > ahead satisfies: (1) j \< i (2) not blocked by any k-th buildings with > k \< i. Write an algorithm that runs in O(n) total time. > >Sample Input 1: >```text >8 >5 3 8 3 2 5 5 5 >``` >I have written the following code in C. I am not sure why am I getting the wrong answer. I tested quite a number of different cases which all give correct answers(I cannot find a wrong test maybe I am testing not a large number of buildings in the test case I use). But I am not sure why the logic is still wrong. Also, how can I make my code more cleaner? Moreover, this task make use of StackADT and I assume that you are familiar with the basic functions in this ADT. Thank you so much for your help! Editted: >The parameter StackADT s is simply an empty stack called s. While int value refers to the height of the building. Suppose this function DoSomething() is computing the unblocked buildings that the observer can see when the stack s and the height of the building (int value) are passed to the function. In sample input 1, 8 means there are in total of 8 buildings And each number follows in the array correspond to the height of each building. ``` int DoSomething(StackADT s, int value) { int count = 0; if(IsEmpty(s)){ Push(s, value); return 0; } int index = s->size-1; int blockingheight = value; // counting numbers smaller than value for(index; index>=0; index--){ if(s->arr[index] < value){ count++; } else if(s->arr[index] == value){ count++; break; } else{ break; } } // counting numbers larger than value for(index; index>=0; index--){ if(s->arr[index] > blockingheight){ count++; blockingheight = s->arr[index]; } } Push(s, value); return count;}
I have code below and based on MDN document, I know how `result` and `state` will be specified for a `promise`, resulted from a handler: > returns a value: p gets fulfilled with the returned value as its > value. > doesn't return anything: p gets fulfilled with undefined as its > value. > throws an error: p gets rejected with the thrown error as its > value. > returns an already fulfilled promise: p gets fulfilled with > that promise's value as its value. > returns an already rejected promise: p gets rejected with that promise's > value as its value. > returns another pending promise: p is pending and becomes > fulfilled/rejected with that promise's value as its value immediately > after that promise becomes fulfilled/rejected. so why the `state` for my `promise` is `fullfilled`? code: const test = Promise.reject(new Promise((resolve, reject) => { throw new Error("error") })) const test2 = test.catch((result) => { result.catch(() => { throw new Error("error2"); }) }) console.log(test2); //result in console: //[[Prototype]]: Promise //[[PromiseState]]: "fulfilled" //[[PromiseResult]]: undefined
why promise returns an unexpected output for nested promises?
|javascript|promise|
I am trying to send a music file from my app to WhatsApp using Apple Share sheet which is UIActivityViewController. I am able to share the music file but the problem is I cannot add metadata to this. I mean I can share audio with url and it can be open and listen in WhatsApp but I cannot figure out how to add metadata to this url, I want to add title, description and image to my url as Apple Music do, then when shared in WhatsApp you can see some data with the file url, not only the audio file. Is It possible ? When I open the share sheet with my code I can set metadata image, title and description in the header as you can see in the following image : https://i.stack.imgur.com/Ymzec.jpg This following image is when I share an audio music file from my app to WhatsApp, you can see I want to share metadata too but I cannot add these datas : https://i.stack.imgur.com/3qHK9.jpg The following image it is almost what I want, it is shared by Apple Music app to WhatsApp, you can see the metadata (image, title and some description text) : https://i.stack.imgur.com/WuVus.jpg Here is my code : ``` func openShareSheet(shareItem: ShareFile, completion: @escaping (String?) -> Void) { var item: ShareItem = ShareItem(title: shareItem.title, artist: shareItem.artist, url: shareItem.url, coverImage: UIImage(named: "defaultImage")) getImage(shareItem.coverImage) { image in if let image = image { item.coverImage = image let itemToShare: [Any] = [ item ] let activityViewController = UIActivityViewController(activityItems: itemToShare, applicationActivities: nil) activityViewController.popoverPresentationController?.sourceView = self.navigationController?.navigationBar activityViewController.excludedActivityTypes = [UIActivity.ActivityType.addToReadingList, UIActivity.ActivityType.assignToContact] activityViewController.completionWithItemsHandler = { (activityType, completed: Bool, returnedItems: [Any]?, error: Error?) in if completed { doSomething() } self.deleteFile(filePath: shareItem.url) completion(nil) } self.present(activityViewController, animated: true, completion: nil) } else { completion("Image error") } } } import LinkPresentation class ShareFile { var title: String var artist: String var url: URL var coverImage: String init(title: String, artist: String, url: URL, coverImage: String) { self.title = title self.artist = artist self.url = url self.coverImage = coverImage } } class ShareItem: UIActivityItemProvider { var title: String var artist: String var url: URL var coverImage: UIImage? init(title: String, artist: String, url: URL, coverImage: UIImage?) { self.title = title self.artist = artist self.url = url self.coverImage = coverImage super.init(placeholderItem: "") } override var item: Any { return url } override func activityViewControllerPlaceholderItem(_ activityViewController: UIActivityViewController) -> Any { return url } override func activityViewController(_ activityViewController: UIActivityViewController, itemForActivityType activityType: UIActivity.ActivityType?) -> Any? { return url } override func activityViewController(_ activityViewController: UIActivityViewController, subjectForActivityType activityType: UIActivity.ActivityType?) -> String { return title } @available(iOS 13.0, *) override func activityViewControllerLinkMetadata(_ activityViewController: UIActivityViewController) -> LPLinkMetadata? { let metadata: LPLinkMetadata = LPLinkMetadata() metadata.title = title metadata.originalURL = URL(fileURLWithPath: artist) metadata.url = url metadata.imageProvider = NSItemProvider(object: coverImage ?? UIImage()) return metadata } }``` Is it possible to do the same thing in my app please ?
For example, I use XAMPP on Windows and I have the following file structure: ``` C:\xampp\htdocs\website_1 C:\xampp\htdocs\website_2 C:\xampp\htdocs\website_3 ``` By default, any script e.g. in the `website_1` folder has access to any file on my computer. I want to create a "sandbox" for each website. I tried to use `open_basedir`, but it significantly slows down websites.
How to isolate PHP apps from each other on a local machine(Windows or Linux)?
|php|apache|xampp|webserver|lamp|
null
Here is one possible option using [`cKDTree.query`][1] from [tag:scipy]: ```py from scipy.spatial import cKDTree def knearest(gdf, **kwargs): notna = gdf["PPM_P"].notnull() coordinates = gdf.get_coordinates().to_numpy() dist, idx = ( cKDTree(coordinates[notna]).query( coordinates[~notna], **kwargs) ) _ser = pd.Series( gdf.loc[notna, "PPM_P"].to_numpy()[idx].tolist(), index=(~notna)[lambda s: s].index, ) gdf.loc[~notna, "PPM_P"] = _ser[~notna].map(np.mean) return gdf N = 2 # feel free to make it 5, or whatever.. out = knearest(gdf.to_crs(3662), k=range(1, N + 1))#.to_crs(4326) ``` Output (*with `N=2`*): [![enter image description here][2]][2] ***NB**: Each red point (an `FID` having no `PPM_P`), is associated with the `N` nearest green points* : ``` { 1: [0, 10], 2: [11, 12], 3: [12, 4], 5: [14, 4], 6: [14, 7], 8: [9, 0], 13: [4, 14], 15: [14, 7], 16: [7, 14], 17: [7, 14], 18: [7, 14], 19: [9, 0], } ``` Final GeoDataFrame (*with intermediates*): ```py FID PPM_P (OP) PPM_P (INTER) PPM_P geometry 0 0 34.919571 NaN 34.919571 POINT (842390.581 539861.877) 1 1 NaN 37.480218 37.480218 POINT (842399.476 539861.532) 2 2 NaN 35.567003 35.567003 POINT (842408.370 539861.187) 3 3 NaN 35.567003 35.567003 POINT (842420.229 539860.726) 4 4 36.214436 NaN 36.214436 POINT (842429.124 539860.381) 5 5 NaN 38.127651 38.127651 POINT (842438.018 539860.036) 6 6 NaN 40.431946 40.431946 POINT (842446.913 539859.691) 7 7 40.823028 NaN 40.823028 POINT (842458.913 539862.868) 8 8 NaN 37.871299 37.871299 POINT (842378.298 539851.425) 9 9 40.823028 NaN 40.823028 POINT (842390.158 539850.965) 10 10 40.040865 NaN 40.040865 POINT (842399.052 539850.620) 11 11 36.214436 NaN 36.214436 POINT (842407.947 539850.275) 12 12 34.919571 NaN 34.919571 POINT (842419.947 539853.452) 13 13 NaN 38.127651 38.127651 POINT (842428.841 539853.107) 14 14 40.040865 NaN 40.040865 POINT (842437.736 539852.761) 15 15 NaN 40.431946 40.431946 POINT (842449.595 539852.301) 16 16 NaN 40.431946 40.431946 POINT (842458.489 539851.956) 17 17 NaN 40.431946 40.431946 POINT (842467.384 539851.611) 18 18 NaN 40.431946 40.431946 POINT (842476.278 539851.266) 19 19 NaN 37.871299 37.871299 POINT (842368.981 539840.859) ``` [1]: https://docs.scipy.org/doc/scipy/reference/generated/scipy.spatial.cKDTree.query.html [2]: https://i.stack.imgur.com/KefCq.png
If you are running it locally try: > `streamlit run app.py --server.enableXsrfProtection false`
I have a Postgres custom type as below: create type custom_type as ( a text, b text, c boolean ); And the function is as follows CREATE OR REPLACE FUNCTION test(strings custom_type[]) RETURNS VOID AS $$ BEGIN end; $$ language plpgsql; Now i have the following JDBC implementation as follows. try (Connection connection = DataSource.getConnection()) { String call = "select test(?)"; Array sqlArray = connection.createArrayOf("custom_type", new CustomTypeDTO[]{ new CustomTypeDTO("123456", "11221", "false"), new CustomTypeDTO("123426", "113221", "false"), }); PreparedStatement preparedStatement = connection.prepareStatement(call) preparedStatement.setArray(1, sqlArray); preparedStatement.execute(); } catch (SQLException e) { e.printStackTrace(); } Here i get the following error ERROR: malformed record literal: "main.java.test.dto.CustomTypeDTO@4802796d" Detail: Missing left parenthesis.
JDBC call function with custom type parameter
|java|postgresql|jdbc|
I want to remove duplicate ranges of 3 within an array: ``` let array = [ "string-1", "string-2", "string-3", "string-4", "string-5", "string-3", "string-4", "string-5", "string-6", "string-7", "string-8", "string-9", "string-10", "string-11", "string-9", "string-10", "string-11", "string-12" ] ``` The patterns: ``` "string-3", "string-4", "string-5" ``` and ``` "string-9", "string-10", "string-11" ``` appear twice. How would I detect and remove them?
How to remove duplicate ranges found within array
|arrays|swift|
null
null
null
null
I'm using the titanic package in R. For my question, I've been given 3 if statements/conditions for the for loop code. This is the question: Use the for loop and if control statements to list the women's non-empty home destinations (home.dest), age 50 or older, who embarked from Southampton (S) on the Titanic. I don't understand how to start the for loop statement where the character i is defined. I'm also trying to skip printing empty cells of the home destination column. This is what I've tried so far: for (i in 1) { if (titanicDataset$age[i] >= 50 & (titanicDataset$embarked[i] == "S") & titanicDataset$sex == "female") {(print(titanicDataset$home.dest[i]))} else if (i == "") next } Error in if (titanicDataset$age[i] >= 50 & (titanicDataset$embarked[i] == : the condition has length > 1
Can anyone help me solve this for loop and if statements code?
|r|for-loop|if-statement|
So it turned out, the issue was actually transitive dependency from the third library. So it wasn't a conflict between debug and main, but a conflict between debug and third party's main version of the library
You're creating your own instance of the `Modal` class. This would be in **addition** to the one that would automatically be instantiated by Flowbite's JavaScript. Instead of creating your own `Modal` instance, consider getting the auto-created instance and calling `.hide()` on that: <!-- begin snippet: js hide: false console: true babel: false --> <!-- language: lang-js --> $('#save-article').click(function() { window .FlowbiteInstances .getInstance('Modal', 'extralarge-modal') ?.hide(); }); <!-- language: lang-html --> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js" integrity="sha512-v2CJ7UaYy4JwqLDIrZUI/4hqeoQieOmAZNXBeQyjo21dadnwR+8ZaIJVT8EE2iyI61OV8e6M8PP2/4hpQINQ/g==" crossorigin="anonymous" referrerpolicy="no-referrer"></script> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/flowbite/2.2.1/flowbite.min.css" integrity="sha512-75dkJxTte+gUDJlkLYrVF5u55sGUQpYuGiDaMtsSq+jmblR1yBv1QgKNi3vDcjo4E2Nk/7LOYV65Cq8gkfQGJw==" crossorigin="anonymous" referrerpolicy="no-referrer" /> <script src="https://cdnjs.cloudflare.com/ajax/libs/flowbite/2.2.1/flowbite.min.js" integrity="sha512-khqZ6XB3gzYqfJvXI2qevflbsTvd+aSpMkOVQUvXKyhRgEdORMefo3nNOvCM8584/mUoq/oBG3Vb3gfGzwQgkw==" crossorigin="anonymous" referrerpolicy="no-referrer"></script> <script src="https://cdn.tailwindcss.com/3.1.4"></script> <button id="model-but" data-modal-target="extralarge-modal" data-modal-toggle="extralarge-modal" class="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded " > Create a News Article </button> <div id="extralarge-modal" tabindex="-1" class="fixed top-0 left-0 right-0 z-50 hidden w-full p-4 overflow-x-hidden overflow-y-auto md:inset-0 h-[calc(100%-1rem)] max-h-full"> <div class="relative w-full max-w-7xl max-h-full"> BUNCH of stuff removed </div> <div class="flex items-center p-4 md:p-5 space-x-3 rtl:space-x-reverse border-t border-gray-200 rounded-b dark:border-gray-600"> <button id="save-article" type="button" class="bunch removed">Save</button> <button data-modal-hide="extralarge-modal" type="button" class="bunch removed">Cancel</button> </div> <div> <!-- end snippet -->
|c|loops|while-loop|
recently updated from Solr 5.* version to Solr 8.11.2, while testing the functionality I came across a "bug" or I'm not even sure what it is, in admin panel MCF row is missing input data. After understanding that it's not working I made a super easy configuration: This is my mapping file: "a" => "b" "d" => "c" This is config in schema.xml: <fieldType name="text_general_ws" class="solr.TextField" positionIncrementGap="100"> <analyzer type="index"> <charFilter class="solr.MappingCharFilterFactory" mapping="mapping.txt"/> <tokenizer class="solr.WhitespaceTokenizerFactory"/> </analyzer> </fieldType> The problem with this is that when I connect to admin panel, choose core, select Analyzer, uncheck the verbose output and select text_general_ws it tokenizes the text okay, the a's are changed to b's and d's are changed to c's, but in the "MCF" row I don't get ANY output, when in 5.* solr I was getting the same text that was in the input but only with changed letters if any was there to change. Would appriciate any help :) [Screenshot of not having ANYTHING in MCF row](https://i.stack.imgur.com/OOv9I.jpg)
Mongoose - Delete document with all array values are greater than specific value
|mongodb|mongoose|mongodb-query|
1. Ensure your CI application/logs file has write permission by the web user. 2. Here are the relevant snippets from your application/config/config.php file: $config['log_threshold'] = 4; $config['log_path'] = ''; 3. Restart your web server (e.g. "/etc/init.d/apache2 stop/start" for many versions of Linux. 4. if you're absolutely certain your log_message() is getting called, and you still don't see any entries in "application/logs", then consider changing log_path to a different path (e.g. /tmp, if only for troubleshooting purposes). 5. However, even "/tmp" isn't a Sure Thing. Look at my post on how Systemd redirects PHP/Apache to a "private temp": https://stackoverflow.com/q/55014399/421195 6. Failing all else, the problem might be SELinux: [CentOS 7 + SELinux + PHP + Apache – cannot write/access file no matter what](https://blog.lysender.com/2015/07/centos-7-selinux-php-apache-cannot-writeaccess-file-no-matter-what/)
{"Voters":[{"Id":20195232,"DisplayName":"Álvaro"}]}
I am using antd `"antd": "^5.15.4"` tree to let user select the folder tree, when the user selected the folder tree, I want to get the full path from the tree root to select node. This is the current code look like: import { TexFileModel } from "@/model/file/TexFileModel"; import { TreeFileType } from "@/model/file/TreeFileType"; import { MoveFileReq } from "@/model/request/file/edit/MoveFileReq"; import { mvFile } from "@/service/file/FileService"; import { useState } from "react"; import Tree from 'antd/lib/tree'; import type { GetProps, TreeDataNode } from 'antd'; import 'antd/lib/tree/style'; import React from "react"; type DirectoryTreeProps = GetProps<typeof Tree.DirectoryTree>; const { DirectoryTree } = Tree; export type TreeFileEditProps = { projectId: string; texFile: TexFileModel; }; const TreeFileMove: React.FC<TreeFileEditProps> = (props: TreeFileEditProps) => { const [texFileModel, setTexFileModel] = useState<TreeDataNode[]>(); const [distPath, setDistPath] = useState<string>(); React.useEffect(() => { let projTree = localStorage.getItem('projTree:' + props.projectId); if (projTree == null) { return; } let treeNodes: TexFileModel[] = JSON.parse(projTree); let projFolderTree = treeNodes.filter((node) => node.file_type == TreeFileType.Folder); const treeData: TreeDataNode[] = convertToTreeDataNode(projFolderTree); setTexFileModel(treeData); }, []); const handleOk = () => { let req: MoveFileReq = { project_id: props.projectId, file_id: props.texFile.file_id, file_name: props.texFile.name, parent_id: props.texFile.parent, file_type: 0, src_path: props.texFile.file_path, dist_path: "" }; mvFile(req); } const onSelect: DirectoryTreeProps['onSelect'] = (keys: React.Key[], info) => { const selectedKey = keys[0]; const selectedNode = info.node; const fullPath = getFullPath(selectedNode); console.log('Full path:', fullPath); }; const getFullPath = (node:TreeDataNode) => { let path = node.title; // it seems no parent in node let parent = node.; while (parent) { path = `${parent.title}/${path}`; parent = parent.parentNode; } return path; }; const onExpand: DirectoryTreeProps['onExpand'] = (keys, info) => { console.log('Trigger Expand', keys, info); }; const convertToTreeDataNode = (data: TexFileModel[]): TreeDataNode[] => { return data.map(item => { const node: TreeDataNode = { key: String(item.id), title: item.name, children: item.children.length > 0 ? convertToTreeDataNode(item.children) : undefined }; return node; }); }; return ( <div className="modal fade" id="moveFileModal" aria-labelledby="moveModalLabel" aria-hidden="true"> <div className="modal-dialog"> <div className="modal-content"> <div className="modal-header"> <h5 className="modal-title" id="moveModalLabel">移动到文件夹</h5> <button type="button" className="btn-close" data-bs-dismiss="modal" aria-label="Close"></button> </div> <div className="modal-body"> <DirectoryTree multiple defaultExpandAll onSelect={onSelect} onExpand={onExpand} treeData={texFileModel} /> </div> <div className="modal-footer"> <button type="button" className="btn btn-secondary" data-bs-dismiss="modal">取消</button> <button type="button" className="btn btn-primary" data-bs-dismiss="modal" onClick={() => { handleOk() }}>确定</button> </div> </div> </div> </div> ); } export default TreeFileMove; is there any way to get the full path of the tree node?
how to get the full path of antd tree
|reactjs|typescript|tree|antd|
You should first find the element corresponding to the button labelled "I'm ready to pump" using and clicks on it to close the dialog which opens n loading the page.Then find the button element that corresponds to the sorting dropdown and click on it.After that Identify all the sorting options shown. Defines the sorting option to be selected as a variable for e.g. "sort: market cap". Iterates through each available sorting option and clicks on the one matching the defined option. Breaks out of the loop once the desired option is selected Below code will work import time from selenium import webdriver from selenium.webdriver.support.wait import WebDriverWait from selenium.webdriver.common.by import By from selenium.webdriver.chrome.service import Service from selenium.webdriver.support import expected_conditions as EC from selenium.common.exceptions import NoSuchElementException from webdriver_manager.chrome import ChromeDriverManager # Initialize WebDriver driver = webdriver.Chrome(service=Service(ChromeDriverManager().install())) driver.implicitly_wait(10) url = "https://www.pump.fun/board" driver.get(url) wait = WebDriverWait(driver, 20) pump = driver.find_element(By.XPATH, "//button[text()[contains(.,'ready to pump')]]") pump.click() button = driver.find_element(By.XPATH, "//span[text()='sort: bump order']/..") wait.until(EC.element_to_be_clickable(button)) button.click() options = driver.find_elements( By.XPATH, "//div[@role='option']/span[contains(text(),'sort')]" ) optionToSelect = "sort: market cap" for option in options: text = option.text if text == optionToSelect: option.click() break driver.quit()
How do I access a subproperty from my .resw file in code?
|xaml|uwp|winui|
Yes you can! Just replace the `.`s with `/`s: ```cpp auto resourceLoader{ Windows::ApplicationModel::Resources::ResourceLoader::GetForCurrentView() }; const auto myString = resourceLoader.GetString(L"Greeting/Text"); ``` ## Further information XAML calls resources that correspond to properties on a control **property identifiers**: whereas `Farewell` can only be loaded manually, from code, `Greeting.Text` corresponds to a property on a control (and is automatically applied to any control with the `x:Uid="Greeting"`. These property paths seem to be encoded as URIs, so you have to switch from `.` to `/` when accessing them in code. MSDN describes that behavior on [Localize strings in your UI and app package manifest#Refer to a string resource identifier from code](https://learn.microsoft.com/en-us/windows/uwp/app-resources/localize-strings-ui-manifest#refer-to-a-string-resource-identifier-from-code): > If a resource name is segmented (it contains "." characters), then replace dots with forward slash ("/") characters in the resource name. Property identifiers, for example, contain dots; so you'd need to do this substitution in order to load one of those from code. > > ```csharp > this.myXAMLTextBlockElement.Text = resourceLoader.GetString("Fare/Well"); // <data name="Fare.Well" ...> ... > ``` > > If in doubt, you can use [MakePri.exe](https://learn.microsoft.com/en-us/windows/uwp/app-resources/makepri-exe-command-options) to dump your app's PRI file. Each resource's uri is shown in the dumped file. > > ```xml > <ResourceMapSubtree name="Fare"><NamedResource name="Well" uri="ms-resource://<GUID>/Resources/Fare/Well">... > ```
I try to restore our airflow env by using dokcer-compose up command. But it didn't work. bellow error coming. I did different method to restore this but didn't any of that. [enter image description here](https://i.stack.imgur.com/Bd57c.png) How restore airflow env
Airflow Failure
|docker-compose|airflow|
null
``` {% for wc in response %} <tr> <td>{{ response.wc }}</td> </tr> {% endfor %} ``` Seems incorrect. **Use as below.** ``` {% for wc in response %} <tr> <td>{{ wc }}</td> </tr> {% endfor %} ``` `wc` is the current value of for loop. You should use that. You can access attributes of this `wc` object like `wc.attribute_name`.
My python program has a busy loop. Within the loop, some delays are calculated in the following fashion: timeout_s: float = args.timeout_s timeout_end_s: float = time.time() + timeout_s while True: now: float = time.time() if now > timeout_end_s: break The `time.time()` function returns a `float` which as for as I know is not an accurate way of storing numbers due to floating-point precision. The current time since epoch is `1710402835`. `float` in python is an IEEE 754 binary64 on "most systems", it is safe to assume I am using only "most systems". Assuming `timeout_s` is relatively small and human comprehensible, between 0.1 seconds and under 10 seconds, and current time is nowadays, how much at `time.time() + timeout_s` calculation accuracy is lost due to using IEEE 754 binary64 to represent the time? When does the moment happen when floating point accuracy will become troubling? In other words, for how long will the calculation accuracy of `time.time() + timeout_s` be within 1 millisecond? In 100 years? In 10000 years? In 10 years? Bottom line, is there a way to calculate this? Is there a way to measure or calculate IEEE 754 binary64 accuracy in specific range of numbers? What is the accuracy of IEEE 754 binary64 around 1710402835?
You don't need to import ANYTHING! Just use "self". Here's how you do this class A: instances = [] def __init__(self): A.instances.append(self) # suggested by @Herrivan print('\n'.join(A.instances)) #this line was suggested by @anvelascos It's this simple. No modules or libraries imported
I'm developing a program with Jupiter Api and [gagliardetto/solana-go](https://github.com/gagliardetto/solana-go). It always returns `invalid transaction: Transaction failed to sanitize accounts offsets correctly` when I submit the transaction. And both two of the Privatekeys(the payer key and the base(order id) key) are used to sign the transaction. I'm developing a program with Jupiter Api and [gagliardetto/solana-go](https://github.com/gagliardetto/solana-go). It always returns `invalid transaction: Transaction failed to sanitize accounts offsets correctly` when I submit the transaction. And both two of the Privatekeys(the payer key and the base(order id) key) are used to sign the transaction. My code like below: ``` func (s *RaydiumSwap) MakeLimitSellOrder(ctx context.Context, tokenMint string, inAmount uint64, outAmount uint64) (*solana.Signature, error) { fromToken := tokenMint toToken := config.WrappedSOL // Unique Order ID of Jup limit order base := solana.NewWallet() resp, err := s.GetTxInfo(inAmount, fromToken, outAmount, toToken, base.PublicKey().String()) if err != nil { return nil, err } tx, err := NewTransactionFromBase64(resp) if err != nil { return nil, err } signers := []solana.PrivateKey{*&s.account, *&base.PrivateKey} _, err = tx.Sign( func(key solana.PublicKey) *solana.PrivateKey { for _, signer := range signers { if signer.PublicKey().Equals(key) { return &signer } } log.Println("Missing Key: ", key) return nil }, ) if err != nil { return nil, err } rawTransaction, err := tx.MarshalBinary() if err != nil { return nil, err } log.Println(tx.MustToBase64()) sig, err := s.clientRPC.SendRawTransactionWithOpts( ctx, rawTransaction, rpc.TransactionOpts{ SkipPreflight: false, PreflightCommitment: rpc.CommitmentFinalized, }, ) if err != nil { return nil, err } return &sig, nil } ``` Doc from Jupiter are like: 5. Deserialize and sign the transaction ``` // deserialize the transaction const transactionBuf = Buffer.from(tx, "base64"); var transaction = VersionedTransaction.deserialize(transactionBuf); // sign the transaction using the required key // for create order, wallet and base key are required. transaction.sign([wallet.payer, base]); ``` 6. Execute the transaction ``` // Execute the transaction const rawTransaction = transaction.serialize(); const txid = await connection.sendRawTransaction(rawTransaction, { skipPreflight: true, maxRetries: 2, }); await connection.confirmTransaction(txid); console.log(`https://solscan.io/tx/${txid}`); ```
invalid transaction: Transaction failed to sanitize accounts offsets correctly
|go|solana|
null
I’ve been trying to do a problem on leetcode(29) and i submit my answer but it gives me this error. Here’s the code: ``` class Solution(object): def divide(self, dividend, divisor): """ :type dividend: int :type divisor: int :rtype: int """ dividend = input() divisor = input() if -2^31 <= dividend and divisor != None and divisor<= 2^31 - 1: result = dividend/divisor else: print("Invalid") exit() print(result) ``` It should give me the int of the division.
I'm going through an exercise of adding type hints through a large codebase, but I'm sometimes seeing that less-than-optimal type hint worsens IDE recommendations: before, the IDE is able to figure out that y['result'] is a string: [![enter image description here](https://i.stack.imgur.com/vlcUE.png)](https://i.stack.imgur.com/vlcUE.png) after, it does not know: [![enter image description here](https://i.stack.imgur.com/tlMER.png)](https://i.stack.imgur.com/tlMER.png) I know I could fix this with a more specific type hint: [![enter image description here](https://i.stack.imgur.com/iW1wT.png)](https://i.stack.imgur.com/iW1wT.png) But in general, is there a way to know if the type hint being added is less specific that what the LSP was able to infer from the code? I've looked to add very detailed type hints to avoid this issue (e.g. subclassing TypeDict), but keen to avoid the effort if the LSP is able to figure things out itself. ### EDIT #1: To clarify, I'm asking if there is a way to warn the user when they are adding a type hint that will worsen the LSP's understanding of the code: We have warnings when the type hints contradict the code: [![enter image description here][1]][1] What I'm looking for is some warning for when the type hint is worse than no type hint at all. [![enter image description here][2]][2] ### EDIT #2: To elaborate further, you can see here that the LSP was easily able to infer a pretty detailed return type. [![enter image description here][3]][3] Which would have been lost if the user added a "bad" type hint. [![enter image description here][4]][4] But I take the overall feedback, maybe this is an ask to the pylance project more than a stack overflow question. [1]: https://i.stack.imgur.com/oL13p.png [2]: https://i.stack.imgur.com/VSgnX.png [3]: https://i.stack.imgur.com/bjwsp.png [4]: https://i.stack.imgur.com/KSW5m.png
If you are in a CI context, you should unlock the mac keychain. You can do so with the following command : `security unlock-keychain -p <password> login.keychain`
In modern computers, most Bluetooth adapters are connected to the computer's USB subsystem. An optional component of Wireshark is USBPcap, which is supplied with `USBPcapCMD.exe`. The `-o` option allows you to save the traffic to a pcap file. ``` C:\Program Files\USBPcap>Usage: USBPcapCMD.exe [options] -h, -?, --help Prints this help. -d <device>, --device <device> USBPcap control device to open. Example: -d \\.\USBPcap1. -o <file>, --output <file> Output .pcap file name. -s <len>, --snaplen <len> Sets snapshot length. -b <len>, --bufferlen <len> Sets internal capture buffer length. Valid range <4096,134217728>. -A, --capture-from-all-devices Captures data from all devices connected to selected Root Hub. --devices <list> Captures data only from devices with addresses present in list. List is comma separated list of values. Example --devices 1,2,3. --inject-descriptors Inject already connected devices descriptors into capture data. -I, --init-non-standard-hwids Initializes NonStandardHWIDs registry key used by USBPcapDriver. This registry key is needed for USB 3.0 capture. ```
How can I prevent word break hyphens from displaying on top of the ellipsis rendered by line-clamp? &__title { hyphens: auto; overflow: hidden; word-break: break-word; display: -webkit-box; -webkit-box-orient: vertical; -moz-box-orient: vertical; -ms-box-orient: vertical; box-orient: vertical; -webkit-line-clamp: 2; -moz-line-clamp: 2; -ms-line-clamp: 2; line-clamp: 2; } Here's how it looks: [![How it looks][1]][1] [1]: https://i.stack.imgur.com/3MFIP.png
TypeError(str(ret) +”is not valid value for expected return type integer”)
|python|equation|
null
i know it's late but this answer can help somebody. I had the same issue but this is how i solved it fs.copy(from, to, function(err) { if(err){ console.log(err); }else{ console.log('copied from -> '+from+' to -> '+to); } }); Thanks!
I would like to outsource the following hungry process in a worker within the loop: ```encoder.addFrame(ctx);``` Unfortunately, I have not been able to do this with node.js worker threads so far. Perhaps I have lacked the right approach so far. In my attempts, I was unable to pass either the encoder or the ctx object to the worker. Maybe my plan doesn't work at all with node.js Worker threads... I don't know. Maybe someone of you has a solution or knows another way to outsource the process in the background? Here is the complete code: generate: function (cb) { const GIFEncoder = require('gif-encoder-2'); const encoder = new GIFEncoder( Number(200), Number(200), 'neuquant', true); encoder.start(); encoder.setRepeat( 0 ); encoder.setDelay(1000); encoder.setQuality(10); const { createCanvas, registerFont } = require('canvas'); const canvas = createCanvas( Number(200), Number(200) ); const ctx = canvas.getContext('2d'); for (let i = 0; i < 10; i++) { ctx.beginPath(); ctx.moveTo(0, 0); ctx.lineTo(200, 0); ctx.lineTo(200, 200); ctx.lineTo(0, 200); ctx.closePath(); ctx.fillStyle = 'blue'; ctx.fill(); ctx.fillStyle = 'white'; ctx.font = ['72px', 'Open Sans'].join(' '); ctx.textAlign = 'center'; ctx.textBaseline = 'middle'; ctx.fillText(i.toString(), 100, 84 + ctx.measureText(i.toString()).actualBoundingBoxAscent / 2); encoder.addFrame(ctx); // Process this in a worker! } encoder.finish(); return encoder.out.getData(); }
I want to generate html table from a complex nested json,in PHP code here are details.. here is my json and php code ``` $data = json_decode($jsonData, true); function generateTable($data) { $html = '<table border="1">'; foreach ($data as $item) { if(is_array($item['node']['value'])) { $rowspan = count($item['node']['value']); } $html .= '<tr rowspan='.$rowspan.'>'; $html .= '<tr>'; $html .= '<th>' . $item['node']['key'] . '</th>'; $html .= '<td>'; if (isset($item['node']['value']) && is_array($item['node']['value'])) { $html .= generateTable($item['node']['value']); } else { $html .= $item['node']['value']; } $html .= '</td>'; $html .= '</tr>'; } $html .= '</table>'; return $html; } echo generateTable($data); ``` ``` [ { "node":{ "key":"header", "value":[ { "node":{ "key":"msg_id", "value":"236001" }, "type":"string", "minLength":1, "maxLength":12, "desc":"Message ID, this field should be unique id for each Api call. This will be generated from client side. \n\n If the same message ID is used the system will decline the API call with Error Description “Duplicate Message ID” ", "req":"required" }, { "node":{ "key":"msg_type", "value":"TRANSACTION" }, "type":"string", "minLength":1, "maxLength":12, "desc":"Message Type – This can have either “TRANSACTION” or “ENQUIRY” \n\n As for this API the value expected is “TRANSACTION” ", "req":"required" }, { "node":{ "key":"msg_function", "value":"REQ_ACCOUNT_CREATE" }, "type":"string", "minLength":1, "maxLength":50, "desc":"Message functions: Should be “REQ_ACCOUNT_CREATE” ", "req":"required" }, { "node":{ "key":"src_application", "value":"IVR" }, "type":"string", "minLength":1, "maxLength":10, "desc":"Source Application: This is a free Text and the client can populate the source system from where the API is Initiated \n\n Example: IVR, IB, MB \n\n No Validations of these are kept at Network Systems", "req":"required" }, { "node":{ "key":"target_application", "value":"WAY4" }, "type":"string", "minLength":1, "maxLength":10, "desc":"The target_application can hold any value from FI side, this can be used by FI to check the target system of the API call", "req":"required" }, { "node":{ "key":"timestamp", "value":"2020-07-20T10:49:02.366+04:00" }, "type":"string", "minLength":1, "maxLength":30, "desc":"Timestamp of the request - Format YYYY-MM-DDtHH:MM:SS.SSS+04:00", "req":"required" }, { "node":{ "key":"bank_id", "value":"NIC" }, "type":"string", "minLength":1, "maxLength":4, "desc":"Bank Id is Unique Id 4 digit code for each client and the same will be provided once the client setup is completed in our core system. \n\n For sandbox testing – Please use “NIC” ", "req":"required" } ] }, "type":"object", "minLength":null, "maxLength":null, "desc":"", "req":"false" }, { "node":{ "key":"body", "value":[ { "node":{ "key":"customer_id", "value":"100000027" }, "type":"string", "minLength":1, "maxLength":20, "desc":"Customer ID: Customer Identification number \n\n This should be a unique number", "req":"required" }, { "node":{ "key":"card_type", "value":"CREDIT" }, "type":"string", "minLength":1, "maxLength":7, "desc":"Informative value to the request, does not have any functional impact, the value can be PREPAID/CREDIT/DEBIT", "req":"required" }, { "node":{ "key":"account", "value":[ { "node":{ "key":"customer_id", "value":"100000027" }, "type":"string", "minLength":1, "maxLength":20, "desc":"Customer ID: Customer Identification number \n\n This should be a unique number", "req":"required" }, { "node":{ "key":"account_number", "value":"0009821110000000008" }, "type":"string", "minLength":1, "maxLength":64, "desc":"Account number, if not provided CMS will generate it", "req":"false" }, { "node":{ "key":"parent_account_number", "value":"0009821110000000008" }, "type":"string", "minLength":1, "maxLength":64, "desc":"Parent account number - Applicable only for Corporate products", "req":"false" }, { "node":{ "key":"branch_code", "value":"982" }, "type":"string", "minLength":1, "maxLength":10, "desc":"Branch Code, if no branches are used, the code must be same as bank_code", "req":"required" }, { "node":{ "key":"product_code", "value":"982_AED_002_A" }, "type":"string", "minLength":1, "maxLength":32, "desc":"Product code, this code is generated by CMS after creating the product, this code is FI spesific code 982_AED_002_A is just used as an example in Sandbox", "req":"required" }, { "node":{ "key":"billing_day", "value":"" }, "type":"string", "minLength":1, "maxLength":10, "desc":"Billing date, applicable only for credit card products", "req":"false" }, { "node":{ "key":"currency", "value":"AED" }, "type":"string", "minLength":1, "maxLength":3, "desc":"Informative value to the request, does not have any functional impact, the currency will be taken from the product", "req":"required" }, { "node":{ "key":"limit", "value":[ { "node":{ "key":"type", "value":"FIN_LIMIT" }, "type":"string", "minLength":1, "maxLength":32, "desc":"Credit limit type - applicable only for credit card products", "req":"false" }, { "node":{ "key":"currency", "value":"SAR" }, "type":"string", "minLength":1, "maxLength":3, "desc":"Credit limit currency - applicable only for credit card products", "req":"false" }, { "node":{ "key":"value", "value":"55000" }, "type":"string", "minLength":1, "maxLength":20, "desc":"Credit limit value - applicable only for credit card products", "req":"false" } ] }, "type":"object", "minLength":null, "maxLength":null, "desc":"", "req":"false" }, { "node":{ "key":"custom_fields", "value":[ { "node":{ "key":"key", "value":"contract_idt_scheme" }, "type":"string", "minLength":1, "maxLength":20, "desc":"Custom Tag. Example: contract_idt_scheme", "req":"false" }, { "node":{ "key":"value", "value":"CONTRACT_NUMBER" }, "type":"string", "minLength":1, "maxLength":128, "desc":"Tag value. Example: CONTRACT_NUMBER", "req":"false" } ] }, "type":"array", "minLength":null, "maxLength":null, "desc":"", "req":"false" } ] }, "type":"object", "minLength":null, "maxLength":null, "desc":"", "req":"required" } ] }, "type":"object", "minLength":null, "maxLength":null, "desc":"", "req":"false" } ] ``` and i want this type of out put, like in image. main issue is rowspan and colspan, i can calculate rowspan but having problem in colspan, i need some recursive php function, this one is creating table in each <td> i want <tr> like in image.... JSON can go any unlimited level.... [enter image description here](https://i.stack.imgur.com/P8gbu.png) i am expecting this result
I'm trying to make my own Brick Breaker game using SDL library and I'm having some issues with dealing the collision resolution and ball bouncing when it comes to the bouncing of the paddle. I'm calculating collision angle based on the collision point between ball and paddle and calculating balls' velocity direction based on that angle. The issue I'm experiencing is after the collision with the paddle, ball doesn't change it's Y direction, instead just keeps going down and hitting the paddle. It continues to do that until eventually "slides" of the paddle. I don't think my math is wrong here (although it could easily be), but I simply don't know what the issue is or how to fix it. This is the code that is responsible for collision detection and calculating angle and direction. ``` void Ball::CollisionWithPaddle(Paddle*& paddle) { if (CollisionManager::GetInstance()->Collision(GetHitbox(), paddle->GetHitbox())) { double collisionAngle = CalculateCollisionAngle(paddle->GetHitbox()); Vector2Df newVelocityDirection = CalculateNewVelocityDirection(collisionAngle); velocity = newVelocityDirection * velocity.Magnitude(); AdjustBallPosition(paddle); } } double Ball::CalculateCollisionAngle(const SDL_Rect& paddle) { double collisionPointX = transform->X + width / static_cast<double>(2); double collisionPointY = transform->Y + height / static_cast<double>(2); double relativeX = collisionPointX - (paddle.x + paddle.w / static_cast<double>(2)); double relativeY = collisionPointY - (paddle.y + paddle.h / static_cast<double>(2)); double collisionAngle = atan2(relativeY, relativeX); collisionAngle = fmod((collisionAngle + 180), 360) - 180; return collisionAngle; } Vector2Df Ball::CalculateNewVelocityDirection(double collisionAngle) { // Calculate direction of the new velocity based on the collision angle double newVelocityX = std::cos(collisionAngle); double newVelocityY = -std::sin(collisionAngle); Vector2Df newVelocityDirection(newVelocityX, newVelocityY); return newVelocityDirection.Normalize(); } void Ball::AdjustBallPosition(Paddle* paddle) { transform->Y = paddle->GetHitbox().y - height; } ``` This is the code where I'm simply updating the position of the ball with the current velocity. ``` void Ball::Update() { transform->X += velocity.X * Engine::GetInstance()->GetDeltaTime(); transform->Y += velocity.Y * Engine::GetInstance()->GetDeltaTime(); rec.x = transform->X; rec.y = transform->Y; } ```
Solr 8.11.2 Mapping Char Filter gives no output in admin panel
|solr|
null
if you trying to execute it in CMD, make sure to you specify `-providerpath` correctly.
I wonder what is the correct way of logging out user. In my code i created in `Navigation` context that provides `logout()` function. But by doing this i am able to reset AsyncStorage and do request to server to expire token. How can I navigate to loginscreen ? Is it a correct implementation ? If not how do you do this ? Thanks for replies. ``` export const Navigation = () => { const contextValue: AuthContextProps | undefined = React.useContext(AuthContext); if(contextValue == undefined){ console.log("Undefinied context value from index.tsx"); } const handleSignOut = () => { contextValue?.logout(); } return ( <NavigationContainer> <Stack.Navigator> {contextValue?.splashLoading ? ( <Stack.Screen name='MainPage' component={MainPageScreen} options={{headerShown: false}} /> ) : contextValue?.userInfo.access_token ? ( <Stack.Group screenOptions={{ headerShown: false }}> <Stack.Screen name="Navigate" options={{title: "InnerNavigation"}}> {() => <InnerNavigation handleSignOut={handleSignOut} />} </Stack.Screen> </Stack.Group> ) : ( <Stack.Group screenOptions={{ headerShown: false }}> <Stack.Screen name="Welcome" component={WelcomeScreen}/> <Stack.Screen name='Login' component={LoginScreen}/> <Stack.Screen name="Register"component={RegisterScreen}/> <Stack.Screen name="RecoverPassword" component={RecoverPasswordScreen}/> <Stack.Screen name="PersonalData" component={PersonalDataScreen}/> </Stack.Group> )} </Stack.Navigator> </NavigationContainer> ); }; ```
How correctly logout user in React Native App?
|react-native|
I have grouped/counted and joined two data frames on column 'Amzius' and got one data frame df_joined. Now I try to use it in combo chart and have a problem: I found 2 headers instead of 3. I miss column 'Amzius' (key column). Print shows strange things: [![enter image description here][1]][1] Response to command `df_joined.columns.values` Does not give column 'Amzius'. I see only two columns: 'Atlygis' and 'Kaina'. Here is my code: df_grouped = df.groupby('Amzius')['Atlygis'].mean() df_grouped1 = df.groupby('Amzius')['Kaina'].mean() df_joined = pd.concat([df_grouped, df_grouped1],axis = 1, join='inner') print(df_joined) print(df_joined.columns.values) How can I fix it? [1]: https://i.stack.imgur.com/ixYvg.png
Wrong header of joined dataframes
|python|pandas|matplotlib|
|python|pandas|
So my problem is, that I have a React JS app that has a Sidebar with some tabs that the users can navigate through. Each one of these tabs makes a fetch request to Firebase Firestore where my data is stored (and if anyone here worked with Firebase you know it can become quite expensive if you don't handle the reads and all the stuff properly). So, my problem is, that every time the user navigates through the tabs, the component is unmounted and mounted again, and this triggers another request to firebase increasing the number of reads of my project a lot. So what I want to achieve is: I want to mount all the components of the sidebar once, and when the user navigates through them i don't want to unmount any of them, is there a way to achieve this? Here is my main.tsx file ``` import ReactDOM from 'react-dom/client' import App from './App.tsx' import './index.css' import { AuthContextProvider } from './context/AuthContextProvider.tsx' import { SubscriptionProvider } from './context/SubscriptionContext.tsx' ReactDOM.createRoot(document.getElementById('root')!).render( <AuthContextProvider> <SubscriptionProvider> <App /> </SubscriptionProvider> </AuthContextProvider > ) ``` App.tsx ``` import './App.css' import { BrowserRouter as Router, Route, Routes } from 'react-router-dom'; import { isMobile } from 'react-device-detect'; import Sidebar from './components/component/sidebarWrapper' import Gerador from './components/pages/gerador/Gerador' import Home from './components/pages/Home/Home'; import Logon from './components/pages/logon/Logon' import Login from './components/pages/logon/Login' import Analise from './components/pages/analise/Analise' import PasswordRecovery from './components/pages/recover/Recover'; import Crm from './components/pages/crm/Crm' import UserConfig from './components/pages/userconfig/UserConfig' // import Profile from './components/pages/profile/Profile'; import Error from './components/pages/errorpage/error' import { ThemeProvider } from "@/components/component/theme-provider" import { useAuthContext } from './hooks/useAuthContext'; import { Loader } from './components/component/loader'; import { useState, useEffect } from 'react'; import Assinatura from './components/pages/billing/Assinatura'; import Templates from './components/pages/templates/Templates'; import { Toaster } from './components/ui/toaster'; import IA from './components/pages/IA/IA'; import { useSubscriptionContext } from './hooks/useSubscriptionContext'; import { MobileHome } from './components/component/MobileHome'; function App() { const { user, authIsReady } = useAuthContext() const { subscriptionDoc } = useSubscriptionContext() const [authReady, setAuthReady] = useState(false) useEffect(() => { // Esperar até que a autenticação esteja pronta if (authIsReady) { setAuthReady(true); } }, [authIsReady]); if (!authReady) { // Renderizar um componente de carregamento enquanto a autenticação está sendo verificada return <Loader />; } return ( <ThemeProvider defaultTheme="dark" storageKey="vite-ui-theme"> <Toaster /> <Sidebar /> <Router> {user ? ( <> <Routes> <Route path="/home" element={isMobile ? <MobileHome /> : <Home />} /> {subscriptionDoc?.plan !== undefined ? ( subscriptionDoc?.status !== "ACTIVE" ? ( <Route path="/gerador" element={<Home />} /> ) : ( <Route path="/gerador" element={<Gerador />} /> ) ) : ( <Route path="/gerador" element={<Gerador />} /> )} <Route path="/treine-sua-ia" element={<IA />} /> <Route path="/analise" element={<Analise />} /> <Route path="/crm" element={<Crm />} /> <Route path="/assinatura" element={<Assinatura />} /> <Route path="/recover" element={<PasswordRecovery />} /> {subscriptionDoc?.status === "ACTIVE" ? ( <Route path="/templates" element={<Templates />} /> ) : ( <Route path="/templates" element={<Home />} /> ) } {/* <Route path="/perfil" element={<Profile />} /> */} {/* user config routes */} <Route path="/userconfig" element={<UserConfig />} /> <Route path="/*" element={isMobile ? <MobileHome /> : <Home />} /> </Routes> </> ) : ( <Routes> <Route path="/entrar" element={<Login />} /> <Route path="/criar-conta" element={<Logon />} /> <Route path="/recover" element={<PasswordRecovery />} /> <Route path="/error" element={<Error />} /> <Route path="/*" element={<Logon />} /> </Routes> ) } </Router> </ThemeProvider> ) } export default App ``` Sidebar.tsx ``` return ( <div className='box '> <aside className="flex code-hook-scroll bg-background flex-col w-64 h-screen px-5 md:py-4 lg:py-8 overflow-y-auto border-r rtl:border-r-0 rtl:border-l dark:border-gray-700"> <Link to="#" className='relative'> <div className="flex w-22 h-16 rounded-md bg-logo"> <img className="w-40 logo-home -translate-y-12 -translate-x-6" src={logoPath} alt="Logo da empresa escrito 'BuildX'" /> </div> </Link> <div className="flex flex-col justify-between flex-1 mt-10"> <nav className="flex-1 -mx-3 space-y-3 "> {/* <div className="relative mx-3 mb-8"> <span className="absolute inset-y-0 left-0 flex items-center pl-3"> <svg className="w-5 h-5 text-gray-400" viewBox="0 0 24 24" fill="none"> <path d="M21 21L15 15M17 10C17 13.866 13.866 17 10 17C6.13401 17 3 13.866 3 10C3 6.13401 6.13401 3 10 3C13.866 3 17 6.13401 17 10Z" stroke="currentColor" strokeWidth="2" ></path> </svg> </span> <Input type="text" className="w-full py-1.5 pl-10 pr-4 text-gray-700 bg-white border rounded-md dark:bg-gray-900 dark:text-gray-300 dark:border-gray-600" placeholder={`Pesquisar (${searchTerm})`} value={searchTerm} onChange={handleSearchChange} // Adicionando a função de callback para a mudança no input /> </div> */} <Link to="/home" className="flex items-center px-3 py-2 text-gray-600 transition-colors duration-300 transform rounded-lg dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-800 dark:hover:text-gray-200 hover:text-gray-700" > <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" strokeWidth="1.5" stroke="currentColor" className="w-5 h-5"> <path strokeLinecap="round" d="M2.25 12l8.954-8.955c.44-.439 1.152-.439 1.591 0L21.75 12M4.5 9.75v10.125c0 .621.504 1.125 1.125 1.125H9.75v-4.875c0-.621.504-1.125 1.125-1.125h2.25c.621 0 1.125.504 1.125 1.125V21h4.125c.621 0 1.125-.504 1.125-1.125V9.75M8.25 21h8.25" /> </svg> <span className="mx-2 text-sm font-medium">Home</span> </Link> {/* <Link to="/gerador" className="flex items-center px-3 py-2 text-gray-600 transition-colors duration-300 transform rounded-lg dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-800 dark:hover:text-gray-200 hover:text-gray-700" > <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" strokeWidth="1.5" stroke="currentColor" className="w-5 h-5"> <path strokeLinecap="round" d="M3.75 3v11.25A2.25 2.25 0 006 16.5h2.25M3.75 3h-1.5m1.5 0h16.5m0 0h1.5m-1.5 0v11.25A2.25 2.25 0 0118 16.5h-2.25m-7.5 0h7.5m-7.5 0l-1 3m8.5-3l1 3m0 0l.5 1.5m-.5-1.5h-9.5m0 0l-.5 1.5m.75-9l3-3 2.148 2.148A12.061 12.061 0 0116.5 7.605" /> </svg> <span className="mx-2 text-sm font-medium">Gerar componentes</span> </Link> */} <Link onClick={(e) => { // Verificar se o texto é diferente de "Em breve" if (subscriptionDoc?.plan !== undefined) { if (subscriptionDoc?.status !== 'ACTIVE') { e.preventDefault(); // Prevenir a ação padrão do link toast({ variant: "destructive", title: "Conta não permitida.", description: `Sua conta não está ATIVA, o gerador esta disponível apenas para assinantes.`, action: <ToastAction onClick={goToUpgrade} altText="Recarregar">Fazer upgrade</ToastAction>, }); } } }} to="/gerador" className="flex items-center px-3 py-2 text-gray-600 transition-colors duration-300 transform rounded-lg dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-800 dark:hover:text-gray-200 hover:text-gray-700" > <div className='flex gap-16 items-center whitespace-nowrap'> <div className='flex'> <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" strokeWidth="1.5" stroke="currentColor" className="w-5 h-5"> <path strokeLinecap="round" d="M3.75 3v11.25A2.25 2.25 0 006 16.5h2.25M3.75 3h-1.5m1.5 0h16.5m0 0h1.5m-1.5 0v11.25A2.25 2.25 0 0118 16.5h-2.25m-7.5 0h7.5m-7.5 0l-1 3m8.5-3l1 3m0 0l.5 1.5m-.5-1.5h-9.5m0 0l-.5 1.5m.75-9l3-3 2.148 2.148A12.061 12.061 0 0116.5 7.605" /> </svg> <span className="mx-2 text-sm font-medium">BUILD<span className='font-bold text-primary'>X</span> Gen &#8482;</span> </div> {subscriptionDoc?.plan !== undefined ? ( subscriptionDoc?.status !== "ACTIVE" && <Lock className='w-4 h-4 text-red-600' /> ) : ( '' )} </div> </Link> <Link to="/crm" className="flex items-center px-3 py-2 text-gray-600 transition-colors duration-300 transform rounded-lg dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-800 dark:hover:text-gray-200 hover:text-gray-700" > <svg className='w-5 h-5' viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg"><g id="SVGRepo_bgCarrier" strokeWidth="1.5"></g><g id="SVGRepo_tracerCarrier" strokeLinecap="round" ></g><g id="SVGRepo_iconCarrier"> <path d="M12 4H10C6.22876 4 4.34315 4 3.17157 5.17157C2 6.34315 2 8.22876 2 12C2 15.7712 2 17.6569 3.17157 18.8284C4.34315 20 6.22876 20 10 20H12M15 4.00093C18.1143 4.01004 19.7653 4.10848 20.8284 5.17157C22 6.34315 22 8.22876 22 12C22 15.7712 22 17.6569 20.8284 18.8284C19.7653 19.8915 18.1143 19.99 15 19.9991" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round"></path> <path d="M9 12C9 12.5523 8.55228 13 8 13C7.44772 13 7 12.5523 7 12C7 11.4477 7.44772 11 8 11C8.55228 11 9 11.4477 9 12Z" fill="currentColor"></path> <path d="M13 12C13 12.5523 12.5523 13 12 13C11.4477 13 11 12.5523 11 12C11 11.4477 11.4477 11 12 11C12.5523 11 13 11.4477 13 12Z" fill="currentColor"></path> <path d="M15 2V22" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round"></path> </g></svg> <span className="mx-2 text-sm font-medium">Gestão</span> </Link> <Link to="/treine-sua-ia" className='flex items-center px-3 py-2 text-gray-600 transition-colors duration-300 transform rounded-lg dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-800 dark:hover:text-gray-200 hover:text-gray-700 ' onMouseEnter={() => setTreinarText('Em breve')} onMouseLeave={() => setTreinarText('Treinar IA (Scrap docs)')} onClick={(e) => { // Verificar se o texto é diferente de "Em breve" if (treinarText === 'Em breve') { e.preventDefault(); // Prevenir a ação padrão do link // Adicionar lógica adicional, se necessário } }} > <BrainCog className='w-5 h-5' /> <span className="mx-2 text-sm font-medium">{treinarText}</span> </Link> <Link aria-disabled='true' to="/analise" className="flex items-center px-3 py-2 text-gray-600 transition-colors duration-300 transform rounded-lg dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-800 dark:hover:text-gray-200 hover:text-gray-700" onMouseEnter={() => setAnaliseText('Em breve')} onMouseLeave={() => setAnaliseText('Análise com IA')} onClick={(e) => { // Verificar se o texto é diferente de "Em breve" if (analiseText === 'Em breve') { e.preventDefault(); // Prevenir a ação padrão do link // Adicionar lógica adicional, se necessário } }} > <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" strokeWidth="1.5" stroke="currentColor" className="w-5 h-5"> <path strokeLinecap="round" d="M10.5 6a7.5 7.5 0 107.5 7.5h-7.5V6z" /> <path strokeLinecap="round" d="M13.5 10.5H21A7.5 7.5 0 0013.5 3v7.5z" /> </svg> <span className="mx-2 text-sm font-medium">{analiseText}</span> </Link> <Link onClick={(e) => { // Verificar se o texto é diferente de "Em breve" if (subscriptionDoc?.status !== 'ACTIVE') { e.preventDefault(); // Prevenir a ação padrão do link toast({ variant: "destructive", title: "Conta não permitida.", description: `Sua conta não está ATIVA, os templates estão disponíveis apenas para assinantes.`, action: <ToastAction onClick={goToUpgrade} altText="Recarregar">Fazer upgrade</ToastAction>, }); } }} to="/templates" className="flex items-center px-3 py-2 text-gray-600 transition-colors duration-300 transform rounded-lg dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-800 dark:hover:text-gray-200 hover:text-gray-700" > <div className='flex gap-24 items-center'> <div className='flex'> <svg className='w-5 h-5' viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg" stroke="currentColor"><g id="SVGRepo_bgCarrier" strokeWidth="1.5"></g><g id="SVGRepo_tracerCarrier" strokeLinecap="round"></g><g id="SVGRepo_iconCarrier"> <path d="M4.97883 9.68508C2.99294 8.89073 2 8.49355 2 8C2 7.50645 2.99294 7.10927 4.97883 6.31492L7.7873 5.19153C9.77318 4.39718 10.7661 4 12 4C13.2339 4 14.2268 4.39718 16.2127 5.19153L19.0212 6.31492C21.0071 7.10927 22 7.50645 22 8C22 8.49355 21.0071 8.89073 19.0212 9.68508L16.2127 10.8085C14.2268 11.6028 13.2339 12 12 12C10.7661 12 9.77318 11.6028 7.7873 10.8085L4.97883 9.68508Z" stroke="currentColor" strokeWidth="1.5"></path> <path d="M5.76613 10L4.97883 10.3149C2.99294 11.1093 2 11.5065 2 12C2 12.4935 2.99294 12.8907 4.97883 13.6851L7.7873 14.8085C9.77318 15.6028 10.7661 16 12 16C13.2339 16 14.2268 15.6028 16.2127 14.8085L19.0212 13.6851C21.0071 12.8907 22 12.4935 22 12C22 11.5065 21.0071 11.1093 19.0212 10.3149L18.2339 10" stroke="currentColor" strokeWidth="1.5"></path> <path d="M5.76613 14L4.97883 14.3149C2.99294 15.1093 2 15.5065 2 16C2 16.4935 2.99294 16.8907 4.97883 17.6851L7.7873 18.8085C9.77318 19.6028 10.7661 20 12 20C13.2339 20 14.2268 19.6028 16.2127 18.8085L19.0212 17.6851C21.0071 16.8907 22 16.4935 22 16C22 15.5065 21.0071 15.1093 19.0212 14.3149L18.2339 14" stroke="currentColor" strokeWidth="1.5"></path> </g></svg> <span className="mx-2 text-sm font-medium">Templates</span> </div> {subscriptionDoc?.status !== "ACTIVE" && <Lock className='w-4 h-4 text-red-600' />} </div> </Link> </nav> <div className="md:mt-0 lg:mt-6"> <div className="p-3 bg-gray-100 rounded-lg dark:bg-gray-800"> <h2 className="text-sm font-medium text-gray-800 dark:text-white">Novidade em breve! Template de APP</h2> <p className="mt-1 text-xs text-gray-500 dark:text-gray-400 " title='Template completo com as funcionalidades do Firebase. Pronto para adcionar as funcionalidade do seus Saas e começar a rodar.'> Template completo com as funcionalidades do Firebase. Pronto para adcionar as funcionalidade do seus Saas e começar a rodar. </p> <img className="object-cover w-full md:h-20 lg:h-fit mt-2 rounded-lg" src={Feature}></img> </div> <div className="flex items-center justify-between mt-6"> {user ? ( <a className="flex items-center gap-x-2"> <img referrerPolicy="no-referrer" className="object-cover rounded-full h-7 w-7 dark:bg-muted" src={profileImage || user.photoURL || userIconDefault} // Use profileImage se existir, caso contrário, use o valor padrão alt="Imagem de perfil do usuário" /> <span className="text-sm font-medium text-gray-700 dark:text-gray-200"> {user.displayName} </span> </a> ) : ( <p className="text-sm font-medium text-gray-700 dark:text-gray-200">Usuário não autenticado</p> )} <Link onClick={async () => { await logout(); }} to="/criar-conta" className="text-gray-500 transition-colors duration-200 rotate-180 dark:text-gray-400 rtl:rotate-0 hover:text-blue-500 dark:hover:text-blue-400"> <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" strokeWidth="1.5" stroke="currentColor" className="w-5 h-5"> <path strokeLinecap="round" d="M15.75 9V5.25A2.25 2.25 0 0013.5 3h-6a2.25 2.25 0 00-2.25 2.25v13.5A2.25 2.25 0 007.5 21h6a2.25 2.25 0 002.25-2.25V15M12 9l-3 3m0 0l3 3m-3-3h12.75" /> </svg> </Link> </div> </div> </div> </aside> </div> ) } export default Sidebar ``` Home.tsx ``` const Home = () => { return ( <Sidebar> <> <div className='flex '> <ModeToggle></ModeToggle> <ThemeToggle /> <div className='w-full p-8 pb-0 '> <CardsMetrics></CardsMetrics> <OnBoardSteps /> <GridHome></GridHome> {/* <TableHistory/> */} </div> </div> </> </Sidebar> ) } export default Home ``` Here in home.tsx, inside it i have the CardsMetrics component that makes the call to firestore, below is the code that makes the call: ``` const { documents: historico } = useSubcollectionHistory({ coll: "users", docId: `${userID}`, subcoll: "historico", _limit: 0, }); ``` the function useSubcollectionHistory is a hook i created to handle the multiple uses of this call in different components to avoid rewriting all the call in different locations, below is the hook: useSubcollectionHistory.tsx ``` export const useSubcollectionHistory = ({ coll, docId, subcoll, _query, _orderBy, _limit, }: UseSubcollectionProps) => { const [documents, setDocuments] = useState<DocumentData[] | null>(null); const [error, setError] = useState<string | null>(null); const q = useRef(_query).current; const ob = useRef(_orderBy).current; useEffect(() => { // Create a reference to the subcollection let ref: CollectionReference<DocumentData> | Query<DocumentData> = collection( db, `${coll}/${docId}/${subcoll}` ); if (q) { ref = query(ref as CollectionReference<DocumentData>, where(q[0], q[1], q[2])); } if (ob) { ref = query(ref, orderBy(ob[0], ob[1])); } if (_limit) { ref = query(ref, limit(_limit)); } const unsub: Unsubscribe = onSnapshot( ref, (snapshot) => { const results: DocumentData[] = []; snapshot.forEach((doc) => { results.push({ ...(doc.data() as DocumentData), id: doc.id }); }); setDocuments(results); setError(null); }, (error) => { setError("Could not fetch the documents." + error); } ); // Cleanup return () => {unsub()}; }, [coll, docId, subcoll, q, ob, _limit]); return { documents, error }; }; ``` I tried using cache for this, it worked but killed the Firebase snapshot listener to keep track of real-time changes, so the fetch was made only once but the user was forced to refresh the page by himself if he wanted to see the change he made. Also tried using the componentWillMount and componentWillUnmount to keep track of the component state but this didn't work as well (not sure if I implemented it wrong or not).
null
Supplemental to [Jannis's answer][1], which was: ```css #txa_movieEditComment {-fx-background: #191919;} ``` I believe what you did works for you because `-fx-background` is an undocumented [looked-up-color][2] in the `modena.css` style sheet which is used for theming the styles. When you set it on a parent node, it will be inherited in child nodes, so any child node that also has colors derived from `-fx-background` (such as scroll pane content that is inside a text area) automatically changes color as well. From the documentation on looked-up-colors: > With looked-up colors you can refer to any other color property that is set on the current node or any of its parents. This is a very powerful feature, as it allows a generic palette of colors to be specified on the scene then used thoughout the application. If you want to change one of those palette colors you can do so at any level in the scene tree and it will affect that node and all its decendents. Looked-up colors are not looked up until they are applied, so they are live and react to any style changes that might occur, such as replacing a palette color at runtime with the "style" property on a node. By contrast, this does not work: ```css #txa_movieEditComment {-fx-background-color: #191919;} ``` The reason is that `-fx-background-color` is a non-inherited CSS property, not a looked-up-color. CSS properties *can* [inherit](https://openjfx.io/javadoc/21/javafx.graphics/javafx/scene/doc-files/cssref.html#introinheritance) so that when you set them in a container node, nodes contained by it also inherit the property setting. But, by default, very few CSS properties are inherited (normally just font, text alignment, and cursor settings). When you set a non-inherited CSS property via a CSS style, it will only apply to the node exactly matching the CSS selector and not to any of the nodes contained by that node. [1]: https://stackoverflow.com/a/78232314/1155209 [2]: https://openjfx.io/javadoc/21/javafx.graphics/javafx/scene/doc-files/cssref.html#typecolor