instruction
stringlengths
0
30k
I am trying to make a API call and get all data related to orders and show that in a list. I have tested the following which are working as expected. 1 - Adding static data to the view. 2 - The api call is returning the data and is being parsed properly. The only thing which is not happening is when i am updating the data in the adapter using orderAdapter!!.notifyDataSetChanged() its not updating the data. class OrderHistoryActivity : AppCompatActivity() { lateinit var recyclerView: RecyclerView var orderAdapter: OrderAdapter? = null var models: MutableList<OrderModel>? = null lateinit var prefs: Prefs override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_order_history) recyclerView = findViewById(R.id.orderRecyclerView) models = ArrayList() prefs = Prefs(this@OrderHistoryActivity) GlobalScope.launch(Dispatchers.Default) { runCatching { Log.d("FUNCTION", "API TO GET ORDERS INIT ${prefs.token} ${prefs.userId}") try { val response = withTimeout(REST_API_TIMEOUT) { RetrofitClient(this@OrderHistoryActivity).getApi().getOrders( prefs.token, prefs.userId,"get" ).execute().parseResult<OrdersResponse>() } Log.d("FUNCTION", "API TO GET RESULTS -> RESPONSE ${Gson().toJson(response)} ") response.lastReadDate = System.currentTimeMillis() var i = 0 (models as ArrayList<OrderModel>).clear() // CLEAR OLD LIST // while (i < response.data.size) { val data = response.data[i] val order_id=data.id val order_status=data.status val order_date=data.date Log.d("FUNCTION", "API TO GET IND RESULT -> RESPONSE ${order_id} ${order_status}") (models as ArrayList<OrderModel>).add(OrderModel("${order_id}", "Nov 20, 2024", "${order_status}")) i++ } // UPDATE DATA // orderAdapter!!.notifyDataSetChanged() Log.d("FUNCTION", "API TO GET IND RESULT MODELS -> RESPONSE ${models}") } catch (ex: RestApiException) { var err = OnApiErrorEvent(ex.message ?: ex.toString()) Log.d("FUNCTION","rest exp") Log.d("FUNCTIONwwr","${err}") } catch (ex: Exception) { var err = OnApiErrorEvent(ex.message ?: ex.toString()) } catch (ex: CancellationException) { } finally { launch(Dispatchers.Main) { // viewModel.progress.set(false) } } } } for (i in 0..7) { (models as ArrayList<OrderModel>).add(OrderModel("#14524$i", "Nov 3, 2022", "Completed")) } recyclerView.setLayoutManager(LinearLayoutManager(this@OrderHistoryActivity)) orderAdapter = OrderAdapter(this@OrderHistoryActivity, models) recyclerView.setAdapter(orderAdapter) Log.d("FUNCTION", "RESULT - > STATIC DATA") }
Duplicate and Incorrec Legends shown in the plot
|dataframe|matplotlib|
If you look at the page, the borders overlap and thicken due to the detail section. Why doesn't the following work? I tried removing all the borders of the details class with CSS, but it didn't work. The bottom border is always there and overlaps. [enter image description here][1] `td colspan="100%" class="details"style="padding: 0 !important; border-bottom: none !important;" ` it does not work. ``` <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <!-- Font Awesome --> <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css" rel="stylesheet"> <!-- Bootstrap CSS --> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet"> <!-- Bootstrap Bundle JS --> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script> <style> .list-group { max-height: 320px; /* veya istediğiniz başka bir değer */ overflow-y: auto; } </style> </head> <body> <div class="container-fluid"> <div class="row"> <div class="col-md-12 ps-0 pe-0"> <div class="table-responsive"> <table class="table table-bordered table-hover"> <thead> <tr> <th scope="col">Kitap</th> <th scope="col">Poz No</th> <th scope="col">Eski Poz No</th> <th scope="col">Tanım</th> <th scope="col">Tür</th> <th scope="col">Birim</th> <th scope="col">Güncel Fiyat</th> <th scope="col">Detay</th> </tr> </thead> <tbody id="table-content"> <tr> <td>Karayolları 2012 ve Sonrası</td> <td>01.001</td> <td>10.100.1001</td> <td>Pist Beton Kaplama Ustası (Hava Meydanları İnş.İçin) </td> <td>Rayiç</td> <td>Kg</td> <td>1415.00 TL</td> <td><b type="button" class="collapse-button" data-bs-toggle="collapse" data-bs-target="#details_251" aria-expanded="false" aria-controls="details_251" onclick="toggleCaret('details_251')"> Detay <i class="ph-bold ph-caret-down caret-icon"></i> </b></td> </tr> <tr class="tr-detail" data-id="251"> <td colspan="100%" class="details" style="padding: 0 !important; border-bottom: none !important;"> <div id="details_251" class="collapse table-details"> <div class="container-fluid"> <li class="list-group-item"> <div class="d-flex align-items-center"> <a href="#" download style="background-color: #efe81d; padding: 6px 15px; color: #0b0b0b; text-decoration: none; border-radius: 4px; margin-left: 20px; transition: background-color 0.3s;" onmouseover="this.style.backgroundColor='#eff81d';" onmouseout="this.style.backgroundColor='#efe81d';"> <i class="fa-solid fa-circle-info pe-2"></i><strong>Detay Sayfasına Git</strong> </a> <a href="#" download style="background-color: #1D6F42; padding: 5px 15px; color: #fff; text-decoration: none; border-radius: 4px; margin-left: 20px; transition: background-color 0.3s;" onmouseover="this.style.backgroundColor='#1DaF42';" onmouseout="this.style.backgroundColor='#1D6F42';"> <i class="fa-regular fa-file-excel pe-1"></i>Analizi İndir </a> </div> </li> <div class="col-md-12"> <div class="row"> <div class="col-md-9 mt-4 d-flex flex-column"> <h4 class="mb-3"><i class="fas fa-cube"></i> Birim Fiyat Tarifi </h4> <div class="d-flex flex-column border rounded bg-white" style="overflow-y: auto; flex-grow: 1; padding: 0;"> <p style="flex-grow: 1; padding: 15px; margin: 0;">Lorem ipsum dolor sit amet consectetur adipisicing elit. Qui ratione, magni iusto voluptates esse dolorem, deleniti accusamus, ipsa corrupti saepe hic vitae porro voluptatum earum soluta maiores molestiae rem officia? Quos veritatis eum amet ipsa saepe recusandae vel ad excepturi obcaecati optio culpa quae assumenda perspiciatis possimus iste numquam ducimus enim nostrum sit, perferendis, harum distinctio. Ratione magnam provident fuga? At harum, voluptate dignissimos ex unde fugiat sit voluptatem ipsa ipsum reiciendis numquam! Natus obcaecati praesentium, in quaerat dolorum ullam magni omnis veritatis, numquam amet, sint voluptatum modi odit culpa? Voluptatem ducimus nisi consequatur consequuntur non quidem quod repudiandae labore saepe amet nulla minima, consectetur ex rerum nam necessitatibus officiis? Voluptatibus recusandae reprehenderit voluptas voluptate architecto illum? Eos, consequuntur molestiae.</p> </div> </div> <div class="col-md-3 mt-4 d-flex flex-column"> <h4 class="mb-3"><i class="fas fa-cube"></i> Birim Fiyatlar</h4> <ul class="list-group flex-grow-1"> <li class="list-group-item d-flex justify-content-between align-items-center"> 2014 <span class="badge-custom" style="font-size: 0.9em;">4.152,21</span> </li> <li class="list-group-item d-flex justify-content-between align-items-center"> 2014 <span class="badge-custom" style="font-size: 0.9em;">4.152,21</span> </li> <li class="list-group-item d-flex justify-content-between align-items-center"> 2014 <span class="badge-custom" style="font-size: 0.9em;">4.152,21</span> </li> <li class="list-group-item d-flex justify-content-between align-items-center"> 2014 <span class="badge-custom" style="font-size: 0.9em;">4.152,21</span> </li> <li class="list-group-item d-flex justify-content-between align-items-center"> 2014 <span class="badge-custom" style="font-size: 0.9em;">4.152,21</span> </li> <li class="list-group-item d-flex justify-content-between align-items-center"> 2014 <span class="badge-custom" style="font-size: 0.9em;">4.152,21</span> </li> <li class="list-group-item d-flex justify-content-between align-items-center"> 2014 <span class="badge-custom" style="font-size: 0.9em;">4.152,21</span> </li> <li class="list-group-item d-flex justify-content-between align-items-center"> 2014 <span class="badge-custom" style="font-size: 0.9em;">4.152,21</span> </li> <li class="list-group-item d-flex justify-content-between align-items-center"> 2014 <span class="badge-custom" style="font-size: 0.9em;">4.152,21</span> </li> <li class="list-group-item d-flex justify-content-between align-items-center"> 2014 <span class="badge-custom" style="font-size: 0.9em;">4.152,21</span> </li> <li class="list-group-item d-flex justify-content-between align-items-center"> 2014 <span class="badge-custom" style="font-size: 0.9em;">4.152,21</span> </li> <!-- Include other years here --> </ul> </div> </div> </div> </div> </div> </td> </tr> <tr> <td>Karayolları 2012 ve Sonrası</td> <td>01.001</td> <td>10.100.1001</td> <td>Pist Beton Kaplama Ustası (Hava Meydanları İnş.İçin) </td> <td>Rayiç</td> <td>Kg</td> <td>1415.00 TL</td> <td><b type="button" class="collapse-button" data-bs-toggle="collapse" data-bs-target="#details_252" aria-expanded="false" aria-controls="details_252" onclick="toggleCaret('details_252')"> Detay <i class="ph-bold ph-caret-down caret-icon"></i> </b></td> </tr> <tr class="tr-detail" data-id="252"> <td colspan="100%" class="details" style="padding: 0 !important; border-bottom: none !important;"> <div id="details_252" class="collapse table-details"> <div class="container-fluid"> <li class="list-group-item"> <div class="d-flex align-items-center"> <a href="#" download style="background-color: #efe81d; padding: 6px 15px; color: #0b0b0b; text-decoration: none; border-radius: 4px; margin-left: 20px; transition: background-color 0.3s;" onmouseover="this.style.backgroundColor='#eff81d';" onmouseout="this.style.backgroundColor='#efe81d';"> <i class="fa-solid fa-circle-info pe-2"></i><strong>Detay Sayfasına Git</strong> </a> <a href="#" download style="background-color: #1D6F42; padding: 5px 15px; color: #fff; text-decoration: none; border-radius: 4px; margin-left: 20px; transition: background-color 0.3s;" onmouseover="this.style.backgroundColor='#1DaF42';" onmouseout="this.style.backgroundColor='#1D6F42';"> <i class="fa-regular fa-file-excel pe-1"></i>Analizi İndir </a> </div> </li> <div class="col-md-12"> <div class="row"> <div class="col-md-9 mt-4 d-flex flex-column"> <h4 class="mb-3"><i class="fas fa-cube"></i> Birim Fiyat Tarifi </h4> <div class="d-flex flex-column border rounded bg-white" style="overflow-y: auto; flex-grow: 1; padding: 0;"> <p style="flex-grow: 1; padding: 15px; margin: 0;">Lorem ipsum dolor sit amet consectetur adipisicing elit. Qui ratione, magni iusto voluptates esse dolorem, deleniti accusamus, ipsa corrupti saepe hic vitae porro voluptatum earum soluta maiores molestiae rem officia? Quos veritatis eum amet ipsa saepe recusandae vel ad excepturi obcaecati optio culpa quae assumenda perspiciatis possimus iste numquam ducimus enim nostrum sit, perferendis, harum distinctio. Ratione magnam provident fuga? At harum, voluptate dignissimos ex unde fugiat sit voluptatem ipsa ipsum reiciendis numquam! Natus obcaecati praesentium, in quaerat dolorum ullam magni omnis veritatis, numquam amet, sint voluptatum modi odit culpa? Voluptatem ducimus nisi consequatur consequuntur non quidem quod repudiandae labore saepe amet nulla minima, consectetur ex rerum nam necessitatibus officiis? Voluptatibus recusandae reprehenderit voluptas voluptate architecto illum? Eos, consequuntur molestiae.</p> </div> </div> <div class="col-md-3 mt-4 d-flex flex-column"> <h4 class="mb-3"><i class="fas fa-cube"></i> Birim Fiyatlar</h4> <ul class="list-group flex-grow-1"> <li class="list-group-item d-flex justify-content-between align-items-center"> 2014 <span class="badge-custom" style="font-size: 0.9em;">4.152,21</span> </li> <li class="list-group-item d-flex justify-content-between align-items-center"> 2014 <span class="badge-custom" style="font-size: 0.9em;">4.152,21</span> </li> <li class="list-group-item d-flex justify-content-between align-items-center"> 2014 <span class="badge-custom" style="font-size: 0.9em;">4.152,21</span> </li> <li class="list-group-item d-flex justify-content-between align-items-center"> 2014 <span class="badge-custom" style="font-size: 0.9em;">4.152,21</span> </li> <li class="list-group-item d-flex justify-content-between align-items-center"> 2014 <span class="badge-custom" style="font-size: 0.9em;">4.152,21</span> </li> <li class="list-group-item d-flex justify-content-between align-items-center"> 2014 <span class="badge-custom" style="font-size: 0.9em;">4.152,21</span> </li> <li class="list-group-item d-flex justify-content-between align-items-center"> 2014 <span class="badge-custom" style="font-size: 0.9em;">4.152,21</span> </li> <li class="list-group-item d-flex justify-content-between align-items-center"> 2014 <span class="badge-custom" style="font-size: 0.9em;">4.152,21</span> </li> <li class="list-group-item d-flex justify-content-between align-items-center"> 2014 <span class="badge-custom" style="font-size: 0.9em;">4.152,21</span> </li> <li class="list-group-item d-flex justify-content-between align-items-center"> 2014 <span class="badge-custom" style="font-size: 0.9em;">4.152,21</span> </li> <li class="list-group-item d-flex justify-content-between align-items-center"> 2014 <span class="badge-custom" style="font-size: 0.9em;">4.152,21</span> </li> <!-- Include other years here --> </ul> </div> </div> </div> </div> </div> </td> </tr> </tbody> </table> </div> </div> </div> </div> </body> </html> ``` <td colspan="100%" class="details"style="padding: 0 !important; border-bottom: none !important;"> it does not work. [1]: https://i.stack.imgur.com/SHxW7.png
I’m trying to create an HTMl table from data from several tables with values and the length of values in different arrays are the same. I will simplify the example here by limiting it to two tables. I would like to get something like this: [enter image description here](https://i.stack.imgur.com/BfRaN.png) But with my code I have : [enter image description here](https://i.stack.imgur.com/TR6iS.png) Moreover I dont' know how to add the average line and fill this under the age and I tried just with name and age to do easy. If someone can Help me :) JS: ``` let names = ["X","Y"] let ages = [22,10] const newTable = document.createElement("table"); newTable.innerHTML = "<thead><th>Name</th><th>Index</th></thead>"; for (let name of names) { let newRow = document.createElement("tr"); const tdName= document.createElement("td"); tdName.textContent = name; newRow.appendChild(tdName); newTable.appendChild(newRow); } for (let age of ages ) { let newRow = document.createElement("tr"); const tdAge= document.createElement("td"); tdAge.textContent = String(age); newRow.appendChild(tdAge); newTable.appendChild(newRow); } const target = document.getElementById('target'); target.appendChild(newTable); } ``` HTML: ``` <div id="target"></div> ``` MAJ 1.0 : Thank you mykaf it's working now I would like to do more like this : enter image description here I Add in my code let tdAverage = document.createElement("td") tdAverage .textContent = "Average age" let newRow2 = document.createElement("tr"); newRow2.appendChild(tdAverage ) newTable.appendChild(newRow2) I have the row that appears but how could I put the average variable under the column age? If you have an explanation for me
I'm learning navigation in React Native, and can't figure out way how to conditionally use one Back Button. Wanted behaviour would be like this - if user navigate between screens, he can press Go Back button, but if one of the screens contains WebView and he already visited few pages there, user would go back through this webview pages first, then Screens. Hope that makes sense. Something like that: Screen A <- Screen B <- Screen C with WebView <- Webview Page 1 <- Webview Page 2 [enter image description here](https://i.stack.imgur.com/1imzG.png) **AppScreen** ``` import React from 'react'; import {Pressable, StyleSheet, Text} from 'react-native'; import {NavigationContainer} from '@react-navigation/native'; import {createNativeStackNavigator} from '@react-navigation/native-stack'; import HomeScreen from './src/screens/HomeScreen'; import WebViewScreen from './src/screens/WebViewScreen'; import ParamsScreen from './src/screens/ParamsScreen'; const Stack = createNativeStackNavigator(); function App(): React.JSX.Element { return ( <NavigationContainer> <Stack.Navigator initialRouteName="Home" screenOptions={ ({navigation}) => {} }> <Stack.Screen name="Home" component={HomeScreen} options={{title: 'Customized Header Home'}} /> <Stack.Screen name="WebView Screen" component={WebViewScreen} options={({navigation, route}) => ({ title: 'Webview', headerLeft: () => ( <Pressable onPress={() => navigation.goBack()}> <Text style={{color: 'blue'}}>Go Back within Screens</Text> </Pressable> ), })} /> <Stack.Screen name="Params Screen" component={ParamsScreen} /> </Stack.Navigator> </NavigationContainer> ); } const styles = StyleSheet.create({}); export default App; ``` **WebViewScreen** ``` import {StyleSheet, Text, View, ActivityIndicator, Button} from 'react-native'; import React, {useRef, useState} from 'react'; import {WebView} from 'react-native-webview'; const WebViewScreen = ({navigation, route}) => { const webViewRef = useRef<WebView>(null); return ( <> <View style={{flex: 0, alignItems: 'center', justifyContent: 'center'}}> <Text>WebView Screen</Text> <Button title="Go Back within WebView" onPress={() => webViewRef.current?.goBack()} /> </View> <WebView source={{uri: 'https://google.com'}} startInLoadingState ref={webViewRef} renderLoading={() => ( <View style={{flex: 1, alignItems: 'center'}}> <ActivityIndicator size="large" /> </View> )} allowsBackForwardNavigationGestures onNavigationStateChange={navState => {}} /> </> ); }; export default WebViewScreen; const styles = StyleSheet.create({}); ``` At the moment I've managed to have two separate working buttons, but it would be much better to have one back button in the header. I was playing with Screen **options** and **onNavigationStateChange** params, and but kind of got lost there.
I faced this issue after reinstalling IntelliJ IDEA. Despite having correctly set the JAVA_HOME variable and ensuring a clean Java installation, the problem persisted. Upon closer inspection, I discovered that I was attempting to launch IntelliJ using an outdated Windows shortcut that pointed to a previously uninstalled or corrupted directory. My solution: 1. Closed all running instances of IntelliJ IDEA through the task manager. 2. Deleted the corrupted old installation folder. 3. Navigated directly to the new IntelliJ installation Executor using the following path: IntelliJ_Path/bin/idea64.exe 4. Launched IntelliJ IDEA using the idea64.exe executable to create a new shortcut.
How about update table_a a set a.status = (select b.status from table_b b where b.state = a.state and b.name = a.name ); or merge into table_a a using table_b b on a.state = b.state and a.name = b.name when matched then update set a.status = b.status;
I has some python scripts that use argparse for input and is working fine. I want to use pytest to test these scripts. I cannot figure out how to tell pytest to ignore input arguments intended for my test. Also how to tell my test to ignore input arguments intended for pytest. For example, I want to use pytest -s option. I had to define the -s option in my test script even though my test has nothing to do with this argument. Also in my script all arguments must have defaults. I cannot figure out a way to pass in input arguments from the command line intended for my test and have pytest ignore these arguments. I wrote the following script but I cannot pass in the port number as pytest will flag an error: ```none pytest: error: unrecognized arguments: --port ``` Also I had to define `-s` option in my test that is intended for pytest. Here is the test script: ``` import argparse import pytest from litellm import completion def test_main(options): model = f"ollama/{options['model']}" port = options["port"] response = completion( model=model, messages = [{ "content": "Hello, how are you?","role": "user"}], api_base=f"http://localhost:{port}" ) print(f"model {model} response {response}") @pytest.fixture def options(): return Options() def Options(): parser = argparse.ArgumentParser() parser.add_argument('--port', type=int, help='repeatcnt', default=11434) parser.add_argument('--model', type=str, help='model', default="llama2") parser.add_argument('-s', action='store_true') return vars(parser.parse_args()) ``` Here is the error when I tried to pass in the port number: ```none (venv) kenneth@kpc:~/learning/litellms$ pytest -s --port 8000 /home/kenneth/learning/venv/lib/python3.10/site-packages/_pytest/config/__init__.py:331: PluggyTeardownRaisedWarning: A plugin raised an exception during an old-style hookwrapper teardown. Plugin: helpconfig, Hook: pytest_cmdline_parse UsageError: usage: pytest [options] [file_or_dir] [file_or_dir] [...] pytest: error: unrecognized arguments: --port inifile: None rootdir: /home/kenneth/learning/litellms For more information see https://pluggy.readthedocs.io/en/stable/api_reference.html#pluggy.PluggyTeardownRaisedWarning config = pluginmanager.hook.pytest_cmdline_parse( ERROR: usage: pytest [options] [file_or_dir] [file_or_dir] [...] pytest: error: unrecognized arguments: --port ``` What I am hoping is have a way to tell pytest the following arguments are for the test script and have pytest ignore them. Also have my test to ignore input arguments that are intended for pytest. Right now I do not have a way to provide input arguments from the command line and I have to use defaults to make it work such as the default for port.
Data not updating in recycler view after api call using retrofit
|android|kotlin|retrofit|
Here is some test code to help me understand multibyte character management. #include <stdio.h> #include <stdlib.h> #include <string.h> int main(int argc, char *argv[]) { char * line = malloc(1024); size_t n; getline(&line, &n, stdin); while (*line) { int offset = mblen(line, strlen(line)); if (offset == -1) return 0; printf("%d\n", offset); line += offset; } return 0; } As I understand it, if the user were to type "éléphant", my output should show 2 1 2 1 ... However, it shows -1 for an `mblen` error, right from the first byte. I gather it probably ain't a bug in these 2 lines of code, what must I do, what resources can I read to get a hint on what happens here? Of course a `printf("%s", line)` would work (and does) work perfectly.
|c|multibyte-functions|
I'm trying to subset this issue using R base. I have a list of names that I want to subset by severam nested lists of indices. The list of names comes in as very compact and straightforward, the list of indices is nested an the indices may have leaps, ie, some numbers can be non-consecutive; each sublist starts the count from 1. The index numbers may go until ~80, but they're always less than the vector of names, *ie.* it's always possible to use them to subset the element within the ```List OfNames```. Data are like this for the various ```ListOfIndices_n```: ``` ListOfIndices_1<-list( Chr1 <- list(c(1,2,3,4,5,6), c(7,8,9,10), c(11,12)), Chr2 <- list(c(4,5), c(7,8,9,10)), Chr3 <- list(c(1,2,3), c(5,6,7,8,9), c(10,11), c(14,15,16)) ) ListOfIndices_2<-list( Chr1 <- list(c(1,2),c(5,6,7),c(10,11,12)), Chr2 <- list(c(1,2,3), c(4,5), c(9,10), c(13,14,15,16)), Chr3 <- list(c(1,2), c(5,6,7), c(10,11), c(15,16)), Chr4 <- list(c(2,3,4), c(5,6), c(8,9,10,11), c(13,14,15,16)) ) ``` and like this for ```ListOfNames```: ``` ListOfNames<-list( Chr1 <- c("A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","A1","B2","C3","D4","E1","F2","G3","H4","I1"), Chr2 <- c("a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","a1","b2","c3","d4","e5","f6","g7","h8","i9","j10","k11","l12","m13","n14","o15","p16","q17","r18","s19","t20","u1","v2","w3","x4","y5","z6"), Chr3 <- c("aA","bB","cC","dD","eE","fF","gG","hH","iI","jJ","kK","lL","mM","nN","oO","pP","qQ","rR","sS","tT","uU","vV","wW","xX","yY","zZ") Chr4 <- c("aA1","bB2","cC3","dD4","eE5","fF6","gG7","hH8","iI9","jJ10","kK11","lL12","mM13","nN14","oO15","pP16","qQ17","rR18","sS19","tT20","uU21","vV22","wW23","xX24","yY25","zZ26") ) ``` What I want to get are several ```ListOfIndicisedNames```, each the result of ```ListOfNames``` subsetted by a different ```ListOfIndices_n```: ``` ListOfIndicisedNames_1<-list( Chr1 <- list(c("A","B","C","D","E","F"),c("G","H","I","J"),c("K","L")), Chr2 <- list(c("d","e"), c("g","h","i","j")), Chr3 <- list(c("aA","bB","cC"), c("eE","fF","gG","hH","iI"), c("jJ","kK"),c("nN","oO","pP")) ) ListOfIndicisedNames_2<-list( Chr1 <- list(c("A","B") c("E","F","G") c("J","K","L")), Chr2 <- list(c("a","b","c"), c("d","e"), c("i","h"), c("m","n","o","p"), Chr3 <- list(c("aA","bB"), c("eE","fF","gG"), c("iI","jJ"), c("oO","pP")) Chr4 <- list(c("bB2","cC3","dD4"), c("eE5","fF6"), c("hH8","iI9","jJ10","kK11"), c("mM13","nN14","oO15","pP16") ) ``` I've tried several flavours of ```lapply()``` and ```sapply()```, though I didn't manage to get ```do.call()``` - I still find it very magical whenever I manage to make it work. I think that another way could be gettig the result by a ```for``` loop with ```i``` and ```j``` for lists and sublists respectively, but every attempt has made R angry. Could someone please help me in this maze?
I'm pip installing the ibm_watson_machine_learning module on a new virtual environment running python 3.12.1. I get an error saying 'could not build wheels for pandas, which is required to install pyproject.toml-based projects'. I tried to install pandas using pip and update pip to pip 24.0, to no avail.
pip installing ibm_watson_machine_learning module fails
|python|pip|ibm-watson|
null
Aspose.Words for Python supports conversion from PDF to DOCX. The code is pretty simple: ```py import aspose.words as aw doc = aw.Document("C:\\Temp\\in.pdf") doc .save("C:\\Temp\\out.docx") ``` [Aspose.Words support a lot of document formats][1], but at first it has been designed to work with MS Word documents. [1]: https://docs.aspose.com/words/python-net/supported-document-formats/
I want to read a file (object) from S3 bucket in Mule 4. I have access to read/write file only to this bucket. Hence when I enter access key & secret in global config of AWS S3 connector and do 'Test connection', I am getting Access Denied error. The way we can access in WinSCP is using using remote directory option from Advanced tab. They we are giving bucket name and then we can get access to this specific bucket. Not sure how to achieve in Mule using S3 connector. Kindly help. [![enter image description here][1]][1] [1]: https://i.stack.imgur.com/a5w4B.png
<!-- begin snippet: js hide: false console: true babel: false --> <!-- language: lang-js --> client.on('messageCreate', (message) => { if (message.channelId === mhc_minor && !message.author.bot) { const ignorePrefixes = ["[+1 Soul Point]", "[!]", "[Info]", "[Event]", "[Be sure", "[Sale]"]; const startsWithIgnorePrefix = ignorePrefixes.some(prefix => message.content.startsWith(prefix)); if (!startsWithIgnorePrefix) { let contentToSend = message.content; let channelToSend = mhc_bfs; if (message.content.includes("➤")) { channelToSend = mhc_mprivate; } else if (message.content.includes('@')) { contentToSend = message.content.replace(/@(\S+)/g, '`@$1`'); } const channel = client.channels.cache.get(channelToSend); channel.send(contentToSend); } } }); <!-- end snippet -->
It depends on the device you're using. Try adding `touchstart` event listener for mobile In your case: <div ontouchstart="toggleForm()" id="toggleButton"> <h3>TITLE</h3> </div> *The most efficient way is to have an if statement in your script and add `touchstart` or `click` event listener based on the users device (desktop or mobile)
For the first question: You can simply modify the content of the kv file as follows: ``` <testApp>: Screen: Image: source: "pic.png" size_hint: 1, 1 allow_stretch: True keep_ratio: False ``` This will make it resize to fit the entire window and position itself at the top-left corner by default (without needing to specify `pos_hint` unless you require specific positioning. Please note that there are some spelling errors in your file like this, such as using 'halgin' instead of 'halign'.). Alternatively, you can use the updated syntax like this: ```python fit_mode: "fill" ``` This statement refers to the following in the KivyMD documentation: ```markdown To control how the image should be adjusted to fit inside the widget box, you should use the fit_mode property. Available options include: "scale-down": maintains aspect ratio without stretching. "fill": stretches to fill widget, may cause distortion. "contain": maintains aspect ratio and resizes to fit inside widget. "cover": maintains aspect ratio and stretches to fill widget, may clip ``` Regarding the second issue, you need to modify `theme_style` instead of `theme__style`. Therefore, the correct way is: ``` self.theme_cls.theme_style = 'Dark' ``` Reason: This is a conventionally established property name within the KivyMD framework. For further information, you can refer to its documentation. I have modified your program, and here's the complete content: ``` python from kivymd.app import MDApp from kivy.lang import Builder from kivy.core.window import Window from kivy.uix.screenmanager import Screen class testApp(Screen): def __init__(self, **kwargs): super().__init__(**kwargs) class MyApp(MDApp): def build(self): self.theme_cls.theme_style = 'Dark' return testApp() def change_theme(self): if self.theme_cls.theme_style == 'Dark': self.theme_cls.theme_style = 'Light' else: self.theme_cls.theme_style = 'Dark' if __name__ == '__main__': Window.size = (1100, 600) Builder.load_file("main.kv") MyApp().run() ``` ``` <testApp>: Screen: Image: source: "pic.png" size_hint: 1, 1 fit_mode: "fill" MDLabel: text: "cover the window I open" font_size: "48dp" halign: "center" color: app.theme_cls.text_color pos_hint: {'center_x': 0.4, 'center_y': 0.4} MDRaisedButton: text: "Click me!" pos_hint: {'center_x': 0.5, 'center_y': 0.2} on_press: app.change_theme() md_bg_color: app.theme_cls.primary_color text_color: app.theme_cls.text_color ``` Please note that I've added a simple MDRaisedButton to display the status of the theme activation. Normally, you should observe a change in the text color, which indicates that the theme is functioning properly. Hope this helps!
I have the following Terragrunt unit that I'd like to prefix a given environment too. ``` envs: - dev - stg tables: dynamo-db-table: hash_key: "key" attributes: - name: "key" type: "S" ``` working with the following module ``` module "dynamodb_table" { source = "terraform-aws-modules/dynamodb-table/aws" version = "3.3.0" for_each = var.tables name = each.key hash_key = each.value.hash_key attributes = each.value.attributes } variable "tables" { description = "Dyanamodb tables" type = map(object({ hash_key = string attributes = list(map(string)) })) ``` When I apply the above config, I'd like the output to ultimately create 2 dynamodb tables "dev-dynamo-db-table" and "stg-dynamo-db-table" I suspect there is a way of concatenating the envs value onto the map key through a locals value but am not sure how, nor if there is a much simpler way of doing it?
Create list of map keys to iterate over in Terraform
|terraform|terragrunt|
When I run `./waf configure -v` locally, I get ``` Checking for 'gcc' (C compiler) : 13:52:02 runner ['/usr/bin/gcc', '-dM', '-E', '-'] /usr/bin/gcc Checking for 'gcc' (C compiler) : 13:52:02 runner ['clang', '-dM', '-E', '-'] not found Checking for 'clang' (C compiler) : 13:52:02 runner ['clang', '-dM', '-E', '-'] clang Checking for 'gcc' (C compiler) : 13:52:02 runner ['/usr/bin/gcc', '-dM', '-E', '-'] /usr/bin/gcc Checking for 'gcc' (C compiler) : 13:52:02 runner ['clang', '-dM', '-E', '-'] not found Checking for 'clang' (C compiler) : 13:52:02 runner ['clang', '-dM', '-E', '-'] clang Checking for 'gcc' (C compiler) : 13:52:02 runner ['x86_64-w64-mingw32-gcc', '-dM', '-E', '-'] x86_64-w64-mingw32-gcc ``` However, when I run it on github actions, I NEED it to specifically use `clang-15` and `gcc-13` which are installed manually. It actually does discover `clang-15` on its own if I just run `./waf configure -v`, but it still gives up for absolutely no reason. If I run it with `CC=clang-15 ./waf configure -v` it still fails with the same error. The error for just `./waf configure -v` is ``` Checking for 'gcc' (C compiler) : 19:30:07 runner ['/usr/bin/gcc', '-dM', '-E', '-'] /usr/bin/gcc Checking for 'gcc' (C compiler) : 19:30:08 runner ['clang', '-dM', '-E', '-'] not found Checking for 'clang' (C compiler) : 19:30:10 runner ['clang', '-dM', '-E', '-'] clang Checking for 'gcc' (C compiler) : 19:30:10 runner ['/usr/bin/gcc', '-dM', '-E', '-'] /usr/bin/gcc Checking for 'gcc' (C compiler) : 19:30:10 runner ['clang', '-dM', '-E', '-'] not found Checking for 'clang' (C compiler) : 19:30:10 runner ['clang', '-dM', '-E', '-'] clang Checking for 'gcc' (C compiler) : not found Checking for 'clang' (C compiler) : not found Checking for 'icc' (C compiler) : not found could not configure a C compiler! ``` The astute reader will notice that (a) these outputs are different, and (b) on gha, Waf has very mysteriously decided that it will refuse to work even though it patently found `clang` and `/usr/bin/gcc` successfully. What is going on here? This doesn't make any sense at all. It's incoherent. Like, fair play it's finding different compilers on my system vs gha; they have different compilers installed so this makes sense. But, truly, WHY is it attempting to find `icc` on gha but not my computer, and WHY is it giving up due to not finding a C compiler on gha but not my computer when, again, it finds a C compiler on both? I certainly have no idea what could possibly be causing this failure, but it should be obvious already to anyone who does. Nevertheless, here is the [gha workflow](https://github.com/hacatu/Number-Theory-Utils/blob/master/.github/workflows/cov_and_docs.yml) and here is the [wscript](https://github.com/hacatu/Number-Theory-Utils/blob/master/wscript) (beware it's chonky). I've searched Waf's gitlab issues, stackoverflow, and google, but I didn't find much useful. I did find that Waf will display the output of the compiler on an empty program if you look in its log files, since this was relevant in one gitlab issue where the user had a custom compiler that Waf didn't recognize, but I really have gcc and clang so this should not be the problem. I also found that there's some way to make ubuntu use clang-15 and gcc-13 by default, I think this might actually help but I remember it (shock of shocks) not working on gha in the past.
httpd root domain to serve content of subdomain
|php|wordpress|apache|apache2|httpd.conf|
Facing issue with my telegram bot using aiogram 3.4.x. Works fine on android devices, but can't find solution for iOS(tested on different iphone devices) After history cleanup on android devices "START" button available after 5 seconds delay. On iOS devices history remaining empty and button not appear. Tested using same devices on other but similar bots, button is appear. As I understand this should be default telegram behavior and have no controls from the bot side. Use default start handler: ``` @dp.message(CommandStart()) async def command_start_handler(message: types.Message) -> None: ``` and default bot start: ``` async def main() -> None: bot = Bot(TOKEN, parse_mode=ParseMode.HTML) await dp.start_polling(bot) ```
|python|ios|bots|telegram|aiogram|
The problem with taking a screenshot is that the canvas is divided into several sections: ![enter image description here](https://i.stack.imgur.com/p7xKE.png) I am using Angular and I don't see a way to capture it, I have tried to create a single canvas combining the existing ones but the styles are not maintained in the new one. I try: ```downloadGrafo() { var sigmaContainer = document.getElementById('sigma-container'); var combinedCanvas = document.createElement('canvas'); combinedCanvas.width = sigmaContainer.offsetWidth; combinedCanvas.height = sigmaContainer.offsetHeight; var ctx = combinedCanvas.getContext('2d'); sigmaContainer.querySelectorAll('canvas').forEach(function(canvas) { // Dibujar el contenido del canvas en el canvas combinado ctx.drawImage(canvas, 0, 0); }); var imageDataURL = combinedCanvas.toDataURL(); var downloadLink = document.createElement('a'); downloadLink.href = imageDataURL; downloadLink.download = 'sigma_image.png'; downloadLink.click(); }```
Maybe try `import_owl()` from Bioconductor package **simona**.
{"OriginalQuestionIds":[66447374],"Voters":[{"Id":7758804,"DisplayName":"Trenton McKinney","BindingReason":{"GoldTagBadge":"seaborn"}}]}
|laravel|database|join|connection|
I'm very new to the ROS/Slam? can somebody point to any documents/article on the topic of analysing the slam method of running it on several datasets? i already managed to run the algorithm on the rgb-d and stereo cameras but i dint know how to run it on a dataset
How do i stream the data from TUM RGB-D to ORB-SLAM3 ard analyse/record data from that
|ros|slam|
null
The confluent avro library (io.confluent:kafka-avro-serializer) does **not** provide an option for JSON encoding of Avro data. This was confusing to me as well, since Conluent's docs [mention][1] the option for JSON encoding. However their library explicitly makes use of binary Avro encoding with no option to configure to use the json encodings: - `AbstractKafkaAvroSerializer` - Contains an instance of `org.apache.avro.io.EncoderFactory` - Uses `encoderFactory.directBinaryEncoder(out, null)` to encode data. - `AbstractKafkaAvroDeserializer` - Contains an instance of `org.apache.avro.io.DecoderFactory` - Uses `decoderFactory.binaryDecoder(buffer)` to decode data. I can't speak to why this may be other than the fact that binary encoded data is much more compact... It seems if you want to use JSON encoded Avro the producer and all consumers will need to use a different library to write and read the Kafka topic. I don't have an open source library option to offer, you may need to roll your own. If it isn't realistic within your organization to expect all Kafka consumers (and producers) that interact with your topic to **not** use the confluent library, then you'll want to stick to binary encoded Avro. [1]: https://docs.confluent.io/platform/current/schema-registry/fundamentals/serdes-develop/serdes-avro.html#test-drive-avro-schema
I have Azure Notifications Hubs set up on iOS device and it is receiving messages from the Test Send page in Azure Notification Hubs, but I cannot seem to get an Azure Function Timer to send notifications using the backend adapted code examples for [specific devices][1] and [specific users][2]. I keep getting this error: Error: The remote server returned an error: (400) BadRequest. Reason: Bad Request..TrackingId:xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx,TimeStamp:2024-03-26T10:35:00.5448540Z The code is: private async Task sendMessageAsync() { _logger.LogInformation("SendingMessage..."); NotificationHubClient hub = NotificationHubClient .CreateClientFromConnectionString("Endpoint=<endpoint string>" , "<hub name>"); try { var msg = "\"{\"aps\":{\"alert\":\"Notification Hub test notification\"}}"; await hub.SendAppleNativeNotificationAsync(msg); } catch (Exception e) { Console.WriteLine("Error: " + e.Message); } } I copied the `DefaultFullSharedAccessSignature` from the Notification Hub and am using the right Notification Hub name. The test message itself is taken from the Notification Hub test page. I am sending from Azure Functions running on my MacOS using Visual Studio, but don't think that matters. I am using this in the .csproj: <PackageReference Include="Microsoft.Azure.NotificationHubs" Version="4.2.0" /> This post, [Getting Bad Request (400) on Azure Notification Hub's "Test Send"][3], didn't apply as the test send is working. this post, [NotificationHub BadRequest][4] didn't have a resolution. This post, [Azure Apple Push Notification Error: 400 Bad Request][5], the test was not working. This post, [azure-notificationhubs IOS Bad request][6], the test was not working. These posts seem to use the same method: - [Sending Push Notifications from a Azure Function][7] - [Getting Started — Azure, Notification Hub, and iOS][8] - [ASP .NET Core Web API with Azure Notification Hub][9] **UPDATE** I thought I might try a console app, to avoid all the local function complexity in case that was somehow the problem, but still received the 400 error. using Microsoft.Azure.NotificationHubs; using System.Threading.Tasks; namespace NotificationConsole; class Program { static void Main(string[] args) { Console.WriteLine("Hello, World!"); SendNotificationAsync().Wait(); } static async Task SendNotificationAsync() { NotificationHubClient hub = NotificationHubClient .CreateClientFromConnectionString("<endpoint connection string" , "<hub name>"); NotificationOutcome outcome = null; try { var msg = "\"{\"aps\":{\"alert\":\"Notification Hub test notification\"}}"; outcome = await hub.SendAppleNativeNotificationAsync(msg,""); } catch (Exception e) { Console.WriteLine("Error: " + e.Message); Console.WriteLine(e.StackTrace); } } } I followed this post, [Push notification does not send from console using Azure][10], and the article in the answer, [Sending Notification From A Console Application Using Notification Hubs][11], which was a Windows push, but I just replaced the call and still it didn't work. [1]: https://learn.microsoft.com/en-us/azure/notification-hubs/notification-hubs-ios-xplat-segmented-apns-push-notification [2]: https://learn.microsoft.com/en-us/azure/notification-hubs/notification-hubs-aspnet-backend-ios-apple-apns-notification [3]: https://stackoverflow.com/questions/38919302/getting-bad-request-400-on-azure-notification-hubs-test-send [4]: https://learn.microsoft.com/en-us/answers/questions/745750/notificationhub-badrequest [5]: https://stackoverflow.com/questions/46814066/azure-apple-push-notification-error-400-bad-request [6]: https://stackoverflow.com/questions/43629857/azure-notificationhubs-ios-bad-request [7]: https://blog.verslu.is/azure/push-notifications-azure-function/ [8]: https://medium.com/@Dbradford/getting-started-azure-notification-hub-and-ios-ea7ca648416a [9]: https://techmindfactory.com/ASP-.NET-Core-Web-API-with-Azure-Notification-Hub/ [10]: https://stackoverflow.com/questions/39745507/push-notification-does-not-send-from-console-using-azure [11]: https://www.c-sharpcorner.com/blogs/sending-notification-from-a-console-application-using-notification-hubs
I am implementing maven release process on my gitlab ci cd pipeline. After the release is completed it should push the docker image with the name of the tag release process created. It should then be deployed to internal cloud and to artifactory. I have the following problem. When there is an error during maven release job, and it fails; lets say one of the CI/CD variables was missing and the job fails because of it. The mvn release:prepare already creates the tag and commit the changes in pom files, and when it comes to mvn release:perform, it faces an error to push the images. So when I fix the missing variable problem, and re run the job, it fails from the beginning, saying "Updates were rejected because the tip of your current branch is behind" because it already commited the files in the previous stages, but not pushed. How can i make sure, when a problem occurs during the maven release job and I want to re run it, I start from clean stage, reverting the previous commits and all the changes? I tried to perform rollback operation but it wasnt successful as well ## gitlab-ci.yml : stages: - build - test - release - push - deploy - rollback cache: key: $CI_JOB_NAME paths: - /.m2/repository gemnasium-maven-dependency_scanning: stage: test variables: MAVEN_CLI_OPTS: "-DskipTests --batch-mode" DS_MAX_DEPTH: -1 .setup-mvn: before_script: - 'command -v ssh-agent >/dev/null || ( apt-get update -y && apt-get install openssh-client -y )' - eval $(ssh-agent -s) - chmod 400 "$SSH_PRIVATE_KEY" - ssh-add "$SSH_PRIVATE_KEY" - mkdir -p ~/.ssh - chmod 700 ~/.ssh - git config --global user.email "gitlab@default.com" - git config --global user.name " GitLab CI/CD" - ssh-keyscan -p 2222 code.gitlab.com >> ~/.ssh/known_hosts - chmod 644 ~/.ssh/known_hosts - mkdir -p ~/.m2 - | cat <<EOF > ~/.m2/settings.xml <settings xmlns="http://maven.apache.org/SETTINGS/1.0.0" .... EOF build: image: docker-local.artifactory.com/maven:3.9.6-eclipse-temurin-21-jammy variables: KUBERNETES_CPU_REQUEST: "3" KUBERNETES_CPU_LIMIT: "5" KUBERNETES_MEMORY_REQUEST: "4Gi" KUBERNETES_MEMORY_LIMIT: "7Gi" stage: build extends: .setup-mvn script: - mvn clean package artifacts: paths: - server/target/*.jar maven_release: stage: release image: docker-local.artifactory.com/maven:3.9.6-eclipse-temurin-21-jammy-openssh extends: .setup-mvn when: manual script: - git checkout -B "$CI_COMMIT_REF_NAME" - mvn release:clean release:prepare --batch-mode -DscmCommentPrefix="[skip ci]" - mvn release:perform -Dgoals=install push_image: stage: push dependencies: - maven_release image: name: docker-local.artifactory.com/executor:v1.14.0-debug entrypoint: [""] when: manual script: - VERSION=$(mvn help:evaluate -Dexpression=project.version -q -DforceStdout) - mkdir -p /kaniko/.docker - echo $DOCKER_AUTH_CONFIG > /kaniko/.docker/config.json - /kaniko/executor --context $CI_PROJECT_DIR --dockerfile ./Dockerfile --destination docker-local.artifactory.com/$CI_PROJECT_NAME:$VERSION - /kaniko/executor --context $CI_PROJECT_DIR --dockerfile ./Dockerfile --destination docker-local.artifactory.com/$CI_PROJECT_NAME:latest - echo "Docker image pushed." ## pom.xml (for maven-release-plugin only) : <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-release-plugin</artifactId> <version>3.0.1</version> <configuration> <pushChanges>false</pushChanges> <projectVersionPolicyId>SemVerVersionPolicy</projectVersionPolicyId> <tagNameFormat>v-@{project.version}</tagNameFormat> </configuration> </plugin> </plugins> </build>
I am creating an MLM (multi-level marketing) system in PHP and MYSQL database. I want to fetch the child user ID based on the parent ID. I have found a solution https://stackoverflow.com/questions/45444391/how-to-count-members-in-15-level-deep-for-each-level-in-php but getting errors- I have created a class - ``` <?php Class Team extends Database { private $dbConnection; function __construct($db) { $this->dbConnection = $db; } public function getDownline($id, $depth=5) { $stack = array($id); for($i=1; $i<=$depth; $i++) { // create an array of levels, each holding an array of child ids for that level $stack[$i] = $this->getChildren($stack[$i-1]); } return $stack; } public function countLevel($level) { // expects an array of child ids settype($level, 'array'); return sizeof($level); } private function getChildren($parent_ids = array()) { $result = array(); $placeholders = str_repeat('?,', count($parent_ids) - 1). '?'; $sql="select id from users where pid in ($placeholders)"; $stmt=$this->dbConnection->prepare($sql); $stmt->execute(array($parent_ids)); while($row=$stmt->fetch()) { $results[] = $row->id; } return $results; } } ``` Ans using a class like that - ``` $id = 4; $depth = 2; // get the counts of his downline, only 2 deep. $downline_array = $getTeam->getDownline($id, $depth=2); ``` I am getting errors - Fatal error: Uncaught TypeError: count(): Argument #1 ($value) must be of type Countable|array, int given in and second Warning: PDOStatement::execute(): SQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number of tokens in I want to fetch the child user ID in 5 levels
System and OS : Apple Silicon Mac M3, Sonoma OS Trying to install neo4j with docker and getting below errors: ERROR Failed to start Neo4j: Starting Neo4j failed: Component 'org.neo4j.server.database.LifecycleManagingDatabase@2b037cfc' was successfully initialized, but failed to start. Please see the attached cause exception "Some jar procedure files are invalid, see log for details." Attaching a log file for more reference. I tried googling and found a few solutions for the problem, but none of them worked for me. Can someome please help me out here?
Unable to install Neo4J on Mac M3
|docker|macos|neo4j|
null
I want to get local/remote `SockAddr` pair of a successful reqwest http connection. I used to write the following code. #[tokio::main] async fn main() -> Result<(), anyhow::Error> { let response = reqwest::Client::new() .get("https://example.com/") .send() .await? .error_for_status()?; let http_info = response .extensions() .get::<hyper::client::connect::HttpInfo>() .ok_or(anyhow::anyhow!("failed to collect socket addresses"))?; println!("sock_local_addr: {}", http_info.local_addr()); println!("sock_remote_addr: {}", http_info.remote_addr()); println!("response text: {}", response.text().await?); Ok(()) } In case of old reqwest and hyper (reqwest==0.11, hyper==0.14), it works well. But latest hyper does not have `hyper::client::connect::HttpInfo`, and reqwest 0.11 is a little stale. Is there any proper way to get local/remote socket addresses in latest reqwest version?
I am trying to split the data and rearrange the data in a CSV file. My data looks something like this 1:100011159-T-G,CDD3-597,GG 1:10002775-GA,CDD3-597,GG 1:100122796-C-T,CDD3-597,TT 1:100152282-CAAA-T,CDD3-597,CC 1:100011159-T-G,CDD3-598,GG 1:100152282-CAAA-T,CDD3-598,CC and I want a table that looks like this: | ID | 1:100011159-T-G | 1:10002775-GA | 1:100122796-C-T |1:100152282-CAAA-T | |---------------|-----------------|---------------|------------------|-------------------| | CDD3-597 | GG | GG | TT | CC | | CDD3-598 | GG | | | CC | I have written the following code: <!-- begin snippet: js hide: false console: true babel: false --> <!-- language: lang-html --> import pandas as pd input_file = "trail_berry.csv" output_file = "trail_output_result.csv" # Read the CSV file without header df = pd.read_csv(input_file, header=None) print(df[0].str.split(',', n=2, expand=True)) # Extract SNP Name, ID, and Alleles from the data df[['SNP_Name', 'ID', 'Alleles']] = df[0].str.split(',', n=-1, expand=True) # Create a new DataFrame with unique SNP_Name values as columns result_df = pd.DataFrame(columns=df['SNP_Name'].unique(), dtype=str) # Populate the new DataFrame with ID and Alleles data for _, row in df.iterrows(): result_df.at[row['ID'], row['SNP_Name']] = row['Alleles'] # Reset the index result_df.reset_index(inplace=True) result_df.rename(columns={'index': 'ID'}, inplace=True) # Fill NaN values with an appropriate representation (e.g., 'NULL' or '') result_df = result_df.fillna('NULL') # Save the result to a new CSV file result_df.to_csv(output_file, index=False) # Print a message indicating that the file has been saved print("Result has been saved to {}".format(output_file)) <!-- end snippet --> but this has been giving me the following error: Traceback (most recent call last): File "berry_trail.py", line 11, in <module> df[['SNP_Name', 'ID', 'Alleles']] = df[0].str.split(',', n=-1, expand=True) File "/nas/longleaf/home/svennam/.local/lib/python3.5/site-packages/pandas/core/frame.py", line 3367, in __setitem__ self._setitem_array(key, value) File "/nas/longleaf/home/svennam/.local/lib/python3.5/site-packages/pandas/core/frame.py", line 3389, in _setitem_array raise ValueError('Columns must be same length as key') Can someone please help, I am having hard time figuring this out.Thanks in advance! ValueError: Columns must be same length as key
Data Restructuring using python in unix
|python|unix|
|ruby-on-rails|ruby-on-rails-5|
It works as designed, see CSS Specificity: https://developer.mozilla.org/en-US/docs/Web/CSS/Specificity I would assign the p tag a dedicated class (e.g. `modern-white`). That overrules the global rule.
{"OriginalQuestionIds":[77015145,74750819],"Voters":[{"Id":20287183,"DisplayName":"HangarRash"},{"Id":1974224,"DisplayName":"Cristik","BindingReason":{"GoldTagBadge":"swift"}}]}
Pytest - RuntimeError: Working outside of application context
How do I combine back buttons for Screens and WebView into one in React Native using React Navigation package?
|react-native|react-navigation|back-button|
null
For Example, I am using this JavaScript code to invoke a button click. ``` $(document).ready(function() { document.getElementById('buttonId').click(); }) ``` It works independently. But If I want to use this inside document.arrive(), something like this below, it doesn't work. ``` document.arrive("something...", function(){ $(document).ready(function() { document.getElementById('buttonId').click(); }) }) ``` How to resolve this? Any help is appreciated. I am expecting the button click to happen once certain element is available on the page. That's why used document.arrive(). I have debugged and it goes inside document.arrive() and executes other code, but not the button click.
Javascript issue - Unable to invoke the button click event when I am using document.arrive()
|javascript|jquery|
null
With the name of the table in A1, you can get the sheet name with this formula (directly in Excel, no VBA needed): =MID(CELL("filename",INDIRECT(A1&"[#All]")),FIND("]",CELL("filename",INDIRECT(A1&"[#All]")))+1,999) * `INDIRECT(A1&"[#All]")` returns the table itself. * `CELL("filename",INDIRECT(...))` returns the file name including the sheet name of the table, in a format like "C:\...\[filename.xlsx]SheetName". * `FIND("]", CELL(...))` returns the index of the closing bracket in the file name with the sheet name. * `MID(CELL(...),FIND("]", CELL(...))+1,999)` extracts the sheet name from the file name, from after the closing bracket to the end.
|python|math|contour|
I tried this first after adding few break points: Debug: toggle auto attach I choose [smart][1] attach. I ran from the integrated terminal `node run web` (the script I want to debug), it said debugger attached, but didn't stop at the break point. Then I tried: debug: javascript debug terminal and ran `node run web` from it, now the script stops at the break point. [1]: https://code.visualstudio.com/docs/nodejs/nodejs-debugging#_auto-attach
This is my code. It uses logic in the sense that it checks if the current number can be divisible by any number that came before it, excluding any even numbers. I hope it helps. <!-- begin snippet: js hide: false console: true babel: false --> <!-- language: lang-html --> sub is_prime { my ($num) = @_; return 0 if $num <= 2; return 0 if $num % 2 == 0 ; for (my $i = 3; $i < $num; $i += 2) { if($num % $i == 0){ return 0; } } return 1; } <!-- end snippet -->
I would like to force a user password reset in Flutter on the first time login only. I have a field called "ChangePassword" in my firestore document field. When I query this field I want to show a popup message that the user cannot use the app until the password is changed. How do I do that in Flutter? Here is where the login button is clicked CustomButton( onPressed: () { if (_formkey.currentState!.validate()) { Map<String, dynamic> map = { 'email': email.text, 'password': password.text, }; model.login(context: context, map: map); // }); } else {} }, text: 'Login', ), When the user enters in their credentials and clicks the "Login" button I navigate to this method Future<void> login({ required BuildContext context, required Map<String, dynamic> map, }) async { EasyLoading.show(); var response = await loginUsecase.call(map); response.fold((l) { Logger().d('Erroor'); EasyLoading.dismiss(); }, (r) { // Logger().d(r.toJson()); // Logger().d(_credential); SharedPref.setString(kEMAIL, map[kEMAIL]); SharedPref.setString(kPASSWORD, map[kPASSWORD]); SharedPref.setBool(kLocalAuthSetted, true); EasyLoading.dismiss(); Get.toNamed(AppRoutes.main); }); } What I want to do is intercept this method and query the user table called "Users" and check if this user based on the email entered, has the key "ChangePassword" set to true If it is set to true I want to show a message that the password needs to be changed and then re-route them to the forgot password screen.
I'm trying to implement basic auth functionality for testing purposes. Testing via postman, so before logging in, I call a GET request to /sanctum/csrf-cookie. After that I hit '/login' and able to receive data(if this part $request->session()->regenerate(); is commented out) , but if I try to enter protected route I will receive an error. I believe i followed the documentation well, but still I'm facing an issue when a user tries to sign in. I'm receiving this error while $request->session()->regenerate(); this is not commented out: "message": "Session store not set on request." Here's my bootstrap/app.php: return Application::configure(basePath: dirname(__DIR__)) ->withRouting( using: function () { Route::middleware('api') ->prefix('api') ->group(function () { // routes/api.php is not included here require base_path('routes/Api/V1/Auth/routes.php'); }); }, web: __DIR__ . '/../routes/web.php', commands: __DIR__ . '/../routes/console.php', health: '/up', ) ->withMiddleware(function (Middleware $middleware) { $middleware->statefulApi(); }) ->withExceptions(function (Exceptions $exceptions) { // })->create(); Here's my login: public function login(object $request) { // Validate user credentials if (!Auth::attempt($request->only(['username', 'password']))) { return $this->failedRequest('', 'Invalid email address or password', 400); } // Regenerate the user's session to prevent session fixation $request->session()->regenerate(); // Sign in user Auth::login(Auth::user()); // Return data return $this->successfullRequest(Auth::user(), 'User successfully logged in', 200); } My routes: Route::group(['prefix' => 'v1/auth'], function () { Route::post('register', [AuthController::class, 'register']); Route::post('login', [AuthController::class, 'login']); Route::post('logout', [AuthController::class, 'logout'])->middleware('auth:sanctum'); }); If I remove this part, I basically receive Unauthenticated message when I try to hit .../logout > $request->session()->regenerate();
Session store not set on request Laravel 11
|laravel-sanctum|laravel-11|
As soon as changes are detected, you could disable scrolling and use a `DragGesture` to detect a swipe. Then you can prompt for confirmation. Something like this: ```swift struct ContentView: View { struct FormValues: Equatable { var aFlag = false var text = "" } @State private var isSheetShowing = false @State private var isAlertshowing = false @State private var formValues = FormValues() @State private var hasChanges = false @State private var dragOffset = CGFloat.zero var body: some View { Button("Show sheet") { isSheetShowing = true } .buttonStyle(.bordered) .sheet(isPresented: $isSheetShowing) { Form { Picker("On or off", selection: $formValues.aFlag) { Text("Off").tag(false) Text("On").tag(true) } .pickerStyle(.segmented) TextField("Text", text: $formValues.text) } .offset(y: dragOffset) .animation(.easeInOut, value: dragOffset) .interactiveDismissDisabled(hasChanges) .scrollDisabled(hasChanges) .onChange(of: formValues) { oldVal, newVal in hasChanges = true } .gesture( DragGesture() .onChanged { val in if hasChanges { dragOffset = val.translation.height } } .onEnded { val in dragOffset = 0 if hasChanges { isAlertshowing = true } } ) .confirmationDialog("Are you sure?", isPresented: $isAlertshowing) { Button("Yes") { isSheetShowing = false // Save changes } Button("No", role: .cancel) { // Do nothing } } message: { Text("Are you sure?") } } } } ``` This works, but there are two issues I couldn't resolve: - after an alert choice is selected, the alert disappears but then re-appears, before disappearing a second time - the drag gesture may interfere with some of the form content, for example, with a `Toggle` switch. You may find that the first issue (with the re-appearing alert) happens with other solutions too.
I have created a button to insert a row. Each row I add says "Insert expense here. The problem is that when I click the button and insert the row, the row new row only populates where it says B7. If I were to delete "test" in B7 leave it blank, and then click the button it would get generated under B5 where it says expenses. I just want a new row to be added so I can list my expenses accordingly. I also attached a screenshot Here is my code below: Sub Button17_Click() Range("B" & Rows.Count).End(xlUp).Select ActiveCell.EntireRow.Insert ActiveCell.FormulaR1C1 = "Insert An Expense…" End Sub ["Insert An Expense..." only gets added below the cell that has "test" populated. If the cell is blank, "Insert an Expense" gets populated above the cell that says "expenses" ][1] [1]: https://i.stack.imgur.com/GYUKf.png
I am using **LinkedInShare** library for authentication and I'm getting all information of user's profile. I am passing following permissions at the time of authentication r_fullprofile, r_network, r_emailaddress, w_share, w_messages I'm Program Partner of LinkedIn and I have access to all this to all this permissions and I want to send invitation to other LinkedIn user from my app using linkedin id of linkedin user. Here's details of my request with parameters: URL:https://api.linkedin.com/v1/people/~/mailbox Parameters: { body = "I'd like to add you to my professional network on LinkedIn!"; "item-content" = { "invitation-request" = { authorization = { name = "NAME_SEARCH"; value = DNZy; }; "connect-type" = friend; }; }; recipients = { values = ( { person = { "_path" = "/people/linkedIn-id"; }; } ); }; subject = "Invitation to connect!"; } When I execute this, I'm getting the following error: { errorCode = 0; message = "Internal service error"; requestId = E31HKE6KM7; status = 500; timestamp = 1474549122972; } I also went through whole Invitation API of LinkedIn but I'm not getting that what am I doing wrong here?
|ios|objective-c|oauth|linkedin-api|
I have created a button to insert a row. Each row I add says "Insert expense here. The problem is that when I click the button and insert the row, the row new row only populates where it says B7. If I were to delete "test" in B7 leave it blank, and then click the button it would get generated under B5 where it says expenses. I just want a new row to be added so I can list my expenses accordingly. I also attached a screenshot Here is my code in VBA below: Sub Button17_Click() Range("B" & Rows.Count).End(xlUp).Select ActiveCell.EntireRow.Insert ActiveCell.FormulaR1C1 = "Insert An Expense…" End Sub ["Insert An Expense..." only gets added below the cell that has "test" populated. If the cell is blank, "Insert an Expense" gets populated above the cell that says "expenses" ][1] [1]: https://i.stack.imgur.com/GYUKf.png
{"Voters":[{"Id":23869325,"DisplayName":"alon"}],"DeleteType":1}
I'm using jupyter hub inside kubernetes, my hub nd workspace are separate docker images. Currently when I launch the workspace from the hub page, it receives the ping activity from the workspace pod, but it never finds the pod. This is the only thing I can find in the logs: timestamp="2024-03-28T16:00:50,184-0700",name="JupyterHub",level="WARNING",message="<myusernamehere>'s server never showed up at http://XX.XX.XX.XX:8888/user/<myusernamehere>/ after 60 seconds. Giving up. Common causes of this timeout, and debugging tips: ``` 1. The server didn't finish starting, or it crashed due to a configuration issue. Check the single-user server's logs for hints at what needs fixing. 2. The server started, but is not accessible at the specified URL. This may be a configuration issue specific to your chosen Spawner. Check the single-user server logs and resource to make sure the URL is correct and accessible from the Hub. 3. (unlikely) Everything is working, but the server took too long to respond. To fix: increase `Spawner.http_timeout` configuration to a number of seconds that is enough for servers to become responsive. ``` Now I know #1 and #2 aren't a problem because here are the logs from the user pod: ``` timestamp="2024-03-28 16:03:19,555",name="ServerApp",level="INFO",message="Serving notebooks from local directory: /workspace/user/<myusername>" timestamp="2024-03-28 16:03:19,555",name="ServerApp",level="INFO",message="Jupyter Server 2.5.0 is running at:" timestamp="2024-03-28 16:03:19,555",name="ServerApp",level="INFO",message="http://jupyter-anthony-5fwu:8888/user/<myusername>/lab?token=..." timestamp="2024-03-28 16:03:19,555",name="ServerApp",level="INFO",message=" http://127.0.0.1:8888/user/<myusername>/lab?token=..." timestamp="2024-03-28 16:03:19,555",name="ServerApp",level="INFO",message="Use Control-C to stop this server and shut down all kernels (twice to skip confirmation)." timestamp="2024-03-28 16:03:19,565",name="JupyterHubSingleUser",level="DEBUG",message="Notifying Hub of activity 2024-03-28T23:03:19.224418Z" ``` ServerApp starts and notifies hub of activity. And I can hit the URL the hub says the server should be: `http://XX.XX.XX.XX:8888/user/<myusernamehere>/ ` just a regular curl though to check it's reachable and something is taking requests from there. here is my hub config: ``` ## Enable debug-logging c.JupyterHub.log_datefmt = '%Y-%m-%dT%H:%M:%S' c.JupyterHub.log_format = 'timestamp="%(asctime)s,%(msecs).03s-0700",name="%(name)s",level="%(levelname)s",message="%(message)s"' c.JupyterHub.log_level = 'DEBUG' c.Spawner.debug = True kube_namespace_pod_limit = 100 c.JupyterHub.active_server_limit = kube_namespace_pod_limit - 2 ## Duration (in seconds) to determine the number of active users. c.JupyterHub.active_user_window = 3600 ##Auth stuff: omitting ### JUPYTERHUB_PORT = os.environ.get("JUPYTERHUB_PORT", "18888") c.JupyterHub.bind_url = os.environ.get("JUPYTERHUB_BIND_URL", f"http://0.0.0.0:{JUPYTERHUB_PORT}") # The Hub should be able to resume from database state. c.JupyterHub.cleanup_proxy = False # The Hub should be able to resume from database state. c.JupyterHub.cleanup_servers = False # If set to 0, no limit is enforced. even only one at a time is failing c.JupyterHub.concurrent_spawn_limit = 20 c.JupyterHub.cookie_max_age_days = 14 ## pingback handler stuff: omitting here ### import coco_jupyter_extensions.nbsharing c.JupyterHub.extra_handlers = coco_jupyter_extensions.nbsharing.HANDLERS + [ ("/usagepingback", UsagePingbackHandler), ] + [(f"/{k}(/.*)?", SimpleSparkRewritingProxy) for k in REWRITES.keys()] _hostname = os.environ.get("JUPYTERHUB_SERVICE_NAME", socket.gethostbyname(socket.gethostname())) #c.JupyterHub.hub_connect_url = f"http://{_hostname}:18888/" c.JupyterHub.hub_connect_ip = _hostname c.JupyterHub.hub_ip = '0.0.0.0' c.JupyterHub.init_spawners_timeout = -1 c.Proxy.should_start = False # proxy is served from a diff container c.JupyterHub.proxy_class = 'jupyterhub.proxy.ConfigurableHTTPProxy' with open(os.environ.get( "CONFIGPROXY_AUTH_TOKEN_FILE", "/secrets/dsj/hub_configproxy_auth_token" ), "rt") as token_file: c.ConfigurableHTTPProxy.auth_token = token_file.read() c.ConfigurableHTTPProxy.check_running_interval = 2 # seconds found_proxy_api_url = None for env_key in os.environ: # find e.g. DEV*_JUPYTERHUB_PROXY_SERVICE_PORT_28001_TCP=tcp://172.31.123.69:28001 if all([ "JUPYTERHUB_PROXY_SERVICE" in env_key, env_key.endswith("28001_TCP"), os.environ[env_key].startswith("tcp://") ]): # https://jupyterhub.readthedocs.io/en/stable/reference/api/proxy.html#configurablehttpproxy found_proxy_api_url = os.environ[env_key].replace("tcp://", "http://") c.ConfigurableHTTPProxy.api_url = found_proxy_api_url break else: raise ValueError(f"Cannot auto discover ConfigurableHTTPProxy.api_url from container env.") c.JupyterHub.redirect_to_server = False import sys workspace_timeout_seconds = os.environ.get("DSJ_WORKSPACE_TIMEOUT_SECONDS", 60*60*48) cull_every_seconds = 60 * 15 # check every 15 minutes c.JupyterHub.services = [ { 'name': 'idle-culler', 'admin': True, 'command': [ sys.executable, '-m', 'jupyterhub_idle_culler', '--url=http://localhost:8081/hub/api', f'--timeout={workspace_timeout_seconds}', f'--cull-every={cull_every_seconds}', ], } ] c.JupyterHub.shutdown_on_logout = False c.Spawner.default_url = '/lab' c.Spawner.http_timeout = 60 c.Spawner.start_timeout = 60 * 10 ### User and roles stuff: omitting ### c.Authenticator.enable_auth_state = True ```
I am not experienced in this. I need to do load balancing between three sites located on different containers in the Portainer. So far, the problem is the following. I have two containers. There is a website on one of them index.html based on NGINX, the second one hosts NGINX as a proxy server. I want my site to be displayed at the request of localhost:81 - index.html (The site itself opens at the request of localhost:8080, it works). But at the same time, so that the request goes through NGINX. I did what many people do on the Internet. But they don't use containers in the Portainer environment for this. In the nginx.conf configuration file, which is located in the container at the path etc/nginx/nginx.conf, I added the lines: ``` server { listen 81; server_name _; location / { proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_pass http://localhost:8080; } } ``` And the file began to look like this: ``` worker_processes auto; error_log /var/log/nginx/error.log notice; pid /var/run/nginx.pid; events { worker_connections 1024; } http { include /etc/nginx/mime.types; default_type application/octet-stream; log_format main '$remote_addr - $remote_user [$time_local] "$request" ' '$status $body_bytes_sent "$http_referer" ' '"$http_user_agent" "$http_x_forwarded_for"'; access_log /var/log/nginx/access.log main; sendfile on; #tcp_nopush on; keepalive_timeout 65; server { listen 81; server_name _; location / { proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_pass http://localhost:8080; } } include /etc/nginx/conf.d/*.conf; # include /etc/nginx/sites-enabled/*; } ``` But when I go to localhost:81, I get an nginx welcome page, but not mine. Can you tell me how to solve this problem?
Load balancing using NGINX between sites that are in different docker-containers in the Portainer environment
|nginx|load-balancing|nginx-reverse-proxy|docker-container|portainer|
null
The [System.IO.Abstractions.TestingHelpers][1] package provides a `MockUnixSupport` class for this purpose. Here's the [recommended usage][2] (from `TestableIO.System.IO.Abstractions.TestingHelpers` own tests): ```csharp using XFS = System.IO.Abstractions.TestingHelpers.MockUnixSupport; var path = XFS.Path(@"c:\something\demo.txt"); ``` And here's what it would look like for your sample code: ```csharp using XFS = System.IO.Abstractions.TestingHelpers.MockUnixSupport; var fileSystem = new MockFileSystem(new Dictionary<string, MockFileData> { { XFS.Path(@"c:\scans\myfile.pdf"), new MockFileData("Some text") }, { XFS.Path(@"c:\scans\mysecondfile.pdf"), new MockFileData("Some text") }, { XFS.Path(@"c:\scans\mydog.jpg"), new MockFileData("Some text") } }); var fileService = new FileService(fileSystem); var scanDirPath = XFS.Path(@"c:\scans\"); ``` Then you can write your tests without any conditional code. [1]: https://www.nuget.org/packages/System.IO.Abstractions.TestingHelpers [2]: https://github.com/TestableIO/System.IO.Abstractions/blob/v21.0.2/tests/TestableIO.System.IO.Abstractions.TestingHelpers.Tests/MockFileSetAttributesTests.cs#L13
In a Logic App, use the `HTTP` action to send a [`GET`][1] request to https://management.azure.com/subscriptions/{your_subscription_Id}/providers/Microsoft.Resources/tags/default?api-version=2021-04-01: [![enter image description here][2]][2] Result: [![enter image description here][3]][3] [1]: https://learn.microsoft.com/en-us/rest/api/resources/tags/get-at-scope?view=rest-resources-2021-04-01&tabs=HTTP#get-tags-on-a-subscription [2]: https://i.stack.imgur.com/dCOMC.png [3]: https://i.stack.imgur.com/0mpJ5.png
# Set logo file path logo_file_path = b"Media/GUI.png" # Convert string to bytes # Set the logo file path using libvlc_video_set_logo_string vlc.libvlc_video_set_logo_string(pi, vlc.VideoLogoOption.logo_file, logo_file_path) Make sure you convert the logo file path to bytes using b"..." notation because libVLC expects byte strings for paths. Also, ensure that your VLC instance pi is correctly initialized and that you're using the correct VideoLogoOption constant (vlc.VideoLogoOption.logo_file) to specify the property you want to set
I am struggling to prevent a relative positioned div text content from overflowing outside of the bounds. Markup: <div class="parent"> <div class="details"> <div class="detail1"> lotsoftext lotsoftext lotsoftext lotsoftext lotsoftext lotsoftext lotsoftext lotsoftext lotsoftext lotsoftext lotsoftext lotsoftext </div> <div class="detail2"> lotsmoretext lotsmoretext lotsmoretext lotsmoretext lotsmoretext lotsmoretext lotsmoretext lotsmoretext lotsmoretext lotsmoretext lotsmoretext lotsmoretext </div> </div> </div> CSS: .parent { margin: 5px; max-height: 100px; max-width: 400px; background: pink; } .details { width: 100%; text-align: center; font-size: 14pt; display: grid; grid-template-rows: 1fr 1fr; } .detail1 { grid-row: 1; overflow-y: hidden; } .detail2 { grid-row: 2; overflow-y: hidden; } Check this [JFiddle][1] to show the problem [![enter image description here][2]][2] [1]: https://jsfiddle.net/f5huqxys/ [2]: https://i.stack.imgur.com/Uk9s2.png
css relative positioned div text content expanding and overlapping
|html|css|
Hi all i have a condition to test international phone number patterns that is(###) ###-####,Currently i have written code for this patter,which is working fine,But i want to allow a pattern also (###)###-#### and it should not accept letters but currently it is accepting,Can somebody please helpme how to achieve this ``` const phoneNumber = document.getElementById('phone_number').value.trim(); // Regex pattern for USA phone number const pattern = /^\(\d{3}\) \d{3}-\d{4}$/; // Validate phone number and update message const isValid = pattern.test(phoneNumber); document.getElementById('phoneValidationMsg').textContent = isValid ? '' : 'Please enter a valid phone number.'; return isValid; ```
Multiple regex expressions to check mobile number in javascript
Please see this post for an example on how to create a single page application or how to dynamically load controls/views: [C# WPF Navigation Between Pages (Views)](https://stackoverflow.com/a/61323201/3141792). The following example assumes that you follow the pattern of the provided link. The following example will show how you have to design the `UserControl` for a page and how they share the same `DataContext` in order to show the same data and share the same content section to share the same layout of the particular data view. The page controls are named `MainPage` and `CellSettingsPage` (I'm trying to stick to your original code as much as possible). You need to know - [Microsoft learn: Data binding overview (WPF .NET)](https://learn.microsoft.com/en-us/dotnet/desktop/wpf/data/?view=netdesktop-7.0) - [Microsoft learn: Data Templating Overview](https://learn.microsoft.com/en-us/dotnet/desktop/wpf/data/data-templating-overview?view=netframeworkdesktop-4.8) **PageId.cs** ```c# enum PageId { Default = 0, MainPage, CellSettingsPage } ``` **MainPage.xaml** ```xaml <UserControl> <StackPanel> <TextBlock Text="This is the 'MainPage'" /> <TabControl Background="{x:Null}" Grid.Column="0"> <TabItem Style="{StaticResource TabItemStyle}" Header="Pages"> <!-- This is the host for the shared view section. You can embed it into the page layout by placing this ContentControl where you want the TabControl that contains DataGrids to appear. The ContentControl.Content binds to a property on this UserControl. Simply define a DataTemplate e.g. in App.xaml to define the visuals. Because the other page will use the DataTemplate (and data model), both will show the exact same data view (without duplicating any data as the data is shared). --> <ContentControl Content="{Binding RelativeSource={RelativeSource AncestorType=UserControl}, Path=SharedDataSource}" /> </TabItem> </TabControl> </StackPanel> </UserControl> ``` **MainPage.xaml.cs** ```c# partial class MainPage : UserControl { public object SharedDataSource { get => (object)GetValue(SharedDataSourceProperty); set => SetValue(SharedDataSourceProperty, value); } public static readonly DependencyProperty SharedDataSourceProperty = DependencyProperty.Register( "SharedDataSource", typeof(object), typeof(MainPage), new PropertyMetadata(default)); public MainPage() { InitializeComponent(); } } ``` **CellSettingsPage.xaml** ```xaml <UserControl> <StackPanel> <TextBlock Text="This is the 'CellSettingsPage'" /> <TabControl Background="{x:Null}" Grid.Column="0"> <TabItem Style="{StaticResource TabItemStyle}" Header="CellPages"> <!-- This is the host for the shared view section. You can embed it into the page layout by placing this ContentControl where you want the TabControl that contains DataGrids to appear. The ContentControl.Content binds to a property on this UserControl. Simply define a DataTemplate e.g. in App.xaml to define the visuals. Because the other page will use the DataTemplate (and data model), both will show the exact same data view (without duplicating any data as the data is shared). --> <ContentControl Content="{Binding RelativeSource={RelativeSource AncestorType=UserControl}, Path=SharedDataSource}" /> </TabItem> </TabControl> </StackPanel> </UserControl> ``` **CellSettingsPage.xaml.cs** ```c# partial class CellSettingsPage : UserControl { public object SharedDataSource { get => (object)GetValue(SharedDataSourceProperty); set => SetValue(SharedDataSourceProperty, value); } public static readonly DependencyProperty SharedDataSourceProperty = DependencyProperty.Register( "SharedDataSource", typeof(object), typeof(CellSettingsPage), new PropertyMetadata(default)); public CellSettingsPage() { InitializeComponent(); } } ``` **App.xaml** ```xaml <Application> <Application.Resources> <!-- The DataTemplate for the MainPageViewModel --> <DataTemplate DataType="MainPageViewModel"> <MainPage SharedDataSource="{Binding SharedData}" /> </DataTemplate> <!-- The DataTemplate for the CellSettingsPageViewModel --> <DataTemplate DataType="CellSettingsPageViewModel"> <MainPage SharedDataSource="{Binding SharedData}" /> </DataTemplate> <!-- The DataTemplate for the SharedDataItem. This will actually show the stacked DataGrid elements. --> <DataTemplate DataType="SharedDataItem"> <ListBox ItemsSource0"{Binding DataTables}"> <ListBox.ItemTemplate> <DataTemplate DataType="DataTable"> <DataGrid ItemsSource="{Binding}" /> </DataTemplate> </ListBox.ItemTemplate> </ListBox> </DataTemplate> </Application.Resources> </Application> ``` **SharedDataItem.cs** ```c# // TODO::Implement INotifyPropertyChanged. // If there are properties that change their values // then let them raise the INotifyPropertyChanged.PropertyChanged event. class SharedDataItem : INotifyPropertyChanged { public ObservableCollection<DataTable> DataTables { get; } public SharedDataItem() => this.DataTables = new ObservableCollection<DataTable>(); } ``` **MainPageViewModel.cs** ```c# // TODO::Implement INotifyPropertyChanged. // If there are properties that change their values // then let them raise the INotifyPropertyChanged.PropertyChanged event. class MainPageViewModel : INotifyPropertyChanged { public string Title { get; } public SharedDataItem ShareData { get; } public MainPageViewModel(string title, SharedDataItem sharedDataContext) { this.Title = title; this.SharedData = sharedDataContext; } } ``` **CellSettingsPageViewModel.cs** ```c# // TODO::Implement INotifyPropertyChanged. // If there are properties that change their values // then let them raise the INotifyPropertyChanged.PropertyChanged event. class CellSettingsPageViewModel : INotifyPropertyChanged { public string Title { get; } public SharedDataItem ShareData { get; } public CellSettingsPageViewModel(string title, SharedDataItem sharedDataContext) { this.Title = title; this.SharedData = sharedDataContext; } } ``` **MainViewModel.cs** The example uses the RelayCommand implementation found at [Microsoft learn: Relaying Command Logic](https://learn.microsoft.com/en-us/archive/msdn-magazine/2009/february/patterns-wpf-apps-with-the-model-view-viewmodel-design-pattern#relaying-command-logic) ```c# // TODO::Implement INotifyPropertyChanged. // If there are properties that change their values // then let them raise the INotifyPropertyChanged.PropertyChanged event. class MainViewModel : INotifyPropertyChanged { // TODO::Raise INotifyPropertyChanged.PropertyChanged event public string CurrentContext { get; set: } public ICommand SelectPageContextCommand { get; } private Dictionary<PageId, INotifyPropertyChanged> PageContexts { get; } public MainViewModel(string title) { this.SelectPageContextCommand = new RelayCommand(ExecuteSelectPageContextCommand, CanExecuteSelectPageContextCommand); var sharedDataContext = new SharedDataItem(); // Add shared data to the 'sharedDataContext'. // TODO::Create the DataTables that will be displayed in a DataGrid each. // Conceptual example code: for (int datTableCount = 0; dataTableCount < 3; dataTableCount++) { DataTable sharedDataTable = CreateDataTable(); sharedDataContext.DataTables.Add(sharedDataTable); } this.PageContexts = new Dictionary<PageId, INotifyPropertyChanged> { { PageId.MainPage, new MainPageViewModel("Main page", sharedDataContext) }, { PageId.CellSettingsPage, new CellSettingsPageViewModel("Cell settings page", sharedDataContext) }, }; // Set start page SelectCurrentContext(PageId.MainPage); } private void SelectCurrentContext(PageId pageContextId) { if (this.PageContexts.TryGetValue(pageContextId, out INotifyPropertyChanged pageContext)) { this.CurrentContext = pageContext; } } private bool CanExecuteSelectPageContextCommand(object commandParameter) => commandParameter is PageId pageId && this.PageContexts.ContainsKey(pageId); private void ExecuteSelectPageContextCommand(object commandParameter) => SelectCurrentContext((PageId)commandParameter); } ``` **MainWindow.xaml** ```xaml <Window> <Window.DataContext> <MainViewModel /> </Window.DataContext> <StackPanel> <!-- Page navigation --> <StackPanel Orientation="Horizontal"> <Button Content="Main page" Command="{Binding SelectPageContextCommand}" CommandParameter="{x:Static PageId.MainPage}" /> <Button Content="Show Welcome Screen" Command="{Binding SelectPageContextCommand}" CommandParameter="{x:Static PageId.CellSettingsPage}" /> </StackPanel> <!-- Host of CurrentContext. Automatically displays the DataTemplate (defined in App.xaml) that matches the current data type (e.g. CellSettingsPageViewModel) --> <ContentControl Content="{Binding CurrentContext}" /> <StackPanel> </Window> ``` Notes: the code was written without IDE in this editor using *a lot* copy & paste. Therefore, it may contain some copy & paste related errors. Just keep that in mind when you encounter code that makes little sense like wrong variable names and typos in general etc. However, if you satisfy the *TODO* code annotations in this example the code is supposed to compile and execute.
I have created an fresh angular 17 (Node v18.14.1) project. and tried to run `npm run test` It fails with the following error. Error: src/app/app.component.ts:13:9 - error TS2503: Cannot find namespace 'NodeJS'. ```` import { Component } from '@angular/core'; import { RouterOutlet } from '@angular/router'; @Component({ selector: 'app-root', standalone: true, imports: [RouterOutlet], templateUrl: './app.component.html', styleUrl: './app.component.scss', }) export class AppComponent { title = 'angular-tour-of-heroes'; nodeJsTimeout: NodeJS.Timeout | null = null; } ```` I already tried to add `types: ["node"]` in `tsconfig.app.json` and also in `tsconfig.json`. Didnt resolve my problem.
You are trying to get the copyright div to the normal position right? The problem is, when you are declaring the rotate rule in the :hover, you basically overwrite the rotate rule declared in the non-hover selector instead of adding it up. So your code should look like this: .parent:hover .copyright{ rotate: 0deg }
# As of 2024, macOS 14.2, VSCode 1.85: - `cmd-shift-p` > `Open Logs Folder` - inside that folder, go to `window<XXX>/exthost/vscode.typescript-language-features/tsserver-log-<id>/tsserver.log` [![tsserver logs macos 14.2][1]][1] To copy the full file path: select the interesting `tsserver.log` file -> right click -> `Copy`. [![copy tsserver path][2]][2] Then in your terminal: `code <cmd-v>` to open the logs in VSCode. Overall the full path path is: ``` /Users/<yourname>/Library/Application Support/Code/logs/<timestamp>/window<N>/exthost/vscode.typescript-language-features/tsserver-log-<hash>/tsserver.log` ``` ❗️ Note the space in `Application Support` folder name; so from command line, you either need to escape it as `Application\ Support`, or quote the path and NOT have the `\` escape before the space. [1]: https://i.stack.imgur.com/qKcmp.png [2]: https://i.stack.imgur.com/G5cOp.png
I want to create an alert that will active whenever the close price cross or hit the trendline. This is the trendline code: ``` //Declaration of trendline function a_f_trendline(a__input_function, a__delay, a__only_up, a__extend) => //Calculate line coordinates (Ax,Ay) - (Bx,By) var int a_Ax = 1 var int a_Bx = 1 var float a_By = 0 var float a_slope = 0 a_Ay = fixnan(a__input_function) if ta.change(a_Ay) != 0 a_Ax := time[a__delay] a_By := a_Ay[1] a_Bx := a_Ax[1] a_slope := log_chart ? (math.log(a_Ay) - math.log(a_By)) / (a_Ax - a_Bx) : (a_Ay - a_By) / (a_Ax - a_Bx) a_slope else a_Ax := a_Ax[1] a_Bx := a_Bx[1] a_By := a_By[1] a_By //Draw trendlines var line a_trendline = na var int a_Axbis = 0 var float a_Aybis = 0 var bool a__xtend = true a_extension_time = a_Extension_Multiplier * a_bar_time * 25 a_Axbis := a_Ax + a_extension_time a_Aybis := log_chart ? a_Ay * math.exp(a_extension_time * a_slope) : a_Ay + a_extension_time * a_slope if a_Extension_Multiplier != 0 a__xtend := false a__xtend if ta.change(a_Ay) != 0 a_line_color_Rising_Falling = a_slope * time < 0 ? a__only_up ? a_Rising_Upper_Falling_Lower ? a_Color_Type == 'Colored' ? color.gray : color.teal : na : a_Color_Type == 'Colored' ? #cf0a83 : color.teal : a__only_up ? a_Color_Type == 'Colored' ? #027521 : color.teal : a_Rising_Upper_Falling_Lower ? a_Color_Type == 'Colored' ? color.gray : color.teal : na a_line_color_Not_Rising_Falling = a_slope * time < 0 ? a__only_up ? na : a_Color_Type == 'Colored' ? #cf0a83 : color.teal : a__only_up ? a_Color_Type == 'Colored' ? #027521 : color.teal : na a_line_color = a_Show_Primary and not a_Rising_Upper_Falling_Lower ? a_line_color_Not_Rising_Falling : a_Show_Primary and a_Rising_Upper_Falling_Lower ? a_line_color_Rising_Falling : na if not na(a_line_color) a_trendline = line.new(a_Bx, a_By, a_Axbis, a_Aybis, xloc.bar_time, extend=a__xtend ? extend.right : extend.none, color=a_line_color, style=line.style_solid, width=a_width) a_trendline [a_Bx, a_By, a_Axbis, a_Aybis, a_slope,a_trendline] //Calculate pivot points a_high_point = ta.pivothigh(c > o ? c : o, a_len, a_len / 2) a_low_point = ta.pivotlow(c > o ? o : c, a_len, a_len / 2) //Call trendline function for high and low pivot points [a_phx1, a_phy1, a_phx2, a_phy2, a_slope_high,a_trendline_high] = a_f_trendline(a_high_point, a_len / 2, false, true) [a_plx1, a_ply1, a_plx2, a_ply2, a_slope_low,a_trendline_low] = a_f_trendline(a_low_point, a_len / 2, true, true) ``` I got a line value a_trendline_high and a_trendline_low. How can I create an alert that will alert me whenever the close price crosses/hits the trendlines? I try to do this: ``` upperYvalue = line.get_y1(a_trendline_high) bool newCrossUp = c[1] < upperYvalue and c > upperYvalue bool newCrossDn = c[1] > upperYvalue and c < upperYvalue plotshape(newCrossUp , title="Cross Above", color=color.green, style=shape.triangleup, location=location.absolute) plotshape(newCrossDn , title="Cross Below", color=color.red, style=shape.triangledown, location=location.absolute) ``` But the plotshape is created for every bar.
**SOLVED**: In _start the stack is _already_ aligned so by popping 8 bytes off in my startup code I was actually _misaligning_ it before the call to main(). The SysV x86-64 ABI requires the stack be aligned prior to any calls so it is perfectly reasonable for Clang to assume that the stack is aligned a certain way upon entry to main() and to generate code accordingly. In other words: **This is not a bug**. (And, again, it has nothing to do with using the `--nmagic` linker option which is perfectly fine to use.) **UPDATE3**: [Clang issue submitted][1] as I am now confident that this is a previously unreported compiler bug. (There are many somewhat similar but distinct issues in the LLVM bug tracker.) Thanks to all who genuinely tried to help. **UPDATE2**: It turns out this bug does **NOT** require the use of `-n` (`--nmagic`) option. The same crashes occur on binaries just built without using the C library (`-nostdlib` Clang option). So building NMAGIC binaries apparently has nothing to do with the problem. **UPDATE**: LLVM's own linker, LLD, supports the `-n` (`--nmagic`) option so I installed it and gave it a try. The exact same segfault occurs. Since LLVM's own linker supports building NMAGIC binaries that strongly suggests that that it **should** work when user their compiler (Clang) too. I'll file a bug report. **Original Post**: I've come across a C++ issue where instantiating some objects in programs compiled by Clang segfaults. Thanks in advance to anyone who can help shed light on the issue. Debugging suggests that Clang is generating SSE `movaps` instructions to initialize some char arrays and it's these instructions that appear to cause segfaults in some circumstances. I've tested on multiple Linux systems with the binutils linker with both Clang 16 and Clang 17 with the same results. I'm not sure if the same problem occurs under other x86-64 operating systems or with other linkers. The problem does **not** occur when using versions of the GCC compiler instead of Clang. The segfaults occur for some objects under the following minimum set of conditions: - x86-64 code generation - Optimization is enabled (-O1 or above) - [**EDIT** - This was incorrect. The segfaults do **not** require the `-n` (`--nmagic`) linker option. All that's necessary is to build a binary without the standard C library (`-nstdlib` option to Clang). I should also point out here that use of the `-fno-builtin` option makes no difference.] Here is minimal code to reproduce. Compile with the following on an x86-64 Linux system [**EDIT**: removed unnecessary linker option]: ``` $ clang -O1 -nostdlib -fno-stack-protector -static clang_segv.s clang_segv.cc -o clang_segv ``` clang_segv.cc: ``` struct SegV { void set(const char *s) { char *b = buf; while ( *s ) { *b++ = *s++; } *b = '\0'; } char buf[128] = ""; char *cursor = buf; // needed for segfault }; int main() { SegV v; v.set("aa"); return 0; } ``` clang_segv.s ``` .intel_syntax noprefix .global _start _start: xor rbp,rbp # Zero stack base pointer xor r9,r9 pop rdi # Pop argc off stack -> rdi for 1st arg to main() mov rsi,rsp # Argv @top of stack -> rsi for 2nd arg to main() call main # Call main()... return result ends up in rax xor r9,r9 mov rdi,rax # Move main()'s return to 1st argument for exit() mov rax,231 # exit_group() syscall syscall # Tell kernel to exit program ``` This example is the minimum reproducer I could come up with and has no resemblance to the original code where I noticed the problem save that both have objects with char arrays. Changing the code around can mask or unmask the issue which usually suggests a coding error but I'm at a loss to find one in this simple example. My debugger seems to think that the problems are the instructions that Clang is generating to initialize the 'buf' char array: [Image of debugger suggesting issue with movaps instructions](https://i.stack.imgur.com/LuDiX.png). My Debugger says that Clang generates the following code for the initialization of `char buf[128]`: ``` 0x400171 xorps %xmm0,%xmm0 0x400174 movaps %xmm0,-0x10(%rsp) 0x400179 movaps %xmm0,-0x20(%rsp) 0x40017e movaps %xmm0,-0x30(%rsp) 0x400183 movaps %xmm0,-0x40(%rsp) 0x400188 movaps %xmm0,-0x50(%rsp) 0x40018d movaps %xmm0,-0x60(%rsp) 0x400192 movaps %xmm0,-0x70(%rsp) 0x400197 movaps %xmm0,-0x80(%rsp) 0x40019c lea -0x80(%rsp),%rax ``` and that the segfault is generated by the first movapps instruction. Obviously, I expect that the initialization of the array shouldn't segfault. It doesn't matter if in-class initialization is used as I do here in this example or if initializer-list initialization is used. Both methods suffer from the same problem. I believe the problem might be a mismatch in how the code generated by clang **thinks** the members of the object are (should be) aligned versus how the members are **actually** aligned. I might be wrong about that but if I add alignas(32) to the structure or to the char array the problem goes away. I don't know why I'd need to align at 32 bytes. Perplexingly (to me), aligning at 16 bytes does not mask the problem. The problem also goes away if I just tell Clang not to generate any SSE instructions with `-mno-sse` but I'd rather not lose those optimizations. In this case Clang uses `movq` instructions to initialize the array instead of `movaps`. The problem also goes away if I forgo initialization of the char array member and do it manually in the constructor but of course that is less efficient. At this point to me this looks like a compiler bug. Or am I just using it wrong? Thanks! [1]: https://github.com/llvm/llvm-project/issues/86895
Using jitsi_meet_wrapper in flutter and it's working fine but when I'm creating a meet I'm being put into lobby where it says you'll join when owner gives you access. I saw a solution where I was suggested to change server url from default to one of the community instances from this link - jitsi.github.io/handbook/docs/community/community-instances. But this link is no longer active and has no community instances. How do I solve this problem I want to replace default server url of jitsi meet with some community instance. Help
Jitsi Meet server
|flutter|jitsi|jitsi-meet|
null
> What happens to a Thread when it throws an exception when executed by a thread pool? The answer to this depends on whether or not the code is using `threadPool.execute(...)` or `threadPool.submit(...)`. If you are using `execute(...)` and the task throws an uncaught exception then the thread terminates and pool forgets about the thread and starts another one immediately if appropriate. The task and the thread can get garbage collected. If you are using `submit(...)` then the task will finish, the exception will be caught, and the thread will continue to run and will dequeue the next job submitted to the thread-pool and execute it. You can see what exception is thrown by extending `ThreadPoolExecutor` and overriding: protected void afterExecute(Runnable r, Throwable t) { } With `submit(...)` the thread pool catches all exceptions thrown by the tasks so it can report on the status of the task using `Future`. > Will it terminate and be garbage collected? If `execute(...)` is used then yes, the thread will terminate and it and the task can be garbage collected. If `submit(...)` is used then the thread will not terminate but the task can be garbage collected. Now there are different ways that a pool may decide to reduce the number of threads that are running in it which may cause the thread to terminate and maybe garbage collected. > ... bunch of clients get randomly disconnected ... Meaning that something is interrupting them? Or you are wondering if they throw exceptions? Seems like something else is going on if a bunch terminate at the same time. > My assumption is that the Thread gets interrupted and garbage collected thus Netty losing any references to the thread and disconnecting the assigned tcp clients. If the thread is getting interrupted then someone is calling cancel on the jobs or is shutting down the thread pool. No one else should be interrupting the threads. Regardless, that doesn't cause the thread to be terminated and garbage collected. If the thread is interrupted, the task may keep running of course unless it throws a `RuntimeException` or something. If this happens the thread-pool will clear the interrupt once the task has finished and the thread pulls the next task from the queue. You can see the exception handling with this code: public static void main(String[] args) { ExecutorService threadPool = Executors.newFixedThreadPool(1); // this thread will be killed and replaced threadPool.execute(new Task()); // this thread will catch and handle exception and run the following task threadPool.submit(new Task()); threadPool.submit(new Task()); } private static class Task implements Runnable { @Override public void run() { // this should print out the same thread ids even though the task threw System.out.println(Thread.currentThread().getId()); throw new RuntimeException(); } }