instruction
stringlengths
0
30k
I am using glove embeddings in embeddings layer of LSTM. I wrote a function to build model as below: def build_model(hp): model = keras.Sequential() model.add(Embedding(input_dim=vocab_size, # Size of the vocabulary output_dim=EMBEDDING_DIM, # Length of the vector for each word weights=[embedding_matrix], input_length=MAX_SEQUENCE_LENGTH, trainable=False)) # model.add(Embedding(input_dim=vocab_size, # Size of the vocabulary # output_dim=50, # Length of the vector for each word # input_length = MAX_SEQUENCE_LENGTH)) # Maximum length of a sequence model.add(SpatialDropout1D(hp.Choice('sdropout_', values=[0.2, 0.3, 0.4, 0.5, 0.6]) ) ) model.add(LSTM(hp.Int('units_', min_value=30, max_value=70, step=10), kernel_initializer='random_normal', dropout=0.5, recurrent_dropout=0.5)) counter = 0 for i in range(hp.Int('num_layers', 1, 5)): if counter == 0: model.add(layers.Dense(units=hp.Int('units_', min_value=16, max_value=512, step=32), kernel_initializer='random_normal', #kernel_initializer=hp.Choice('kernel_initializer_', ['random_normal', 'random_uniform', 'zeros']), #bias_initializer=hp.Choice('bias_initializer_', ['random_normal', 'random_uniform', 'zeros']), input_shape=y_train.shape, #kernel_regularizer=regularizers.l2(0.03), kernel_regularizer=keras.regularizers.l2(hp.Choice('l2_value', values = [1e-2, 3e-3, 2e-3, 1e-3, 1e-4])), #kernel_regularizer=regularizers.L1L2(l1=1e-5, l2=1e-4), #bias_regularizer=regularizers.L2(1e-4), #activity_regularizer=regularizers.L2(1e-5), activation=hp.Choice('dense_activation_' + str(i), values=['relu', 'tanh', 'sigmoid'], default='relu') ) ) model.add(layers.Dropout(rate=hp.Float('dropout_' + str(i), min_value=0.0, max_value=0.6, default=0.25, step=0.05) ) ) else: model.add(layers.Dense(units=hp.Int('units_' + str(i), min_value=12, max_value=512, step=32), kernel_initializer='random_normal', #kernel_initializer=hp.Choice('kernel_initializer_', ['random_normal', 'random_uniform', 'zeros']), #bias_initializer=hp.Choice('bias_initializer_', ['random_normal', 'random_uniform', 'zeros']), #kernel_regularizer=regularizers.l2(0.03), kernel_regularizer=keras.regularizers.l2(hp.Choice('l2_value', values = [1e-2, 3e-3, 2e-3, 1e-3, 1e-4])), #kernel_regularizer=regularizers.L1L2(l1=1e-5, l2=1e-4), #bias_regularizer=regularizers.L2(1e-4), #activity_regularizer=regularizers.L2(1e-5), activation=hp.Choice('dense_activation_' + str(i), values=['relu', 'tanh', 'sigmoid'], default='relu') ) ) model.add(layers.Dropout(rate=hp.Float('dropout_' + str(i), min_value=0.0, max_value=0.5, default=0.25, step=0.05) ) ) counter+=1 model.add(layers.Dense(classes, activation='softmax')) optimizer = hp.Choice('optimizer', values = ['adam' # ,'sgd', 'rmsprop', 'adadelta' ]) lr = hp.Choice('learning_rate', values=[1e-2, 1e-3]) if optimizer == 'adam': optimizer = keras.optimizers.Adam(learning_rate=lr) #elif optimizer == 'sgd': # optimizer = keras.optimizers.SGD(learning_rate=lr) #elif optimizer == 'rmsprop': # optimizer = keras.optimizers.RMSprop(learning_rate=lr) # else: # optimizer = keras.optimizers.Adadelta(learning_rate=lr) model.compile( optimizer=optimizer, loss='sparse_categorical_crossentropy', #steps_per_execution=32, metrics=['accuracy'] ) return model After executing the above function, I built a tuner object. tuner = RandomSearch( build_model, objective='val_accuracy', # Set the objective to 'accuracy' #objective='val_loss', # Set the objective to 'val_loss' max_trials=3, # Set the maximum number of trials executions_per_trial=3, # Set the number of executions per trial overwrite=True, directory='my_dir', # Set the directory where the results are stored project_name='consumer_complaints' # Set the project name ) # Display the search space summary tuner.search_space_summary() But after this step, when I run belw code to search the hyper-parameter space. # Assume pad_data_train, pad_data_testare your data tuner.search(pad_data_train, y_train, epochs=5, validation_data=(pad_data_test, y_test) , batch_size = 64 ) I am getting error as shown below. I cant seem t figure out what I am doing wrong. Traceback (most recent call last): File "/opt/conda/lib/python3.10/site-packages/keras_tuner/engine/base_tuner.py", line 270, in _try_run_and_update_trial self._run_and_update_trial(trial, *fit_args, **fit_kwargs) File "/opt/conda/lib/python3.10/site-packages/keras_tuner/engine/base_tuner.py", line 235, in _run_and_update_trial results = self.run_trial(trial, *fit_args, **fit_kwargs) File "/opt/conda/lib/python3.10/site-packages/keras_tuner/engine/tuner.py", line 287, in run_trial obj_value = self._build_and_fit_model(trial, *args, **copied_kwargs) File "/opt/conda/lib/python3.10/site-packages/keras_tuner/engine/tuner.py", line 214, in _build_and_fit_model results = self.hypermodel.fit(hp, model, *args, **kwargs) File "/opt/conda/lib/python3.10/site-packages/keras_tuner/engine/hypermodel.py", line 144, in fit return model.fit(*args, **kwargs) File "/opt/conda/lib/python3.10/site-packages/keras/src/utils/traceback_utils.py", line 70, in error_handler raise e.with_traceback(filtered_tb) from None File "/opt/conda/lib/python3.10/site-packages/tensorflow/python/eager/execute.py", line 53, in quick_execute tensors = pywrap_tfe.TFE_Py_Execute(ctx._handle, device_name, op_name, tensorflow.python.framework.errors_impl.InvalidArgumentError: Graph execution error: Detected at node 'sequential/embedding/embedding_lookup' defined at (most recent call last): File "/opt/conda/lib/python3.10/runpy.py", line 196, in _run_module_as_main return _run_code(code, main_globals, None, File "/opt/conda/lib/python3.10/runpy.py", line 86, in _run_code exec(code, run_globals) File "/opt/conda/lib/python3.10/site-packages/ipykernel_launcher.py", line 17, in <module> app.launch_new_instance() File "/opt/conda/lib/python3.10/site-packages/traitlets/config/application.py", line 1043, in launch_instance app.start() File "/opt/conda/lib/python3.10/site-packages/ipykernel/kernelapp.py", line 736, in start self.io_loop.start() File "/opt/conda/lib/python3.10/site-packages/tornado/platform/asyncio.py", line 195, in start self.asyncio_loop.run_forever() File "/opt/conda/lib/python3.10/asyncio/base_events.py", line 603, in run_forever self._run_once() File "/opt/conda/lib/python3.10/asyncio/base_events.py", line 1909, in _run_once handle._run() File "/opt/conda/lib/python3.10/asyncio/events.py", line 80, in _run self._context.run(self._callback, *self._args) File "/opt/conda/lib/python3.10/site-packages/ipykernel/kernelbase.py", line 516, in dispatch_queue await self.process_one() File "/opt/conda/lib/python3.10/site-packages/ipykernel/kernelbase.py", line 505, in process_one await dispatch(*args) File "/opt/conda/lib/python3.10/site-packages/ipykernel/kernelbase.py", line 412, in dispatch_shell await result File "/opt/conda/lib/python3.10/site-packages/ipykernel/kernelbase.py", line 740, in execute_request reply_content = await reply_content File "/opt/conda/lib/python3.10/site-packages/ipykernel/ipkernel.py", line 422, in do_execute res = shell.run_cell( File "/opt/conda/lib/python3.10/site-packages/ipykernel/zmqshell.py", line 546, in run_cell return super().run_cell(*args, **kwargs) File "/opt/conda/lib/python3.10/site-packages/IPython/core/interactiveshell.py", line 3009, in run_cell result = self._run_cell( File "/opt/conda/lib/python3.10/site-packages/IPython/core/interactiveshell.py", line 3064, in _run_cell result = runner(coro) File "/opt/conda/lib/python3.10/site-packages/IPython/core/async_helpers.py", line 129, in _pseudo_sync_runner coro.send(None) File "/opt/conda/lib/python3.10/site-packages/IPython/core/interactiveshell.py", line 3269, in run_cell_async has_raised = await self.run_ast_nodes(code_ast.body, cell_name, File "/opt/conda/lib/python3.10/site-packages/IPython/core/interactiveshell.py", line 3448, in run_ast_nodes if await self.run_code(code, result, async_=asy): File "/opt/conda/lib/python3.10/site-packages/IPython/core/interactiveshell.py", line 3508, in run_code exec(code_obj, self.user_global_ns, self.user_ns) File "/tmp/ipykernel_42/3795112731.py", line 2, in <module> tuner.search(pad_data_train, y_train, File "/opt/conda/lib/python3.10/site-packages/keras_tuner/engine/base_tuner.py", line 230, in search self._try_run_and_update_trial(trial, *fit_args, **fit_kwargs) File "/opt/conda/lib/python3.10/site-packages/keras_tuner/engine/base_tuner.py", line 270, in _try_run_and_update_trial self._run_and_update_trial(trial, *fit_args, **fit_kwargs) File "/opt/conda/lib/python3.10/site-packages/keras_tuner/engine/base_tuner.py", line 235, in _run_and_update_trial results = self.run_trial(trial, *fit_args, **fit_kwargs) File "/opt/conda/lib/python3.10/site-packages/keras_tuner/engine/tuner.py", line 287, in run_trial obj_value = self._build_and_fit_model(trial, *args, **copied_kwargs) File "/opt/conda/lib/python3.10/site-packages/keras_tuner/engine/tuner.py", line 214, in _build_and_fit_model results = self.hypermodel.fit(hp, model, *args, **kwargs) File "/opt/conda/lib/python3.10/site-packages/keras_tuner/engine/hypermodel.py", line 144, in fit return model.fit(*args, **kwargs) File "/opt/conda/lib/python3.10/site-packages/keras/src/utils/traceback_utils.py", line 65, in error_handler return fn(*args, **kwargs) File "/opt/conda/lib/python3.10/site-packages/keras/src/engine/training.py", line 1742, in fit tmp_logs = self.train_function(iterator) File "/opt/conda/lib/python3.10/site-packages/keras/src/engine/training.py", line 1338, in train_function return step_function(self, iterator) File "/opt/conda/lib/python3.10/site-packages/keras/src/engine/training.py", line 1322, in step_function outputs = model.distribute_strategy.run(run_step, args=(data,)) File "/opt/conda/lib/python3.10/site-packages/keras/src/engine/training.py", line 1303, in run_step outputs = model.train_step(data) File "/opt/conda/lib/python3.10/site-packages/keras/src/engine/training.py", line 1080, in train_step y_pred = self(x, training=True) File "/opt/conda/lib/python3.10/site-packages/keras/src/utils/traceback_utils.py", line 65, in error_handler return fn(*args, **kwargs) File "/opt/conda/lib/python3.10/site-packages/keras/src/engine/training.py", line 569, in __call__ return super().__call__(*args, **kwargs) File "/opt/conda/lib/python3.10/site-packages/keras/src/utils/traceback_utils.py", line 65, in error_handler return fn(*args, **kwargs) File "/opt/conda/lib/python3.10/site-packages/keras/src/engine/base_layer.py", line 1150, in __call__ outputs = call_fn(inputs, *args, **kwargs) File "/opt/conda/lib/python3.10/site-packages/keras/src/utils/traceback_utils.py", line 96, in error_handler return fn(*args, **kwargs) File "/opt/conda/lib/python3.10/site-packages/keras/src/engine/sequential.py", line 405, in call return super().call(inputs, training=training, mask=mask) File "/opt/conda/lib/python3.10/site-packages/keras/src/engine/functional.py", line 512, in call return self._run_internal_graph(inputs, training=training, mask=mask) File "/opt/conda/lib/python3.10/site-packages/keras/src/engine/functional.py", line 669, in _run_internal_graph outputs = node.layer(*args, **kwargs) File "/opt/conda/lib/python3.10/site-packages/keras/src/utils/traceback_utils.py", line 65, in error_handler return fn(*args, **kwargs) File "/opt/conda/lib/python3.10/site-packages/keras/src/engine/base_layer.py", line 1150, in __call__ outputs = call_fn(inputs, *args, **kwargs) File "/opt/conda/lib/python3.10/site-packages/keras/src/utils/traceback_utils.py", line 96, in error_handler return fn(*args, **kwargs) File "/opt/conda/lib/python3.10/site-packages/keras/src/layers/core/embedding.py", line 272, in call out = tf.nn.embedding_lookup(self.embeddings, inputs) Node: 'sequential/embedding/embedding_lookup' indices[41,8] = 6402 is not in [0, 5201) [[{{node sequential/embedding/embedding_lookup}}]] [Op:__inference_train_function_14440] --------------------------------------------------------------------------- RuntimeError Traceback (most recent call last) Cell In[43], line 2 1 # Assume x_train, y_train are your data ----> 2 tuner.search(pad_data_train, y_train, 3 epochs=5, 4 validation_data=(pad_data_test, y_test) 5 , 6 batch_size = 64 7 ) File /opt/conda/lib/python3.10/site-packages/keras_tuner/engine/base_tuner.py:231, in BaseTuner.search(self, *fit_args, **fit_kwargs) 229 self.on_trial_begin(trial) 230 self._try_run_and_update_trial(trial, *fit_args, **fit_kwargs) --> 231 self.on_trial_end(trial) 232 self.on_search_end() File /opt/conda/lib/python3.10/site-packages/keras_tuner/engine/base_tuner.py:335, in BaseTuner.on_trial_end(self, trial) 329 def on_trial_end(self, trial): 330 """Called at the end of a trial. 331 332 Args: 333 trial: A `Trial` instance. 334 """ --> 335 self.oracle.end_trial(trial) 336 # Display needs the updated trial scored by the Oracle. 337 self._display.on_trial_end(self.oracle.get_trial(trial.trial_id)) File /opt/conda/lib/python3.10/site-packages/keras_tuner/engine/oracle.py:107, in synchronized.<locals>.wrapped_func(*args, **kwargs) 105 LOCKS[oracle].acquire() 106 THREADS[oracle] = thread_name --> 107 ret_val = func(*args, **kwargs) 108 if need_acquire: 109 THREADS[oracle] = None File /opt/conda/lib/python3.10/site-packages/keras_tuner/engine/oracle.py:434, in Oracle.end_trial(self, trial) 432 if not self._retry(trial): 433 self.end_order.append(trial.trial_id) --> 434 self._check_consecutive_failures() 436 self._save_trial(trial) 437 self.save() File /opt/conda/lib/python3.10/site-packages/keras_tuner/engine/oracle.py:386, in Oracle._check_consecutive_failures(self) 384 consecutive_failures = 0 385 if consecutive_failures == self.max_consecutive_failed_trials: --> 386 raise RuntimeError( 387 "Number of consecutive failures excceeded the limit " 388 f"of {self.max_consecutive_failed_trials}.\n" 389 + trial.message 390 ) RuntimeError: Number of consecutive failures excceeded the limit of 3. Traceback (most recent call last): File "/opt/conda/lib/python3.10/site-packages/keras_tuner/engine/base_tuner.py", line 270, in _try_run_and_update_trial self._run_and_update_trial(trial, *fit_args, **fit_kwargs) File "/opt/conda/lib/python3.10/site-packages/keras_tuner/engine/base_tuner.py", line 235, in _run_and_update_trial results = self.run_trial(trial, *fit_args, **fit_kwargs) File "/opt/conda/lib/python3.10/site-packages/keras_tuner/engine/tuner.py", line 287, in run_trial obj_value = self._build_and_fit_model(trial, *args, **copied_kwargs) File "/opt/conda/lib/python3.10/site-packages/keras_tuner/engine/tuner.py", line 214, in _build_and_fit_model results = self.hypermodel.fit(hp, model, *args, **kwargs) File "/opt/conda/lib/python3.10/site-packages/keras_tuner/engine/hypermodel.py", line 144, in fit return model.fit(*args, **kwargs) File "/opt/conda/lib/python3.10/site-packages/keras/src/utils/traceback_utils.py", line 70, in error_handler raise e.with_traceback(filtered_tb) from None File "/opt/conda/lib/python3.10/site-packages/tensorflow/python/eager/execute.py", line 53, in quick_execute tensors = pywrap_tfe.TFE_Py_Execute(ctx._handle, device_name, op_name, tensorflow.python.framework.errors_impl.InvalidArgumentError: Graph execution error: Detected at node 'sequential/embedding/embedding_lookup' defined at (most recent call last): File "/opt/conda/lib/python3.10/runpy.py", line 196, in _run_module_as_main return _run_code(code, main_globals, None, File "/opt/conda/lib/python3.10/runpy.py", line 86, in _run_code exec(code, run_globals) File "/opt/conda/lib/python3.10/site-packages/ipykernel_launcher.py", line 17, in <module> app.launch_new_instance() File "/opt/conda/lib/python3.10/site-packages/traitlets/config/application.py", line 1043, in launch_instance app.start() File "/opt/conda/lib/python3.10/site-packages/ipykernel/kernelapp.py", line 736, in start self.io_loop.start() File "/opt/conda/lib/python3.10/site-packages/tornado/platform/asyncio.py", line 195, in start self.asyncio_loop.run_forever() File "/opt/conda/lib/python3.10/asyncio/base_events.py", line 603, in run_forever self._run_once() File "/opt/conda/lib/python3.10/asyncio/base_events.py", line 1909, in _run_once handle._run() File "/opt/conda/lib/python3.10/asyncio/events.py", line 80, in _run self._context.run(self._callback, *self._args) File "/opt/conda/lib/python3.10/site-packages/ipykernel/kernelbase.py", line 516, in dispatch_queue await self.process_one() File "/opt/conda/lib/python3.10/site-packages/ipykernel/kernelbase.py", line 505, in process_one await dispatch(*args) File "/opt/conda/lib/python3.10/site-packages/ipykernel/kernelbase.py", line 412, in dispatch_shell await result File "/opt/conda/lib/python3.10/site-packages/ipykernel/kernelbase.py", line 740, in execute_request reply_content = await reply_content File "/opt/conda/lib/python3.10/site-packages/ipykernel/ipkernel.py", line 422, in do_execute res = shell.run_cell( File "/opt/conda/lib/python3.10/site-packages/ipykernel/zmqshell.py", line 546, in run_cell return super().run_cell(*args, **kwargs) File "/opt/conda/lib/python3.10/site-packages/IPython/core/interactiveshell.py", line 3009, in run_cell result = self._run_cell( File "/opt/conda/lib/python3.10/site-packages/IPython/core/interactiveshell.py", line 3064, in _run_cell result = runner(coro) File "/opt/conda/lib/python3.10/site-packages/IPython/core/async_helpers.py", line 129, in _pseudo_sync_runner coro.send(None) File "/opt/conda/lib/python3.10/site-packages/IPython/core/interactiveshell.py", line 3269, in run_cell_async has_raised = await self.run_ast_nodes(code_ast.body, cell_name, File "/opt/conda/lib/python3.10/site-packages/IPython/core/interactiveshell.py", line 3448, in run_ast_nodes if await self.run_code(code, result, async_=asy): File "/opt/conda/lib/python3.10/site-packages/IPython/core/interactiveshell.py", line 3508, in run_code exec(code_obj, self.user_global_ns, self.user_ns) File "/tmp/ipykernel_42/3795112731.py", line 2, in <module> tuner.search(pad_data_train, y_train, File "/opt/conda/lib/python3.10/site-packages/keras_tuner/engine/base_tuner.py", line 230, in search self._try_run_and_update_trial(trial, *fit_args, **fit_kwargs) File "/opt/conda/lib/python3.10/site-packages/keras_tuner/engine/base_tuner.py", line 270, in _try_run_and_update_trial self._run_and_update_trial(trial, *fit_args, **fit_kwargs) File "/opt/conda/lib/python3.10/site-packages/keras_tuner/engine/base_tuner.py", line 235, in _run_and_update_trial results = self.run_trial(trial, *fit_args, **fit_kwargs) File "/opt/conda/lib/python3.10/site-packages/keras_tuner/engine/tuner.py", line 287, in run_trial obj_value = self._build_and_fit_model(trial, *args, **copied_kwargs) File "/opt/conda/lib/python3.10/site-packages/keras_tuner/engine/tuner.py", line 214, in _build_and_fit_model results = self.hypermodel.fit(hp, model, *args, **kwargs) File "/opt/conda/lib/python3.10/site-packages/keras_tuner/engine/hypermodel.py", line 144, in fit return model.fit(*args, **kwargs) File "/opt/conda/lib/python3.10/site-packages/keras/src/utils/traceback_utils.py", line 65, in error_handler return fn(*args, **kwargs) File "/opt/conda/lib/python3.10/site-packages/keras/src/engine/training.py", line 1742, in fit tmp_logs = self.train_function(iterator) File "/opt/conda/lib/python3.10/site-packages/keras/src/engine/training.py", line 1338, in train_function return step_function(self, iterator) File "/opt/conda/lib/python3.10/site-packages/keras/src/engine/training.py", line 1322, in step_function outputs = model.distribute_strategy.run(run_step, args=(data,)) File "/opt/conda/lib/python3.10/site-packages/keras/src/engine/training.py", line 1303, in run_step outputs = model.train_step(data) File "/opt/conda/lib/python3.10/site-packages/keras/src/engine/training.py", line 1080, in train_step y_pred = self(x, training=True) File "/opt/conda/lib/python3.10/site-packages/keras/src/utils/traceback_utils.py", line 65, in error_handler return fn(*args, **kwargs) File "/opt/conda/lib/python3.10/site-packages/keras/src/engine/training.py", line 569, in __call__ return super().__call__(*args, **kwargs) File "/opt/conda/lib/python3.10/site-packages/keras/src/utils/traceback_utils.py", line 65, in error_handler return fn(*args, **kwargs) File "/opt/conda/lib/python3.10/site-packages/keras/src/engine/base_layer.py", line 1150, in __call__ outputs = call_fn(inputs, *args, **kwargs) File "/opt/conda/lib/python3.10/site-packages/keras/src/utils/traceback_utils.py", line 96, in error_handler return fn(*args, **kwargs) File "/opt/conda/lib/python3.10/site-packages/keras/src/engine/sequential.py", line 405, in call return super().call(inputs, training=training, mask=mask) File "/opt/conda/lib/python3.10/site-packages/keras/src/engine/functional.py", line 512, in call return self._run_internal_graph(inputs, training=training, mask=mask) File "/opt/conda/lib/python3.10/site-packages/keras/src/engine/functional.py", line 669, in _run_internal_graph outputs = node.layer(*args, **kwargs) File "/opt/conda/lib/python3.10/site-packages/keras/src/utils/traceback_utils.py", line 65, in error_handler return fn(*args, **kwargs) File "/opt/conda/lib/python3.10/site-packages/keras/src/engine/base_layer.py", line 1150, in __call__ outputs = call_fn(inputs, *args, **kwargs) File "/opt/conda/lib/python3.10/site-packages/keras/src/utils/traceback_utils.py", line 96, in error_handler return fn(*args, **kwargs) File "/opt/conda/lib/python3.10/site-packages/keras/src/layers/core/embedding.py", line 272, in call out = tf.nn.embedding_lookup(self.embeddings, inputs) Node: 'sequential/embedding/embedding_lookup' indices[41,8] = 6402 is not in [0, 5201) [[{{node sequential/embedding/embedding_lookup}}]] [Op:__inference_train_function_14440]
i had the same issue, this is because standard libraries are missing, I solved it this way: npm install core-js after installation insert the following import into the file where the decode takes place import "core-js/stable/atob"; example: import { jwtDecode } from "jwt-decode"; import "core-js/stable/atob";
|python|graphics|computer-vision|transformation|perspectivecamera|
I'm not sure that you posted the full code, anyways you should also include a `Options()` object and **use the correct `Options` and `Service`** for your browser (imports). from selenium import webdriver from selenium.webdriver.chrome.options import Options from selenium.webdriver.chrome.service import Service driver = webdriver.Chrome(options=Options(), service=Service()) driver.get("https://google.com")
We have an iOS native project, and we are opening some Flutter screens following the official [documentation][1]. After integration, we noticed that some users are experiencing crashes in the Flutter framework. These crashes are not being reported to Crashlytics, although we can see them in the Apple Feedback Crashes tool. Attached is the stack trace of one of the crashes that we personally encountered and submitted to the Apple Feedback tool, but we didn't observe it in Firebase Crashlytics. Additionally, we are facing difficulty symbolicating Flutter crashes when certain Flutter screens are opened within our native iOS project. We are unable to symbolicate the crash logs. How can we address this DYSM issue in Flutter and ensure that crashes occurring in these Flutter screens are correctly reported and symbolicated in Firebase Crashlytics?" [![enter image description here][2]][2] [![enter image description here][3]][3] Doctor summary (to see all details, run flutter doctor -v): [✓] Flutter (Channel stable, 3.16.1, on macOS 14.2 23C64 darwin-arm64, locale en-SA) [✓] Android toolchain - develop for Android devices (Android SDK version 34.0.0) [✓] Xcode - develop for iOS and macOS (Xcode 15.0) [✓] Chrome - develop for the web [✓] Android Studio (version 2022.3) [✓] VS Code (version 1.85.1) [✓] VS Code (version 1.74.3) [✓] Connected device (4 available) ! Error: Browsing on the local area network for Ali’s iPhone. Ensure the device is unlocked and attached with a cable or associated with the same local area network as this Mac. The device must be opted into Developer Mode to connect wirelessly. (code -27) [✓] Network resources • No issues found! QTYPFWXD6G:FlutterDesktop a.ali15$ flutter --version Flutter 3.16.1 • channel stable • https://github.com/flutter/flutter.git Framework • revision 7f20e5d18c (7 weeks ago) • 2023-11-27 09:47:30 -0800 Engine • revision 22b600f240 Tools • Dart 3.2.1 • DevTools 2.28.3 QTYPFWXD6G:FlutterDesktop a.ali15$ [1]: https://docs.flutter.dev/add-to-app/ios/add-flutter-screen?tab=no-engine-vc-uikit-swift-tab [2]: https://i.stack.imgur.com/4r7VM.png [3]: https://i.stack.imgur.com/Jg9jD.png
JS React "frozen"
|reactjs|rust|axios|setinterval|tauri|
This issue went away after rebooting macos. Before then I had also installed xcode but I'm not sure if this had any impact.
I was able to find the right type for it looking at how to handle pagination in the drizzle documentation. Here is the final code with the right type: import { sql } from "drizzle-orm"; import { PgSelect } from "drizzle-orm/pg-core"; import { db } from "../db"; import { Pagination, QueryStringPagination } from "../types"; export async function paginateQuery<T extends PgSelect>({ query, QueryStringPagination, }: { query: T; // <---- correct type QueryStringPagination: QueryStringPagination; }): Promise<{ data: T[]; pagination: Pagination }> { const subQuery = query.as("sub"); const totalRecordsQuery = db .select({ total: sql<number>`count(*)` }) .from(subQuery); const totalRecordsResult = await totalRecordsQuery.execute(); const totalRecords = Number(totalRecordsResult[0].total); const totalPages = Math.ceil(totalRecords / QueryStringPagination.limit); query .limit(QueryStringPagination.limit) .offset((QueryStringPagination.page - 1) * QueryStringPagination.limit); const results = (await query.execute()) as T[]; return { data: results, pagination: { totalRecords: totalRecords, totalPages: totalPages, currentPage: QueryStringPagination.page, limit: QueryStringPagination.limit, }, }; }
|data-structures|hashmap|
I am currently doing desktop automation by using pywinauto. I have done many tests automated and they were running successfully and fast. But suddenly they started to run too slow, 1 seconds step is running in 2-3 mins. For example, entering username takes 2-3 mins or more. I run automated regression tests after getting new version of desktop apps. I need help, what should I do? I reinstalled Python 3.10.6 , Pywinauto and pywinauto-recorder but still same.
pywinauto scripts run so slow now, they were running very well and fast
|pywinauto|
null
create a folder in the name of "Templates" and add your html files in it . Then run . This worked for me
I hope You're doing well , Please advise according to follwoing issue in the below email If Not Intersect(Target, Me.Columns("X")) Is Nothing Then Please your support Regarding to this issue Thank you , If Not Intersect(Target, Me.Columns("X")) Is Nothing Then
Asking about some issues find it in Vba Macro
|vba6|
null
I encountered the same problem today. It seems to occur when you change Excel and try to reinstantiate. The following fix worked for me: - I deleted the already instantiated test cases, including the folder TemplateInstance of ... - Then I instantiated the test case anew. It prompted me to relink the data source. In this situation, it correctly reads the newly added lines in the Excel. - No further issues encountered. The only drawback is that all previously added execution lists will be affected. You'll need to add your test cases again.
I am working on a Angular project. My aim is to make a book finder application using Google Books API and the problem is that sometimes when i refresh the page or I go to a different component and go back to my homepage it sometimes doesnt show any books even though the status code is 200. I checked the console and its supposed to send an array named items. When the error occurs it doesnt send that array. all-books.component.ts : ``` import { Component, OnInit } from '@angular/core'; import { BookService } from '../book.service'; import { Router } from '@angular/router'; @Component({ selector: 'app-all-books', templateUrl: './all-books.component.html', styleUrls: ['./all-books.component.css'] }) export class AllBooksComponent implements OnInit { books: any[] = []; loading: boolean = true; error: string | null = null; searchQuery: string = ''; searchBy: string = 'title'; constructor(private bookService: BookService, private router: Router) { } ngOnInit(): void { this.fetchBooks(); } fetchBooks(): void { this.loading = true; this.bookService.getRandomBooks() .subscribe( (data: any) => { console.log("API Response:", data); if (data && data.items && data.items.length > 0) { this.books = data.items.slice(0, 9); this.error = null; } else { this.books = []; // Reset books array this.error = 'No books found.'; } this.loading = false; }, (error) => { console.error('Error fetching random books:', error); this.error = 'Failed to fetch books. Please try again later.'; this.books = []; this.loading = false; } ); } search(): void { this.loading = true; this.bookService.searchBooks(this.searchQuery, this.searchBy) .subscribe( (data: any) => { if (data && data.items && data.items.length > 0) { this.books = data.items; this.error = ''; } else { this.books = []; this.error = 'No books found.'; } this.loading = false; }, (error) => { console.error('Error fetching search results:', error); this.error = 'Failed to fetch search results. Please try again later.'; this.books = []; // Reset books array this.loading = false; } ); } } ``` all-books.component.html : ``` <div class="container"> <div class="row mt-5 justify-content-center"> <div class="col-md-6"> <div class="input-group"> <input type="text" [(ngModel)]="searchQuery" class="form-control" placeholder="Search for books..." /> <select [(ngModel)]="searchBy" class="form-select"> <option value="title">Title</option> <option value="author">Author</option> <option value="isbn">ISBN</option> </select> <button (click)="search()" class="btn btn-primary">Search</button> </div> </div> </div> <p class="text-center font fw-bold mt-5">Here are a selection of our books</p> <div class="container mt-3"> <div class="row row-cols-1 row-cols-md-2 row-cols-lg-3 g-4 justify-content-center"> <div class="col" *ngFor="let book of books"> <div class="card h-100"> <img [src]="book.volumeInfo?.imageLinks?.thumbnail" alt="No Book Cover Available" class="card-img-top" style="height: 350px; object-fit: cover;"> <div class="card-body"> <h5 class="card-title">{{ book.volumeInfo?.title }}</h5> <ul class="list-group list-group-flush text-center"> <li class="list-group-item">Author: {{ book.volumeInfo?.authors?.join(', ') || 'Unknown' }}</li> <li class="list-group-item">Release date: {{ book.volumeInfo?.publishedDate || 'Unknown' }}</li> <li class="list-group-item">Publisher: {{ book.volumeInfo?.publisher || 'Unknown' }}</li> </ul> </div> <div class="card-footer d-flex justify-content-center"> <a [routerLink]="['/book-details']" [queryParams]="{ bookId: book.id }" class="btn btn-primary fixed-button-size">Details</a> </div> </div> </div> </div> </div> </div> ``` book.service.ts : ``` import { HttpClient } from "@angular/common/http"; import { Injectable } from "@angular/core"; import { Observable } from "rxjs"; @Injectable({ providedIn: 'root' }) export class BookService { private apiUrl: string = 'https://www.googleapis.com/books/v1/volumes'; private apiKey: string = 'myApiKey'; constructor(private http: HttpClient) { } searchBooks(query: string, searchBy: string): Observable<any> { let url: string; if (searchBy === 'title') { url = `${this.apiUrl}?q=intitle:${query}&key=${this.apiKey}`; } else if (searchBy === 'author') { url = `${this.apiUrl}?q=inauthor:${query}&key=${this.apiKey}`; } else if (searchBy === 'isbn') { url = `${this.apiUrl}?q=isbn:${query}&key=${this.apiKey}`; } else { url = `${this.apiUrl}?q=${query}&key=${this.apiKey}`; } return this.http.get(url); } getRandomBooks(): Observable<any> { const randomPage = Math.floor(Math.random() * 100); const query = 'fiction'; const url = `${this.apiUrl}?q=${query}&startIndex=${randomPage * 10}&maxResults=10&key=${this.apiKey}`; return this.http.get(url); } getBookDetails(bookId: string): Observable<any> { const url = `${this.apiUrl}/${bookId}?key=${this.apiKey}`; return this.http.get(url); } } ``` I tried debugging and also tried fixing it with chatGPT but it didn't work.
I want to insert a new row and then get back the row I just inserted. ```rust use serde::{Deserialize, Serialize}; use sqlx::{FromRow, mysql::MySqlPoolOptions}; use tokio; #[derive(Debug, Deserialize, Serialize, FromRow)] struct Session { id: i32, name: String, } #[tokio::main] async fn main() { let pool = MySqlPoolOptions::new() .max_connections(10) .connect("mysql://me:password@localhost/time_tracker") .await .unwrap(); let session: Session = sqlx::query_as("INSERT INTO sessions (name) VALUES (?) RETURNING *") .bind("Session name") .fetch_one(&pool) .await .unwrap(); println!("{session:?}"); } ``` The table looks like this: ``` MariaDB [time_tracker]> DESCRIBE sessions; +------------+---------------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +------------+---------------+------+-----+---------+----------------+ | id | int(11) | NO | PRI | NULL | auto_increment | | name | varchar(255) | YES | | NULL | | | start_time | datetime | YES | | NULL | | | end_time | datetime | YES | | NULL | | | pay_rate | decimal(10,2) | YES | | NULL | | +------------+---------------+------+-----+---------+----------------+ ``` But I get this error. If I change it to `RETURNING name` I get the same error. ``` thread 'main' panicked at src/main.rs:22:10: called `Result::unwrap()` on an `Err` value: ColumnNotFound("id") ``` If I change it to this: ```rust let row = sqlx::query("INSERT INTO sessions (name) VALUES (?)") .bind("Session name") .fetch_one(&pool) .await .unwrap(); ``` I get: ``` thread 'main' panicked at src/main.rs:22:10: called `Result::unwrap()` on an `Err` value: RowNotFound ``` The query works just fine if I do it in MySQL directly. ``` MariaDB [time_tracker]> INSERT INTO sessions (name) VALUES ("Session name") RETURNING *; +----+--------------+------------+----------+----------+ | id | name | start_time | end_time | pay_rate | +----+--------------+------------+----------+----------+ | 32 | Session name | NULL | NULL | NULL | +----+--------------+------------+----------+----------+ 1 row in set (0.001 sec) ``` What am I doing wrong?
`ColumnNotFound("id")` when inserting with SQLx
|mysql|rust|mariadb|sqlx|
I found a simple solution from the [TinyMCE docs - selection.getBookmark()](https://www.tiny.cloud/docs/api/tinymce.dom/tinymce.dom.selection/#getbookmark). > ### getBookmark > Returns a bookmark location for the current selection. This bookmark object can then be used to restore the selection after some content modification to the document. I tried the below and it works to change the case and then mark the new content as selected. ```typescript const handleCaseChange = (ed: Editor) => { ed.on("keydown", (event: KeyboardEvent) => { if (event.shiftKey && event.key === "F3") { event.preventDefault(); const selection = ed.selection.getSel(); const selectedText = selection?.toString(); if (selectedText !== undefined && selectedText.length > 0) { let transformedText; if (selectedText === selectedText.toUpperCase()) { transformedText = selectedText.toLowerCase(); } else if (selectedText === selectedText.toLowerCase()) { transformedText = capitalizeEachWord(selectedText); } else { transformedText = selectedText.toUpperCase(); } const bookmark = ed.selection.getBookmark(); ed.selection.setContent(transformedText); ed.selection.moveToBookmark(bookmark); } } } } const capitalizeEachWord = (str: string) => str.replace(/\b\w/g, (char: string) => char.toUpperCase()); ```
I have a problem deploying nginx on the server using docker swarm. **what i try to do?** I am trying to transfer a request when the client called my DNS name `https://powersolution.digital/` to the NGINX proxy manager on port 81 ---------- **How i try to do it?** I deployed it using `docker stack deploy -c ymlFile stackName` after checking if the service deployed without any problem and checking the logs. I can reach the site if I try to access it using an IP address and port 81 **eg: 125.8.1.10:81**. but after login and set the follwoing configuration [![enter image description here][1]][1] When I tried to reach the site using the domain name I got **connection time out**, also I tried to replace the IP address with `service name` like the following image, but I had the same result. [![enter image description here][2]][2] Also I can't access any other service also throw the **nginx proxy manager** The compose file: ``` version: '3.8' services: maneger-app-service: image: 'jc21/nginx-proxy-manager:latest' restart: unless-stopped ports: - 90:80 - 81:81 - 443:443 networks: - acc_web networks: acc_web: external: true **Note: I tried the above solution with `docker compose -f ymlfile up` and worked without any problem ** ``` [1]: https://i.stack.imgur.com/eGiv9.png [2]: https://i.stack.imgur.com/A2WLT.png
Nginx proxy manager with docker swarm could not reach
|docker|nginx|deployment|
Round Robin partitioning only occurs when the key of a message is not defined. Otherwise, the partition is computed from the hash of that key (test and test2 may hash similarly to arrive in the same partition)
I'm not completely sure why that happens but depth peeling fixes it..: ```python from vedo import * settings.use_depth_peeling = True msh = Mesh("normalized_model.obj").texture("texture.png") show(msh, axes=1) ``` [![enter image description here][1]][1] [1]: https://i.stack.imgur.com/GiPy1.png
Using any sed: $ sed 's/\\/\\\\/' file Hello\\nmate $ sed 's/\(.*\)\\\(.*\)/{"output":"\1\\\\\2"}/' file {"output":"Hello\\nmate"}
To translate data of any Model in Django - you shouild use external library. *For example - i have created [Django-TOF][1]. Also i add in my library, translation on fly the static texts.* In your cases, probably you should repeate **makemessages**: https://docs.djangoproject.com/en/5.0/ref/django-admin/#django-admin-makemessages after *makemessages*, check translations, which you want to translate. After made **compilemessages**: https://docs.djangoproject.com/en/5.0/ref/django-admin/#compilemessages After - **runserver**. All schould be translated. If something is not translated - you are not mark this text as translatable text. [1]: https://github.com/danilovmy/django-tof
I have rewritten the history of a submodule quite some time ago and no longer have the original submodule history (so my question is not a duplicate of [this one][1]) Can I fix the submodule SHA in the parent repository? Based on the criteria that a submodule SHA in the parent repo points at the most recent commit of the submodule at that time. [1]: https://stackoverflow.com/questions/37442500/repository-with-submodules-after-rewriting-history-of-submodule
Let’s walk through this loop… for(int i=0; i<duplicateValues.size(); i++) { if(row == duplicateValues.get(i).getRow() && column == duplicateValues.get(i).getCol()) { When the above `if` test is true, the code applies custom colors to the label: label.setBackground(new Color(duplicateValues.get(i).getBackgroundRed(), duplicateValues.get(i).getBackgroundGreen(), duplicateValues.get(i).getBackgroundBlue())); label.setForeground(new Color(duplicateValues.get(i).getForegroundRed(), duplicateValues.get(i).getForegroundGreen(), duplicateValues.get(i).getForegroundBlue())); And that’s perfect… as long as the program doesn’t go changing the label’s colors to something else. However, because this loop keeps going (in most cases), the next iteration of the loop will *not* set these same colors. Instead, it will enter the `else` part: } else { label.setBackground(getBackground()); label.setForeground(getForeground()); } And now the code which set the custom colors based on the duplicate values has been undone. Your custom colors are lost. The solution is to call label.setForeground and label.setBackground *only once,* after the loop has finished: Color foreground; Color background; if (isSelected) { foreground = table.getSelectionForeground(); background = table.getSelectionBackground(); } else { foreground = table.getForeground(); background = table.getBackground(); for (DuplicateValues d : duplicateValues) { if (row == d.getRow() && column == d.getCol()) { foreground = new Color( d.getForegroundRed(), d.getForegroundGreen(), d.getForegroundBlue()); background = new Color( d.getBackgroundRed(), d.getBackgroundGreen(), d.getBackgroundBlue()); // We found a match. No need to keep checking! break; } } } label.setForeground(foreground); label.setBackground(background);
My code uses **puppeteer to scrape a public API** (cant get axios to work). Takes product´s prices and saves the data into a **Sqlite3 DB**. API has a view limit in every query, so it scrapes www.apiexample.com/api/query=shoes/start=0 www.apiexample.com/api/query=shoes/start=48 www.apiexample.com/api/query=shoes/start=96 ... there are 5200 products **It does this every hour** and it compares the DB data with the new scaped data to look for differences. (prices DO change every now an then- not very frecuent). **Is there a way to scrape the URL items ONLY if there are changes in the data?** I´m looking into caching concept but I cant figure out how to do it. Is there another logic to tackle this proyect? thanks. async function fetchData(browser, queryItem, start) { if (!browser) { console.error('Browser instance is not initialized'); return; } const page = await browser.newPage(); try { const url = `${baseURL}?query=${queryItem}&start=${start}`; await page.goto(url, { waitUntil: 'networkidle0' }); const data = await page.evaluate(() => JSON.parse(document.body.innerText)); let filteredItems = {}; if(data.raw.itemList.items){ filteredItems = data.raw.itemList.items.map(item => ({ link: item.link, displayName: item.displayName, productId: item.productId, price: item.price, salePrice: item.salePrice, salePercentage: item.salePercentage, imageUrl: item.image.src })); } await saveToDatabase(filteredItems); return { totalCount: data.raw.itemList.count, items: filteredItems }; } catch (error) { console.error('Error fetching data:', error); } finally { await page.close(); } }
Using Puppeteer to scrape a public API ONLY ON CHANGE
|javascript|node.js|web-scraping|caching|puppeteer|
I'm trying to install Nativescript on my new Mac and I'm having some problems with it. I've followed the installation steps on [NativeScript's installation guide](https://docs.nativescript.org/setup/macos#installing-node) for both, Android and iOS, but on both it fails on the final step with is actually installing Nativescript, but I'm always getting the same error. I've been trying to find some way to fix it on Google but I'm not having any luck, so I thought I could ask here. Nativescript install command: ``` npm install -g nativescript ``` Error Dump on the Terminal: ``` npm ERR! code 1 npm ERR! path /opt/homebrew/lib/node_modules/nativescript/node_modules/fsevents npm ERR! command failed npm ERR! command sh -c node-gyp rebuild npm ERR! gyp info it worked if it ends with ok npm ERR! gyp info using node-gyp@10.1.0 npm ERR! gyp info using node@21.7.1 | darwin | arm64 npm ERR! gyp info find Python using Python version 3.12.2 found at "/opt/homebrew/opt/python@3.12/bin/python3.12" npm ERR! gyp info spawn /opt/homebrew/opt/python@3.12/bin/python3.12 npm ERR! gyp info spawn args [ npm ERR! gyp info spawn args '/opt/homebrew/lib/node_modules/nativescript/node_modules/node-gyp/gyp/gyp_main.py', npm ERR! gyp info spawn args 'binding.gyp', npm ERR! gyp info spawn args '-f', npm ERR! gyp info spawn args 'make', npm ERR! gyp info spawn args '-I', npm ERR! gyp info spawn args '/opt/homebrew/lib/node_modules/nativescript/node_modules/fsevents/build/config.gypi', npm ERR! gyp info spawn args '-I', npm ERR! gyp info spawn args '/opt/homebrew/lib/node_modules/nativescript/node_modules/node-gyp/addon.gypi', npm ERR! gyp info spawn args '-I', npm ERR! gyp info spawn args '/Users/xxx/Library/Caches/node-gyp/21.7.1/include/node/common.gypi', npm ERR! gyp info spawn args '-Dlibrary=shared_library', npm ERR! gyp info spawn args '-Dvisibility=default', npm ERR! gyp info spawn args '-Dnode_root_dir=/Users/xxx/Library/Caches/node-gyp/21.7.1', npm ERR! gyp info spawn args '-Dnode_gyp_dir=/opt/homebrew/lib/node_modules/nativescript/node_modules/node-gyp', npm ERR! gyp info spawn args '-Dnode_lib_file=/Users/xxx/Library/Caches/node-gyp/21.7.1/<(target_arch)/node.lib', npm ERR! gyp info spawn args '-Dmodule_root_dir=/opt/homebrew/lib/node_modules/nativescript/node_modules/fsevents', npm ERR! gyp info spawn args '-Dnode_engine=v8', npm ERR! gyp info spawn args '--depth=.', npm ERR! gyp info spawn args '--no-parallel', npm ERR! gyp info spawn args '--generator-output', npm ERR! gyp info spawn args 'build', npm ERR! gyp info spawn args '-Goutput_dir=.' npm ERR! gyp info spawn args ] npm ERR! gyp: binding.gyp not found (cwd: /opt/homebrew/lib/node_modules/nativescript/node_modules/fsevents) while trying to load binding.gyp npm ERR! gyp ERR! configure error npm ERR! gyp ERR! stack Error: `gyp` failed with exit code: 1 npm ERR! gyp ERR! stack at ChildProcess.<anonymous> (/opt/homebrew/lib/node_modules/nativescript/node_modules/node-gyp/lib/configure.js:297:18) npm ERR! gyp ERR! stack at ChildProcess.emit (node:events:519:28) npm ERR! gyp ERR! stack at ChildProcess._handle.onexit (node:internal/child_process:294:12) npm ERR! gyp ERR! System Darwin 23.4.0 npm ERR! gyp ERR! command "/opt/homebrew/Cellar/node/21.7.1/bin/node" "/opt/homebrew/lib/node_modules/nativescript/node_modules/.bin/node-gyp" "rebuild" npm ERR! gyp ERR! cwd /opt/homebrew/lib/node_modules/nativescript/node_modules/fsevents npm ERR! gyp ERR! node -v v21.7.1 npm ERR! gyp ERR! node-gyp -v v10.1.0 npm ERR! gyp ERR! not ok ```
Error installing Nativescript on Mac M2 Sonoma 14.4.1
|macos|nativescript|node-gyp|
null
I work in a windows form application. i wanna make a setting page for my program. in this form i have music for the total of my program and i have sound for my button, it sounds when you click on a button. i can off them and on them. my problem, is sounds of buttons. when i off the sound in the setting and it just off for the setting form, and when i go to another form and setting page is still open the sound of button is not off. and it sound when i click. page setting: ``` using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.Media; using WMPLib; namespace WindowsFormsApp3 { public partial class Form1 : Form { WindowsMediaPlayer playerr = new WindowsMediaPlayer(); public WindowsMediaPlayer button = new WindowsMediaPlayer(); public bool s ; public bool p ; bool t; public Form1() { InitializeComponent(); this.StartPosition= FormStartPosition.Manual; this.Location = new Point(300, 150); } private void Form1_Load(object sender, EventArgs e) { //if ( t==true ) playerr.URL = "aurora_runaway.mp3"; playerr.controls.play(); } private void button1_Click(object sender, EventArgs e) { if (pictureBox3.Visible == false && pictureBox4.Visible == true) { button.URL = "notifications-sound-127856.mp3"; button.controls.play(); } } private void pictureBox1_Click(object sender, EventArgs e) { playerr.controls.play(); pictureBox1.Visible= false; pictureBox2.Visible= true; } private void pictureBox2_Click(object sender, EventArgs e) { playerr.controls.stop(); //t = false; pictureBox2.Visible = false; pictureBox1.Visible =true; } private void pictureBox3_Click(object sender, EventArgs e) { pictureBox3.Visible = false; pictureBox4.Visible = true; s = true; p = false; } private void pictureBox4_Click(object sender, EventArgs e) { pictureBox4.Visible = false; pictureBox3.Visible = true; s = false; p = true; } private void button2_Click(object sender, EventArgs e) { new Form3().ShowDialog(); } } } ``` another page: ``` using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace WindowsFormsApp3 { public partial class Form3 : Form { Form1 ff = new Form1(); public Form3() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { if (ff.p == true && ff.s == false) { ff.button.URL = "notifications-sound-127856.mp3"; ff.button.controls.play(); } } } } ```
How to get a JavaScript script to stay within its designated element?
|javascript|html|css|
null
I had the same problem on React JS and I found the simplest way to implement the @IvanSanchez solution. You just need to make React execute the `<div id="leafletmap">` first, before executing javascript. To do this, you just need to add the javascript code inside the useEffect hook, because useEffect is asynchronous, it will execute after the synchronous code execution is done. Here is my code: import L from 'leaflet' import 'leaflet/dist/leaflet.css'; import { useEffect } from 'react'; export default function LeafletContainer() { useEffect(()=>{ var map = L.map('map').setView([51.505, -0.09], 13); L.tileLayer('https://tile.openstreetmap.org/{z}/{x}/{y}.png', { maxZoom: 19, attribution: '&copy; <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a>' }).addTo(map); }) return( <div className="leaflet-container"> <div id="map"></div> </div> ) } Dont forget to add height of the map in css: #map { height: 180px; }
Mark your ScreenState data class as Parcelable, We can't send data class directly as argument. Add below plugins to respective gradle files. // project level gradle plugins { .. id("org.jetbrains.kotlin.android") version "1.9.0" apply false } //app level gradle plugins { .. id("kotlin-parcelize") } Now sync your project and mark data class as Parcelable class like below, @Parcelize data class ScreenState( val name: String = "", val phoneNumber: String = "" ) : Parcelable
I am working on migrating an existing Spring application from Eclipselink version 2.5.2 to 4.0.2. In this application, there is a API in which the data is saved using the JpaRespository to the data, and once the loop ends it does a repo.flush(). Depending on the data, the loop creates the statement for inserting thousand of records to the database, if this number is huge, then I am getting the below error from the DB2 database: ``` [INFO] [err] ***** Out of Package Error Occurred (2024-03-28 20:34:23.76) ***** [INFO] [INFO] Exception stack trace: [INFO] com.ibm.db2.jcc.am.SqlException: NULLID.SYSLH103 0X5359534C564C3031 Concurrently open statements: [INFO] 1. SQL string: INSERT INTO TEST.TABLE1 (CTRYCODE) VALUES (?) [INFO] Number of statements: 1338 ``` Here is the code which is causing this ``` Table1 tab; for (Table1Dto iterator : records) { tab = new Table1(); tab.setData(iterator.getData()); repo.save(tab); } repo.flush(); ``` And here are all the properties set ``` <prop key="eclipselink.target-database">DB2</prop> <prop key="eclipselink.jdbc.cache-statements">true</prop> <prop key="eclipselink.weaving">false</prop> <prop key="eclipselink.id-validation">NULL</prop> <prop key="eclipselink.cache.shared.default">false</prop> <prop key="eclipselink.external-transaction-controller">true</prop> <prop key="eclipselink.jdbc.batch-writing">JDBC</prop> <prop key="eclipselink.jdbc.batch-writing.size">200</prop> <prop key="eclipselink.logging.level">SEVERE</prop> <prop key="eclipselink.logging.level">FINE</prop> <prop key="eclipselink.logging.level.sql">FINE</prop> ``` I suspect that the statement caching is not working as expected. Can someone provide any more information? I do have the property eclipselink.jdbc.cache-statements set to true. The application on the previous version of eclipselink was working fine in these scenarios. Has anything changed in newer version of eclipselink which could cause this? Let me know if I need to share any more information.
On Google Sheets (and only built-in functions allowed, no Google Apps Script) Is it possible to simulate pipe function?
|google-sheets-formula|
null
> I expect to first have `hi` in my console then the error and at the end `why` That's what you'd get **if** you were handling the rejection of the promise, like this: <!-- begin snippet: js hide: false console: true babel: false --> <!-- language: lang-js --> const test = new Promise((resolve, reject) => { console.log("hi"); throw new Error("error"); }); test .catch((error) => console.error(error)) .finally(() => { console.log("why") }); <!-- end snippet --> ...but your code isn't handling rejection, so the rejection isn't reported until the environment's unhandled rejection code kicks in, which isn't until after all the code explicitly handling the promise has been executed. As you've said in a comment, `new Promise` and the execution of the function you pass it are all synchronous, but the error thrown in that function isn't unhandled, it's handled by the `Promise` constructor and converted to a promise rejection (which, *later*, is unhandled). So the sequence is: 1. Create a promise 2. Output `hi` 3. Reject the promise with the error 4. Attach a `finally` handler to it 5. Run any appropriate handlers attached to the promise (since it's settled), in this case your `finally` handler 1. Output `why` 2. Reject the promise created by `finally` 6. Determine that the rejection is unhandled and report it
#include <stdio.h> #define N 10 int main() { int a[N], i, pos; printf("\n\nΕισαγωγή 10 ακεραίων\n"); for (i=0; i<N; i++) { printf("%2d : ", i+1); scanf("%d", &a[i]); } pos = 0; for (i=1; i<N; i++) { if (a[pos] < a[i]){ pos = i;}} printf("\n\nΗ μέγιστη τιμή είναι %d και βρέθηκε στη θέση %d\n\n", a[pos],pos+1); return 0; }" This is the program/code that is found in my e-class' lectures and the thing that literally makes no sense for me, first of all, is the "i++" as "change condition" (I have no idea what is called in English) in "for" repetition statements twice, that normally/logically it is to be expected to add the "position"-variable i twice until it reaches N since we got two "for" repetition statement sand in the program and the "i+1" of printf in the first "for" repetition statement which is also repeated and should be also repeated. Logically, doesn't that add the position-variable "i" thrice in the program every time? Logically this is the thing is must do but when I run it this actually doesn't happen and it operates as we want it/expect it to. Furthermore, I have queries about "a[pos]" that at the start is "a[0]" and with "pos+1".. Since there is no position 0 and we start from "i+1" with the printf function then what is the position 0 and what is its value? Is "i=1" the position 0? Furthermore since we got "pos=i" then why the final printf has to print one position after this with "pos+1"? Considering that every time the a[pos] value-variable is smaller than the a[i] value the position becomes equal with i. This is the sum of my queries.
Solve me please a query of a short program about "Maximum Value of an Array"
how to play a sounds in c# forms?
|c#|windows|forms|audio|settings|
null
That’s the most likely reason. Using a dependency walker is your best option I like to use this https://github.com/lucasg/Dependencies You can add search directories so you can eliminate the AutoCAD dependencies
I wrote a bot to help post some vacation photos, and it had been working well for a few months, but lately I've been getting the following error: ``` Traceback (most recent call last): File "/home/pi/.local/lib/python3.11/site-packages/instagrapi/mixins/private.py", line 359, in _send_private_request response.raise_for_status() File "/usr/lib/python3/dist-packages/requests/models.py", line 1021, in raise_for_status raise HTTPError(http_error_msg, response=self) requests.exceptions.HTTPError: 400 Client Error: Bad Request for url: https://i.instagram.com/api/v1/media/configure_sidecar/ During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/home/pi/Desktop/PostScheduler/with_instagrapi.py", line 133, in <module> main() File "/home/pi/Desktop/PostScheduler/with_instagrapi.py", line 20, in main run_bot(path, post) File "/home/pi/Desktop/PostScheduler/with_instagrapi.py", line 77, in run_bot bot.album_upload(paths=album, File "/home/pi/.local/lib/python3.11/site-packages/instagrapi/mixins/album.py", line 213, in album_upload raise e File "/home/pi/.local/lib/python3.11/site-packages/instagrapi/mixins/album.py", line 202, in album_upload configured = (configure_handler or self.album_configure)( ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/pi/.local/lib/python3.11/site-packages/instagrapi/mixins/album.py", line 281, in album_configure return self.private_request( ^^^^^^^^^^^^^^^^^^^^^ File "/home/pi/.local/lib/python3.11/site-packages/instagrapi/mixins/private.py", line 541, in private_request raise e File "/home/pi/.local/lib/python3.11/site-packages/instagrapi/mixins/private.py", line 526, in private_request self._send_private_request(endpoint, **kwargs) File "/home/pi/.local/lib/python3.11/site-packages/instagrapi/mixins/private.py", line 448, in _send_private_request raise UnknownError(**last_json) instagrapi.exceptions.UnknownError: Sidecar has 1 child. It requires 2 or more children. ``` Has something changed about instagram's API? Has something changed with instagrapi? I've tried looking at the project github but can't find any issues, reported bugs, or updates.
Instagrapi recently showing HTTPError and UnknownError
|python|instagram|instagrapi|
null
As noted in the comments, an `awk` solution is simple. For example: ``` awk '!index($0,q) || ++c>n' n=3 q=please "$filename" ``` or slightly more confusingly but more efficiently (since we can stop checking lines after we've found three matches): ``` awk 'c==n || !index($0,q) || !++c' n=3 q=please "$filename" ``` --- It is not very convenient to try to count with `sed`, although it is possible. Parameterising arguments is also complicated. Ignoring both those issues, here is a sed script to delete the first 3 occurrences of lines containing "please": ``` sed ' /please/ { x s/././3 x t x s/^/ / x d } ' "$filename" ``` Applying either script to: ``` 1 leave this line alone 2 leave this line alone 1 please delete this line 3 leave this line alone 2 please delete this line 4 leave this line alone 5 leave this line alone 3 please delete this line 6 leave this line alone 4 please leave this line alone 7 leave this line alone ``` produces: ``` 1 leave this line alone 2 leave this line alone 3 leave this line alone 4 leave this line alone 5 leave this line alone 6 leave this line alone 4 please leave this line alone 7 leave this line alone ``` As "one-liner": ``` sed -e'/please/{x;s/././3;x;t' -e'x;s/^/ /;x;d;}' "$filename" ```
Fix git submodules after rewriting history of a submodule
|git|git-submodules|
{"Voters":[{"Id":13658399,"DisplayName":"NickW"},{"Id":12638118,"DisplayName":"Robert Kossendey"},{"Id":9214357,"DisplayName":"Zephyr"}],"SiteSpecificCloseReasonIds":[16]}
Laravel by default provides support for multiple database connections and you can dynamically switch between them. Here's how you can handle multiple database connections. **Define Database Connections in `config/database.php`** ``` 'connections' => [ 'mysql' => [ 'driver' => 'mysql', 'host' => env('DB_HOST', '127.0.0.1'), 'database' => env('DB_DATABASE', 'forge'), 'username' => env('DB_USERNAME', 'forge'), 'password' => env('DB_PASSWORD', ''), 'charset' => 'utf8mb4', 'collation' => 'utf8mb4_unicode_ci', 'prefix' => '', 'strict' => true, 'engine' => null, ], 'pgsql' => [ 'driver' => 'pgsql', 'host' => env('DB_HOST', '127.0.0.1'), 'port' => env('DB_PORT', 5432), 'database' => env('DB_DATABASE', 'forge'), 'username' => env('DB_USERNAME', 'forge'), 'password' => env('DB_PASSWORD', ''), 'charset' => env('DB_CHARSET', 'utf8'), 'prefix' => env('DB_PREFIX', ''), 'schema' => env('DB_SCHEMA', 'public'), 'sslmode' => env('DB_SSL_MODE', 'prefer'), ], ], ``` NB: you can have as many connections as needed, irrespective of the driver, ie, multiple MySQL connections, etc. **Switching Between Connections** In your Eloquent models or queries, you can specify the connection to use ``` // Use the default connection (mysql) $users = DB::table('users')->get(); // Use a specific connection $users = DB::connection('pgsql')->table('users')->get(); ``` **Dynamic Connection Switching** ``` $connectionName = 'pgsql'; $users = DB::connection($connectionName)->table('users')->get(); ``` **Raw Queries** You can also execute raw queries using specific connection ``` $users = DB::connection('pgsql')->select('select * from users'); ``` **Cross-Database Joins** I've personally tested this in one of my projects, doing cross-database join. You can specify the connection for each table in the join. ``` $users = DB::table('mysql_users') ->join('pgsql.other_table', 'mysql_users.id', '=', 'other_table.user_id') ->select('mysql_users.*', 'other_table.column') ->get(); ``` Always adjust your migrations, models, and queries when working with multiple databases. Useful links 1. [Using Multiple Database Connections Laravel][1] 2. [Multiple DB Connections in Laravel][2] [1]: https://laravel.com/docs/10.x/database#using-multiple-database-connections [2]: https://fideloper.com/laravel-multiple-database-connections
I think you need to use `AND` instead of `OR`: SELECT ld.status, ld.lead_name FROM DATAWAREHOUSE.SFDC_STAGING.SFDC_LEAD AS ld WHERE ld.status <> 'Open' AND ld.lead_name NOT LIKE '%test%' AND ld.lead_name NOT LIKE '%t3st%' AND ld.lead_name NOT LIKE '%auto%' AND ld.lead_name NOT LIKE '%autoXmation%' AND ld.lead_name NOT LIKE 'automation%';
Use EWDK . You should be able to build your driver without issue since it has all dependency. Msbuild -p:Configuration=Release/Debug; Platform=ARM64
I'm coding up a To-Do List website that asks the user for the task, the importance of the task (choose between two options: low, high) and the due date for said task. The plan is to show the user a list and place items that are of more importance or the due date is coming up for at the very front of the list. I know the general gist of storing text inputs but am completely lost as to how to store something like a date. Even more so trying to understand how to set a countdown for the tasks. I'm pretty new to coding as this is the first project that I have started, but any solutions or answers you give I will be grateful for. [This is the page on the site where users give input](https://i.stack.imgur.com/mN6P6.png) [The /addrec route is the backend of the page that should be recieving user input](https://i.stack.imgur.com/HmShs.png)
How to store a date/time in sqlite (or something similar to a date)
|python|html|database|sqlite|flask|
null
I Try to use xdebug in Windows 10. I had used xdebug in My Mac machine. But, In windows 10, I installed xdebug 2.9.8 then config it. It does not work as I thought. Below is my `php.ini` ``` ; XDEBUG Extension [xdebug] zend_extension = c:\wamp64\bin\php\php7.1.33\ext\php_xdebug.dll xdebug.remote_enable = on xdebug.profiler_enable = off xdebug.profiler_enable_trigger = Off xdebug.profiler_output_name = cachegrind.out.%t.%p xdebug.profiler_output_dir ="c:/wamp64/tmp" xdebug.show_local_vars=0 xdebug.remote_host='127.0.0.1' xdebug.remote_port=9003 xdebug.log="c:/wamp64/logs/xdebug.log ``` I confirmed it was intalled correctly using `php -v` Then I installed php-debug extension in my vscode. and then my apache vhost is like below. ``` <VirtualHost *:80> ServerName hello.localhost DocumentRoot "${INSTALL_DIR}/www/hello" <Directory "${INSTALL_DIR}/www/hello/"> Options +Indexes +Includes +FollowSymLinks +MultiViews AllowOverride All Require local </Directory> </VirtualHost> ``` This is all my settings about debugging php. My expectation is to trigger browser to xdebug server running in vscode When I request to my apache hosts `hello.localhost`. But It does not work. I confirmed any other script worked well for debugging scripts such as debugging current scripts and built-in server configs automatically configured in php-debug extension. I wanna to try is Listen for xdebug script in vscode. It does not work. What does I have to configure more? [![xdebug][1]][1] [![xdebug2][2]][2] [1]: https://i.stack.imgur.com/mmqcJ.png [2]: https://i.stack.imgur.com/K8WmG.png And below is my vscode configure for xdebug. ``` { "version": "0.2.0", "configurations": [ { "name": "Listen for Xdebug", "type": "php", "request": "launch", "port": 9003 } ] } ```
I work in a windows form application. i wanna make a setting page for my program. in this form i have music for the total of my program and i have sound for my button, it sounds when you click on a button. i can off them and on them. my problem, is sounds of buttons. when i off the sound in the setting and it just off for the setting form, and when i go to another form and setting page is still open the sound of button is not off. and it sound when i click. page setting: ``` using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.Media; using WMPLib; namespace WindowsFormsApp3 { public partial class Form1 : Form { WindowsMediaPlayer playerr = new WindowsMediaPlayer(); public WindowsMediaPlayer button = new WindowsMediaPlayer(); public bool s ; public bool p ; public Form1() { InitializeComponent(); this.StartPosition= FormStartPosition.Manual; this.Location = new Point(300, 150); } private void Form1_Load(object sender, EventArgs e) { //if ( t==true ) playerr.URL = "aurora_runaway.mp3"; playerr.controls.play(); } private void button1_Click(object sender, EventArgs e) { if (pictureBox3.Visible == false && pictureBox4.Visible == true) { button.URL = "notifications-sound-127856.mp3"; button.controls.play(); } } private void pictureBox1_Click(object sender, EventArgs e) { playerr.controls.play(); pictureBox1.Visible= false; pictureBox2.Visible= true; } private void pictureBox2_Click(object sender, EventArgs e) { playerr.controls.stop(); pictureBox2.Visible = false; pictureBox1.Visible =true; } private void pictureBox3_Click(object sender, EventArgs e) { pictureBox3.Visible = false; pictureBox4.Visible = true; s = true; p = false; } private void pictureBox4_Click(object sender, EventArgs e) { pictureBox4.Visible = false; pictureBox3.Visible = true; s = false; p = true; } private void button2_Click(object sender, EventArgs e) { new Form3().ShowDialog(); } } } ``` another page: ``` using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace WindowsFormsApp3 { public partial class Form3 : Form { Form1 ff = new Form1(); public Form3() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { if (ff.p == true && ff.s == false) { ff.button.URL = "notifications-sound-127856.mp3"; ff.button.controls.play(); } } } } ```
|c|
null
|javascript|html|jquery|css|css-animations|
I one of my current projects I am using Split.js. Given the complexity of that project I find it necessary to take the original SplitJS code and fork it one of my own ES6 classes. The process has gone smoothly but this line const defaultGutterStyleFn = (dim, gutSize) => ({ [dim]: `${gutSize}px` }) has got me stumped. I am guesssing that defaultGutterStyleFn returns a CSS rule that bears the form `{dim:NNpx}` where - `dim` is probably a dimension (height, width etc) - `gutSize` is a numeric value However, I do not see how the code I have quoted above would possibly doing this. Perhaps I have stumbled upon a JS/ES feature that I don't know?
I'm encountering difficulties with extracting request data in a Flask-Lambda application deployed on AWS Lambda using AWS SAM (Serverless Application Model). Here's a breakdown of my concerns: 1. **Background:** - I've developed a Flask-Lambda application intended to handle various HTTP requests, including POST requests, deployed on AWS Lambda using AWS SAM. - Initially, I used SAM CLI to create a basic "hello_world" template, and I successfully built and deployed the application. GET requests function as expected. 2. **Issue:** - However, I'm facing challenges with extracting request data specifically in POST requests. - When attempting to retrieve the request body using methods like **`request.form.to_dict()`**, **`request.data`**, or **`request.get_json()`**, I consistently receive either empty dictionaries or encounter exceptions. 3. **Troubleshooting Steps Taken:** - I've verified that the Lambda function is properly configured to handle POST requests. - The API Gateway integration request mapping templates appear to be set up correctly to pass the request body to the Lambda function. - I've ensured that Flask-Lambda is integrated correctly within my application and that routes are defined accurately. - Additionally, I've attempted to debug the issue by introducing logging statements in the Lambda function. 4. **Request for Assistance:** - Despite these efforts, I'm still unable to extract the request data successfully. - I'm seeking guidance on potential solutions or further debugging steps to resolve this issue and successfully retrieve request data in POST requests within my Flask-Lambda application deployed on AWS Lambda via AWS SAM. Sample Input : ``` { "id":"1", "name":"Bob", "age":"40" } ``` Sample Code ``` import json import boto3 from flask_lambda import FlaskLambda from flask import request, jsonify app = FlaskLambda(__name__) ddb = boto3.resource('dynamodb') table = ddb.Table('mytable') @app.route('/') def healthCheck(): data = { "message":"Healthy" } return ( json.dumps(data), 200, {"Content-Type":"application/json"} ) @app.route('/leads', methods=["GET","POST"]) def list_or_add_leads(): if request.method == 'GET': data = table.scan()['Items'] return (json.dumps(data), 200, {"Content-Type":"application/json"}) elif request.method == 'POST': try: # Extract raw request body print(event) print(request.body) # table.put_item(Item=request_body) data = { "message":"Successful" } return (json.dumps(data), 200, {"Content-Type":"application/json"}) except Exception as e: data = {"exception":str(e)} return (json.dumps(data), 400, {"Content-Type":"application/json"}) ```
Suppose I have colmap camera poses, is it possible and how to obtain a new view of input image `I` (planar object) from a different viewpoint/camera pose using those poses? Colmap camera poses has following data: ``` extr = cam_extrinsics[key] intr = cam_intrinsics[extr.camera_id] height = intr.height width = intr.width uid = intr.id R = np.array(qvec2rotmat(extr.qvec)) T = np.array(extr.tvec) if intr.model=="SIMPLE_PINHOLE": focal_length_x = intr.params[0] FovY = focal2fov(focal_length_x, height) FovX = focal2fov(focal_length_x, width) fx = fy = intr.params[0] cx = intr.params[1] cy = intr.params[2] elif intr.model=="PINHOLE": focal_length_x = intr.params[0] focal_length_y = intr.params[1] FovY = focal2fov(focal_length_y, height) FovX = focal2fov(focal_length_x, width) fx = intr.params[0] fy = intr.params[1] cx = intr.params[2] cy = intr.params[3] ``` ``` class DummyCamera: def __init__(self, uid, R, T, FoVx, FoVy, K, image_width, image_height): self.uid = uid self.R = R self.T = T self.FoVx = FoVx self.FoVy = FoVy self.K = K self.image_width = image_width self.image_height = image_height self.projection_matrix = getProjectionMatrix(znear=0.01, zfar=100.0, fovX=FoVx, fovY=FoVy).transpose(0,1).cuda() self.world_view_transform = torch.tensor(getWorld2View2(R, T, np.array([0,0,0]), 1.0)).transpose(0, 1).cuda() self.full_proj_transform = (self.world_view_transform.unsqueeze(0).bmm(self.projection_matrix.unsqueeze(0))).squeeze(0) self.camera_center = self.world_view_transform.inverse()[3, :3] ``` Colmap camera poses are computed on different flat object, size of images used in this computation is different from size of image `I` going from this: ![input image](https://i.stack.imgur.com/SyQ5q.jpg) to this after transformation using comap pose: ![expected image](https://i.stack.imgur.com/b6k8V.jpg)
### Preamble Reading the title of your question, I think you have to read quietly the *`address chapter*`* in `info sed`! Understanding the difference between *addressing* and *commands*! `s`, like `p` are commands! So your request is about *addressing* for *executing a command*. ### Address range and address for commands Little sample: <!-- language: lang-bash --> LANG=C info sed | sed -ne ' /^4.3/,/^5/{ /^\o47/{ :a; N; /\n / ! ba; N; p } }' - From the line that ***begin by `4.3`*** to the line that ***begin by `5`***, - On lines that **begin by a *quote `'`***, - Place a *label* *`a`*. - Append next line - If current buffer ***does not contain*** a *newline* followed by **one *space***, the branch to *label `a`*. - Append one more line - print current buffer. <!-- language: lang-none --> '/REGEXP/' This will select any line which matches the regular expression REGEXP. If REGEXP itself includes any '/' characters, each must be '\%REGEXP%' (The '%' may be replaced by any other single character.) '/REGEXP/I' '\%REGEXP%I' The 'I' modifier to regular-expression matching is a GNU extension which causes the REGEXP to be matched in a case-insensitive manner. '/REGEXP/M' '\%REGEXP%M' The 'M' modifier to regular-expression matching is a GNU 'sed' extension which directs GNU 'sed' to match the regular expression '/[0-9]/p' matches lines with digits and prints them. Because the second line is changed before the '/[0-9]/' regex, it will not match and will not be printed: $ seq 3 | sed -n 's/2/X/ ; /[0-9]/p' 1 '0,/REGEXP/' A line number of '0' can be used in an address specification like '0,/REGEXP/' so that 'sed' will try to match REGEXP in the first 'ADDR1,+N' Matches ADDR1 and the N lines following ADDR1. 'ADDR1,~N' Matches ADDR1 and the lines following ADDR1 until the next line whose input line number is a multiple of N. The following command ### Please, RTFM: Have a look at `info sed`, search for *`* sed addresses`*, then *`* Regexp Addresses`*: > ‘/REGEXP/’ > This will select any line which matches the regular expression > REGEXP. If REGEXP itself includes any ‘/’ characters, each must be > escaped by a backslash (‘\’). > ... > > ‘\%REGEXP%’ > (The ‘%’ may be replaced by any other single character.) > > This also matches the regular expression REGEXP, but allows one to > use a different delimiter than ‘/’. This is particularly useful if > the REGEXP itself contains a lot of slashes, since it avoids the > tedious escaping of every ‘/’. If REGEXP itself includes any > delimiter characters, each must be escaped by a backslash (‘\’). ### In fine, regarding your question: So you have to precede your 1st *delimiter* by a backslash `\`: $ echo A | sed -ne '\#A#p' A
null
1. I have a table of groups. 2. I'm searching for a way so that "Group 2" will get updated when "Group 1" changes. ![enter image description here](https://i.stack.imgur.com/QKKsF.png) Please note that * I want this without any Script or HelperColumn. * I don't want to use Named Ranged in dropdown criteria. Thanks in advance. Sample File: https://docs.google.com/spreadsheets/d/1PowepsBJLymzZSr6ODR_Gxioxvn3WDDYGctwZVHbvqg/edit?usp=sharing
I had the same problem and I resolved by deleting all the properties after httpOnly from the response. I also suggest you to ditch the httpOnly and go save the token in the localstorage directly. It is safe, contrary to what many other say
You have two primary challenges in your question: 1. separating the space-separated word read into `input`; and 2. storage for each word. While there are may ways to "tokenize" (separate) input, when wanting space-separated words, a very simple way to do that is to just read with `fgets()` to fill `input` (as you have done) and then simply loop over each word in `input` using `sscanf()` with the `%s` conversion specifier (with a proper *field-width* modifier to protect your array bounds) and using the `%n` pseudo-conversion specifier to capture the number of character read on each call to `sscanf()` so you can capture the next word by providing an `offset` from the beginning of `input`. Using multiple character arrays to hold each word quickly becomes unwieldy (as I suspect you have found). What if you don't know the number of words you are going to read? Since you emphasize using a *"simple"* approach, by far the simplest is to use a 2D array of characters where each row holds a word. Now you can simply reference each word by the index for the 2D array (a 2D array actually being a 1D "array-of-arrays" in C - so the first index points to the 1st array, and so on). Here you are limited to reading no more than your *rows* number of words -- but with a reasonable number of rows set, that provides a great deal of flexibility. You must remember to check each time you add a word against the number of rows you have so you don't attempt to add more words to your 2D array than you have rows for. A slightly more complex approach would be to declare a *pointer-to-array* of characters which would allow you to reallocate storage for more words with the only limit being the amount of memory your computer has. (a pointer-to-array allocation also has the benefit of a single-free) One step further would be to allocate the exact number of characters needed to hold each word and the exact number of pointers needed to keep track of each word in your collection -- but that gets well beyond your "simple" request. Just know there are more flexible ways you will learn in the future. *What Is This Simple Approach?* Before looking at the code, let's think through what you want to do. You will need to: 1. Prompt the user and read the words into `input` using `fgets()` 2. Loop checking that you still have a row available to hold the next word; and 3. Pass `input` plus an `offset` to `sscanf()` - separating the next word with `"%s"` (with appropriate *field-width* modifier) to capture the word (you can use a temporary array to hold the separated word and copy to your array, or you can attempt the read directly into your 2D array providing an index); and - saving the number of characters `sscanf()` read to process that word with `"%n"` so you add that to the offset within `input` to read the next word on your next call to `sscanf()`. 4. You ALWAYS validate that `sscanf()` (or any function) succeeds before going further and handle any error that may arise, 5. Increment the word count (`nwords`) after successfully adding the word to your 2D array of words; and 6. Add the number of characters used by `sscanf()` to an `offset` variable so you are ready to process the next word. 7. After your loop with `sscanf()` ends, you simply loop `nwords` times outputting each word in the format you desire. A short bit of code that does that could be: ```c #include <stdio.h> #include <string.h> #define MAXWRDS 64 #define WORDLN 64 #define MAXCHR 1024 int main (void) { char input[MAXCHR] = "", /* storage for line of input */ words[MAXWRDS][WORDLN] = {""}, /* 2D array of MAXWRDS WORDLN words */ word[WORDLN] = ""; /* temporary storage for each word */ size_t nwords = 0; /* number of words (tokens) read */ int offset = 0, nchars = 0; fputs ("input: ", stdout); /* prompt */ /* validate EVERY input */ if (fgets (input, sizeof input, stdin) == NULL) { return 1; } /* Loop over every whitespace separated sequence * of chars reading into word. Use sscanf() to read * whitespace separated sequences of chars. Use %n to * get the number of characters processed in each call to * sscanf() to provide offset to next word in input. * * Do NOT forget field-width modifier to protect word array bounds * for reading into word and check you read no more than MAXWRDS words. */ while (nwords < MAXWRDS && sscanf (input + offset, "%63s%n", word, &nchars) == 1) { strcpy (words[nwords], word); /* copy word to array at nwords index */ nwords += 1; /* increment nwords */ offset += nchars; /* increment offset by no. of chars */ } putchar ('\n'); /* optional newline before order output */ /* loop over each word stored in words outputting order */ for (size_t i = 0; i < nwords; i++) { printf ("order %2zu: %s\n", i + 1, words[i]); } } ``` Using a `#define` up top for each constant you need provides a convenient place to make a single change should you need to adjust how your code behaves later. **Example Use/Output** Compiling the code (ALWAYS with *full-compiler-warnings-enabled*), your code will now do what you want. With the code compiled to the file named `sscanfwordsinput2d`, you can do: ```none $ ./sscanfwordsinput2d input: my dog has fleas but my cat has none -- lucky cat! order 1: my order 2: dog order 3: has order 4: fleas order 5: but order 6: my order 7: cat order 8: has order 9: none order 10: -- order 11: lucky order 12: cat! ``` If you are using gcc / clang, a good compile string for the code, with full-warnings, would be: ```none $ gcc -Wall -Wextra -pedantic -Wshadow -Werror -std=c11 -O2 -o sscanfwordsinput2d sscanfwordsinput2d.c ``` If using Microsoft `cl.exe` as your compiler (VS, etc..), then a roughly equivalent compile string would be: ```none $ cl /W3 /wd4996 /Wx /O2 /Fesscanfwordsinput2d /Tcsscanfwordsinput2d.c ``` Looks things over and let me know if you have questions.
For windows users who are experiencing this error on a .netcore webapi a quick fix would be to change the port number in your application url which can be found in the found in the launchSettings.json file under the properties folder in Visual Studio IDE. "profiles": { "https": { "commandName": "Project", "dotnetRunMessages": true, "launchBrowser": false, "launchUrl": "weatherforecast", **"applicationUrl": "https://localhost:5002;http://localhost:5003",** "environmentVariables": { "ASPNETCORE_ENVIRONMENT": "Development" } There are certainly other ways to resolve this, but this was a quick approach I used. For example, after changing the port no. in the application url I used https://localhost:5002/weatherforecast for the weatherforecast api.
I suggest using mzhash32 a very simple, fast function with a number of collisions very close to the Universal Hashing Function public static int mzHash32(final byte[] data, int start, int length, int seed) { int hash = 0x95DE1432 ^ seed; for(int i = 0; i < length; i++) hash = (0xA8657C5B * (i + data[start + i])) ^ (hash << 2) ^ (hash >>> 2); return hash; } Source: https://github.com/matteo65/mzHash32 64 bit version: https://github.com/matteo65/mzHash64
In gradle-wraper.properties change the download link to this distributionUrl=https://downloads.gradle.org/distributions/gradle-8.6-bin.zip
For the node-fetch library for Node which is a non-native implementation of the Fetch API for Node.js. For the native Fetch API included native in Node >=18 use the [tag:fetch-api] tag with [tag:node.js]. - [GitHub][1] - [Documentation for v2][2] - [npm][3] [1]: https://github.com/node-fetch/node-fetch [2]: https://github.com/node-fetch/node-fetch/tree/2.x#readme [3]: https://www.npmjs.com/package/node-fetch
For the node-fetch library for Node which is a non-native implementation of the Fetch API for Node.js. For the native Fetch API included native in Node >=18 use the [fetch-api] tag with [node.js].
|javascript|node.js|node-fetch|
{"Voters":[{"Id":147356,"DisplayName":"larsks"},{"Id":10008173,"DisplayName":"David Maze"},{"Id":3306020,"DisplayName":"Magnas"}],"SiteSpecificCloseReasonIds":[18]}
I am trying to adopt functional programming style on Google Sheets and have got quite satisfactory results, such as functors, recursive functions and currying functions. However, I am stuck by the pipe function. It is quite easy to realize the pipe function with other modern programming languages, because they allow us to wrap functions in an array, which is able to be unwrapped and returns us functions functioning as well as the original ones. For example, with JavaScript, we have ```js function pipe(){ return input => [...arguments].reduce((result, func)=>func(result), input) } ``` so that we are allowed to do this: ```js pipe(plusThree, multiplyFour, minusSeven)(2) ``` However, on Google Sheets, it seems that the only way creating an array is to put items in a "virtual" range (a bundle of cells), No matter whether we do MAKEARRAY or {"func", "arr"}. Unfortunately, once we put a function in a cell, it immediately executes and return an error. Therefore, the formula I tried fails ``` =LET( plusOne, LAMBDA(num, num+1), multTwo, LAMBDA(num, num*2), pipe, LAMBDA(functions, LAMBDA(input, LET( recursiveFunction, LAMBDA(self, idx, IF( idx < COLUMNS(functions), CHOOSECOLS(functions, idx)(self(self, idx+1)), CHOOSECOLS(functions, idx)(input) ) ), recursiveFunction(recursiveFunction, 1)))), result, pipe({plusOne, multTwo})(5), result ) ``` (My apologies to use a recursive function. It would be much easier to read if I wrote it with REDUCE, which I tried for the very first time and failed, sadly.) The key point is that I do not have any other way unwrapping an array of functions and get the unwrapped functions in it function as well as the ones before wrapping! And LAMBDA in Google Sheets does not allow us to have uncertain number of arguments in a function (which is soooo frustrating). Zero argument is not allowed, either. (We can use a meaningless placeholder to simulate it, though.) So, even CHOOSE seems a candidate to iterate arguments without wrapping it in an (range-like) array, our pipe function cannot use it as the key part to iterate functions as arguments. So, I am really eager to know whether it is a way simulating pipe function on Google Sheets. The spreadsheet I am working on is noted here, for anyone it may concern: https://docs.google.com/spreadsheets/d/1Z1_udcul2sNtzBtJbCeDlnMR2J4JymytfScKFyUtiw8/edit#gid=1987950802 Any discussions or ideas are much appreciated!
I am trying to run a blink LED program on my [STM32F401CCU6 board](https://robu.in/product/stm32f401ccu6-minimum-system-board-microcomputer-stm32-arm-core-board/), and I am using basic CLI tools (in Linux) like `arm-none-eabi-gcc` or `dfu-util` (or `openocd`) for learning purposes. I have followed [this tutorial](https://kleinembedded.com/stm32-without-cubeide-part-1-the-bare-necessities/) to create the basic program, with one change. I do not have ST-Link, and am trying to use the USB-C port that comes with the board for flashing (and thus, using `dfu-util`). It does not rely on any STM header files (except `stdint.h`, which is for `uint32_t`, and is also from the compiler). The command I used to upload this is: ```sh $ dfu-util -a 0 -s 0x08000000:leave -D ./main.elf dfu-util 0.11 Copyright 2005-2009 Weston Schmidt, Harald Welte and OpenMoko Inc. Copyright 2010-2021 Tormod Volden and Stefan Schmidt This program is Free Software and has ABSOLUTELY NO WARRANTY Please report bugs to http://sourceforge.net/p/dfu-util/tickets/ dfu-util: Warning: Invalid DFU suffix signature dfu-util: A valid DFU suffix will be required in a future dfu-util release Opening DFU capable USB device... Device ID 0483:df11 Device DFU version 011a Claiming USB DFU Interface... Setting Alternate Interface #0 ... Determining device status... DFU state(10) = dfuERROR, status(10) = Device's firmware is corrupt. It cannot return to run-time (non-DFU) operations Clearing status Determining device status... DFU state(2) = dfuIDLE, status(0) = No error condition is present DFU mode device DFU version 011a Device returned transfer size 2048 DfuSe interface name: "Internal Flash " Downloading element to address = 0x08000000, size = 9528 Erase [=========================] 100% 9528 bytes Erase done. Download [=========================] 100% 9528 bytes Download done. File downloaded successfully Submitting leave request... Transitioning to dfuMANIFEST state ``` [This](https://pastebin.com/uESA2DHW) is the objdump of `main.elf`. However, both the on-board LED and the LED connected to A5 pin do not glow. I even tried switching the code to point to the C13 on-board LED, but still it does not glow. I got this `dfu-util` from the AUR. Thank you in advance.
I try to add an "add" button to a sidebar within a `NavigationSplitView` of a `macos` apps same as found in the Xcode window. Using this code within the sidebar-view does create the button at the top of the view but it is NOT going to hide when collapsing the sidebar. .toolbar { ToolbarItem(placement: .primaryAction) { Button(action: addUser) { Label("Create New User", systemImage: "person.crop.circle.badge.plus") } .help("New User") } How to create a sidebar-view specific button at the bottom that sticks to the sidebar and is hidden when the sidebar is collapsing? Thanks! [![enter image description here][1]][1] [1]: https://i.stack.imgur.com/vW5xf.png
SwiftUI Sidebar with collapsing Button
|macos|button|swiftui|sidebar|
In accountsList.vue i call the following script where i commented a lot out because im doing a serious refactor and i wanted to isolate the problem. "balance" has a proper value and is set, i checked. <script setup> import Account from "@/Pages/Partials/AccountItem.vue"; import {UseAccountsStore} from "@/Stores/UseAccountsStore.js" const props = defineProps({ editMode: Boolean, balance: Object }) const accountsStore = UseAccountsStore(); // console.log(props.balance) accountsStore.balance = props.balance; accountsStore.getAccounts() // const balanceStore = UseBalanceStore() // const balanceItemsStore = UseCategoryItemsStore() function update() { // accountsStore.getTotal() // balanceStore.getGrandTotal() } This is my UseAccountsStore import {defineStore} from "pinia"; import {ref} from "vue"; export const UseAccountsStore = defineStore('AccountStore', () => { const balance = ref(null) const accounts = ref([]) const total = ref(0) function getAccounts() { console.log(balance); axios.get(route('accounts.index', {'id': balance.value.id})) .then((response) => accounts.value = response.data) } function getTotal() { axios.get(route('accounts.total')) .then((response) => total.value = response.data) } function addAccount(account) { accounts.value.push(account) } return {accounts, total, getAccounts, getTotal, addAccount} }) What i don't get is that my "console.log(balance);" returns an empty object. I tried to use a setter but that also results in a null value. Does anyone know why? What am i doing wrong?
@gog mentioned, For the same reason you wrote show() with parentheses and not just show.