instruction
stringlengths
0
30k
null
I am experiencing an issue with the Chewie package where the controls UI is not displaying properly. Specifically, the time overlaps with the slider, making it difficult to read and interact with the controls and also addition options not at the corner. ps: I am using **CustomScrollView** ChewieController( videoPlayerController: videoPlayerController, autoInitialize: true, useRootNavigator: false, aspectRatio: 16 / 9, ) ![result](https://i.stack.imgur.com/qWFtR.png)
In the My Account > Woocommerce Order menu there is a Pay Now button if the order has not been completed. If you click the Pay Now button you will be directed to the order-pay endpoint checkout page. On this page I want to display a billing details form so that it can be reviewed and edited by customers. I haven't found the appropriate code to change the code in template/checkout/order-pay.php [My Account > Orders](https://i.stack.imgur.com/mxmXg.png) [Order Pay Endpoint](https://i.stack.imgur.com/5izQv.png) I want the order-pay page to be able to display and edit billing details.
How do you make sure that on the order-pay endpoint checkout page you can display and change billing details
|php|mysql|wordpress|woocommerce|dokan|
null
I want to store every error message and API endpoint in database so we to keep track of errors and I want to do this globally in the ASP.NET Core Web API project. If any error occurs in an API call, I want the API endpoint, error message, and userLoggedInId. I want to do this dynamically and globally. [database table](https://i.stack.imgur.com/2jYUI.png) Code snippet of solution and explanation
Want to log error message in database in ASP.NET Core Web API
|asp.net-core-webapi|
Because when you use BuiltInTripleCamera as device type, our App will use Ultra Wide Camera as active primary device. But iPhone 12 Pro don't support Macro Photography so this device don't work well. You should set device.videoZoomFactor = device.virtualDeviceSwitchOverVideoZoomFactors.first. To let Wide Angle camera can be active primary device. And let iPhone choose camera auto. guard let virtualDeviceSwitchOverVideoZoomFactor = input.device.virtualDeviceSwitchOverVideoZoomFactors.first as? CGFloat else { return } try? input.device.lockForConfiguration() input.device.videoZoomFactor = virtualDeviceSwitchOverVideoZoomFactor input.device.unlockForConfiguration() You can see document about it: https://developer.apple.com/documentation/avfoundation/avcaptureprimaryconstituentdevicerestrictedswitchingbehaviorconditions [enter image description here][1] [1]: https://i.stack.imgur.com/MrdFB.png
I'm currently working on an ASP.NET MVC application and aiming to enhance the user experience by integrating a grammar or spellcheck tool into a textarea. I noticed that Grammarly, as well as QuillBot, doesn't seem to offer a direct API that allows me to send text and receive responses which would represent possible text enhancements. The objective is to send user-entered text to the tool's API and display real-time suggestions for corrections on the frontend. Can anyone recommend a specific tool that meets these criteria?
Integrating Grammar/Spellcheck Tool in ASP.NET Application for Textarea
|grammar|spell-checking|uitextchecker|grammarly|
> Regex Match a pattern that only contains one set of numerals, and not more I would start by writing a _grammar_ for the "forgiving parser" you are coding. It is not clear from your examples, for instance, whether `<2112` is acceptable. Must the brackets be paired? Ditto for quotes, etc. Assuming that brackets and quotes do not need to be paired, you might have the following grammar: ##### _sign_ `+` | `-` ##### _digit_ `0` | `1` | `2` | `3` | `4` | `5` | `6` | `7` | `8` | `9` ##### _integer_ [ _sign_ ] _digit_ { _digit_ } ##### _prefix_ _any-sequence-without-a-sign-or-digit_ [ _prefix_ ] { _sign_ } _any-sequence-without-a-sign-or-digit_ ##### _suffix_ _any-sequence-without-a-digit_ ##### _forgiving-integer_ [ _prefix_ ] _integer_ [ _suffix_ ] Notes: - Items within square brackets are optional. They may appear either 0 or 1 time. - Items within curly braces are optional. They may appear 0 or more times. - Items separated by `|` are alternatives from which 1 must be chosen - Items on separate lines are alternatives from which 1 must be chosen With a grammar in hand, it should be much easier to figure out an appropriate regular expression. ### Program My solution, however, is to avoid the inefficiencies of `std::regex`, in favor of coding a simple "parser." In the following program, function `validate_integer` implements the foregoing grammar. When `validate_integer` succeeds, it returns the integer it parsed. When it fails, it throws a `std::runtime_error`. Because `validate_integer` uses `std::from_chars` to convert the integer sequence, it will not convert the test case `2112.0` from the OP. The trailing `.0` is treated as a second integer. All the other test cases work as expected. The only tricky part is the initial loop that skips over non-numeric characters. When it encounters a sign (`+` or `-`), it has to check the following character to decide whether the sign should be interpreted as the start of a numeric sequence. That is reflected in the "tricky" grammar for _prefix_ given above, where a sign must be followed by a non-digit (or another sign). ```lang-cpp // main.cpp #include <cctype> #include <charconv> #include <iomanip> #include <iostream> #include <stdexcept> #include <string> #include <string_view> bool is_digit(unsigned const char c) { return std::isdigit(c); } bool is_sign(const char c) { return c == '+' || c == '-'; } int validate_integer(std::string const& s) { enum : std::string::size_type { one = 1u }; std::string::size_type i{}; // skip over prefix while (i < s.length()) { if (is_digit(s[i]) || is_sign(s[i]) && i + one < s.length() && is_digit(s[i + one])) break; ++i; } // throw if nothing remains if (i == s.length()) throw std::runtime_error("validation failed"); // parse integer // due to foregoing checks, this cannot fail auto const first{ &s[i] }; auto const last{ &s[s.length() - one] + one }; int n; auto [end, ec] { std::from_chars(first, last, n)}; i += end - first; // skip over suffix while (i < s.length() && !is_digit(s[i])) ++i; // throw if anything remains if (i != s.length()) throw std::runtime_error("validation failed"); return n; } void test(std::ostream& log, bool const expect, std::string s) { std::streamsize w{ 46 }; try { auto n = validate_integer(s); log << std::setw(w) << s << " : " << n << '\n'; } catch (std::exception const& e) { auto const msg{ e.what() }; log << std::setw(w) << s << " : " << e.what() << ( expect ? "" : " (as expected)") << '\n'; } } int main() { auto& log{ std::cout }; log << std::left; test(log, true, "<2112>"); test(log, true, "[(2112)]"); test(log, true, "\"2112, \""); test(log, true, "-2112"); test(log, true, ".2112"); test(log, true, "<span style = \"numeral\">2112</span>"); log.put('\n'); test(log, false, "2112.0"); test(log, false, ""); test(log, false, "21,12"); test(log, false, "\"21\",\"12, \""); test(log, false, "<span style = \"font - size:18.0pt\">2112</span>"); test(log, false, "21TwentyOne12"); log.put('\n'); return 0; } // end file: main.cpp ``` ### Output The "hole" in the output, below the entry for 2112.0, is the failed conversion of the null-string. ```lang-none <2112> : 2112 [(2112)] : 2112 "2112, " : 2112 -2112 : -2112 .2112 : 2112 <span style = "numeral">2112</span> : 2112 2112.0 : validation failed (as expected) : validation failed (as expected) 21,12 : validation failed (as expected) "21","12, " : validation failed (as expected) <span style = "font - size:18.0pt">2112</span> : validation failed (as expected) 21TwentyOne12 : validation failed (as expected) ```
In my C# / WPF application, I have a `ListView` that I want to use as a `GridView` to display items in a table: <ListView x:Name="Table_ListView" ItemsSource="{Binding Conditions}"/> It is binded to a `ObservableCollection<Condition>`, where `Condition` is defined like this: public class Condition { public string Name { get; set; } public ObservableCollection<Property> Properties { get; set; } public class Property { public string Name { get; set; } public double Value { get; set; } } } (Please note that I skipped `INotifyPropertyChanged` implementation here to simplify this example code). Idea is that GridView Column headers should display `Name` property of instances of `Condition`, while row headers should display `Name` instance of Property, and the cells - the `Value`. It is expected that all `Condition` instances will have the same number of Property instances with the same names. So for example if we have this method that creates sample data: private ObservableCollection<Condition> CreateConditions() { ObservableCollection<Condition> conditions = new(); conditions.Add( new Condition() { Name = "c1", Properties = new() { new() { Name = "p1", Value = 5 }, new() { Name = "p2", Value = 10 }, new() { Name = "p3", Value = 15 }, } }); conditions.Add( new Condition() { Name = "c2", Properties = new() { new() { Name = "p1", Value = 8 }, new() { Name = "p2", Value = 12 }, new() { Name = "p3", Value = 20 }, } }); conditions.Add( new Condition() { Name = "c3", Properties = new() { new() { Name = "p1", Value = 11 }, new() { Name = "p2", Value = 17 }, new() { Name = "p3", Value = 25 }, } }); return conditions; } Then the GridView table should look like this: - c1 c2 c3 p1 5 8 11 p2 10 12 17 p3 15 20 25 Since I'm trying to use MVVM, the view model looks like this: public class TableResultsViewViewModel { public ObservableCollection<Condition> Conditions { get; set; } public TableResultsViewViewModel(ObservableCollection<Condition> conditions) { this.Conditions = conditions; } } And the main class: public partial class MainWindow : Window { private TableResultsViewViewModel vm; public MainWindow() { InitializeComponent(); ObservableCollection<Condition> conditions = CreateConditions(); //sample data creation method from before vm = new TableResultsViewViewModel(conditions); this.DataContext = vm; } } But I can't figure out how to properly declare the ListView in WPF so that it would dynamically generate these columns and rows as the `ObservableCollection<Condition> Conditions` changes (instances of `Condition` added or removed from this collection, or instances of `Property` added or removed from `Properties` list inside the instances of `Condition`). Has anyone done anything similar and could help me out? EDIT: I am not particularly bound to use ListView/GridView. DataGrid is also acceptable. I just used GridView in my current attempt.
Assume there is an object whose orientation is q_1 now and it's rotating at angular velocity q_r (according to some references I guess the angular velocity is 0.5 * w * q_1). It's expected to change its orientation to q_2 and stop rotating over a time interval dt. How to calculate the angular acceleration?
How to calculate angular acceleration in quaternion form?
|rotation|quaternions|
I'm running a Python Script ("run whether user is logged on or not") on Windows Server 2016 every hour. The Python Script basically just calls an API and exports the results into the JSON file. The problem is, that sometimes JSON file contains weird characters. For example, "7494690" would be displayed as "�Qޘ'". If I'm logged into the server via RDP, then files are coming out fine 10 out of 10 times. If I'm logged out and tasks run automatically, then most often (not always!) I get weird characters - roughly 8-9 times out of 10. I've changed the user, but the issue persists. Any ideas..?
Running Python Script via Task Scheduler returns weird characters in JSON File
|python|windows-server-2016|windows-task-scheduler|
null
I have data with this structure (real data is more complicated): ``` df1 <- read.table(text = "DT odczyt.1 odczyt.2 '2023-08-14 00:00:00' 362 1.5 '2023-08-14 23:00:00' 633 4.3 '2023-08-15 05:00:00' 224 1.6 '2023-08-15 23:00:00' 445 5.6 '2023-08-16 00:00:00' 182 1.5 '2023-08-16 23:00:00' 493 4.3 '2023-08-17 05:00:00' 434 1.6 '2023-08-17 23:00:00' 485 5.6 '2023-08-18 00:00:00' 686 1.5 '2023-08-18 23:00:00' 487 6.8 '2023-08-19 00:00:00' 566 1.5 '2023-08-19 05:00:00' 278 7.9 '2023-08-19 17:00:00' 561 11.5 '2023-08-19 18:00:00' 365 8.5 '2023-08-19 22:00:00' 170 1.8 '2023-08-19 23:00:00' 456 6.6 '2023-08-20 00:00:00' 498 1.5 '2023-08-20 03:00:00' 961 1.54 '2023-08-20 05:00:00' 397 1.6 '2023-08-20 19:00:00' 532 6.6 '2023-08-20 23:00:00' 493 3.8 '2023-08-21 01:00:00' 441 9.2 '2023-08-21 07:00:00' 793 8.5 '2023-08-21 13:00:00' 395 5.5", header = TRUE) %>% mutate (DT = as.POSIXct(DT)) ``` I am selecting 3 hours for which "reading 1" has the maximum value (I sort "reading 1" from the largest values and select the 3 largest values). I leave the days in which these hours occurred and delete the rest of the lines. For the given data these are: 2023-08-20 03:00:00 (961) 2023-08-21 07:00:00 (793) 2023-08-18 00:00:00 (686) therefore the expected result is: ``` > df1 DT odczyt.1 odczyt.2 1 2023-08-18 00:00:00 686 1.50 2 2023-08-18 23:00:00 487 6.80 3 2023-08-20 00:00:00 498 1.50 4 2023-08-20 03:00:00 961 1.54 5 2023-08-20 05:00:00 397 1.60 6 2023-08-20 19:00:00 532 6.60 7 2023-08-20 23:00:00 493 3.80 8 2023-08-21 01:00:00 441 9.20 9 2023-08-21 07:00:00 793 8.50 10 2023-08-21 13:00:00 395 5.50 ```
Selection of days in which one hour meets the condition
|r|dplyr|
null
I have a web API solution, .NET core 8, Visual Studio 2022, where in a controller is managed the upload of a file; the code is: ``` [HttpPost(nameof(UploadAsync) + "/{projectId}")] [ProducesResponseType(StatusCodes.Status201Created)] [ProducesResponseType(StatusCodes.Status400BadRequest)] [RequestSizeLimit(52428800)] // Limit 50 mb public async Task<IActionResult> UploadAsync(int projectId, IFormFile file) { if (file == null || file.Length == 0) { return BadRequest("NO_FILE_UPLOADED"); } // some other verifications, the magic number, and so on string fileNameWithoutExt = Path.GetFileNameWithoutExtension(file.FileName); string extension = Path.GetExtension(file.FileName); string strFile = fileNameWithoutExt + "_" + DateTime.Now.ToString("yyyyMMddHHmmss") + extension; var filePath = Path.Combine(_webHostEnvironment.ContentRootPath, "Uploads", strFile); try { string folderPath = Path.Combine(_webHostEnvironment.ContentRootPath, "Uploads"); bool exists = Directory.Exists(folderPath); if (!exists) { Directory.CreateDirectory(folderPath); } System.Text.Encoding.RegisterProvider(System.Text.CodePagesEncodingProvider.Instance); // System.Text.Encoding.CodePages package required otherwise err "No data is available for encoding 1252" using (var stream = System.IO.File.Create(filePath)) { await file.CopyToAsync(stream); } return Ok(); } catch (Exception e) { return BadRequest(e.Message); } finally { if (System.IO.File.Exists(filePath)) { System.IO.File.Delete(filePath); } } } ``` Typically are uploaded xlsx files, that can be very big (see the RequestSizeLimit) because they are training data for AI. In the posted code, there is no call to the code that processes the xlsx content. The problem is that already by loading the file this occupies a certain amount of memory, which we can see inside Visual Studio, and this memory is not released even if we can see that a certain point GC is working. For example, the API occupies normally 80 MB of RAM on average, after uploading the memory grows to 400 MB, but it never descends to 80: after some uploads the Ubuntu VM for testing crashes because the occupied memory grows at each upload. What could be the problem? how to fix it? thank you.
webAPI File upload does not release memory
|memory|file-upload|asp.net-core-webapi|
> Already value [org.springframework.jdbc.datasource.ConnectionHolder@20f78dcb] for key [HikariDataSource (HikariPool-1)] bound to thread At first, I used a transaction manager that was created for use with the JDBC template. ```java @Bean @Primary public PlatformTransactionManager dbTxManager() { return new DataSourceTransactionManager(clientDestinationDataSource()); } ``` However, in this case, it was impossible to save to the database (on the contrary, reading works without errors): > threw exception; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'transactionManager' available: No matching TransactionManager bean found for qualifier 'transactionManager' - neither qualifier match nor bean name match! Explicitly specifying the right manager in the Transactional annotation did not solve the problem. ```java ClientRepositry repo; @Transactional("dbTxManager") @Override public Long processClient(Client client){ repo.findById(client.getId()) ... repo.save(client); //error } ``` I decided to set up a separate EntityManager. ```java @EnableJpaRepositories( entityManagerFactoryRef = "clientEntityManagerFactory", transactionManagerRef = "transactionManagerSimple", basePackages = "com.integration") @EnableTransactionManagement @Configuration public class DbConfiguration { @Bean public HikariDataSource clientDataSource(DataSourceProperties clientDestinationDbProps) { return clientDestinationDbProps .initializeDataSourceBuilder() .type(HikariDataSource.class) .build(); } @Bean public LocalContainerEntityManagerFactoryBean clientEntityManagerFactory(HikariDataSource clientDataSource) { LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean(); entityManagerFactoryBean.setDataSource(clientDataSource); entityManagerFactoryBean.setPackagesToScan( "com.integration.domain", "com.integration.repository" ); JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter(); entityManagerFactoryBean.setJpaVendorAdapter(vendorAdapter); Properties properties = new Properties(); properties.setProperty("hibernate.dialect", "org.hibernate.dialect.PostgreSQLDialect"); entityManagerFactoryBean.setJpaProperties(properties); return entityManagerFactoryBean; } @Bean public PlatformTransactionManager transactionManagerSimple(EntityManagerFactory clientEntityManagerFactory) { return new JpaTransactionManager(clientEntityManagerFactory); } } ``` basePackages = "com.integration" - The root from where you need to scan your directories to find all the components for the current data source for which you are configuring EntityManager At the time of data processing, it is not possible to open a transaction. > threw exception; nested exception is org.springframework.transaction.CannotCreateTransactionException: Could not open JPA EntityManager for transaction; nested exception is java.lang.IllegalStateException: Already value [org.springframework.jdbc.datasource.ConnectionHolder@20f78dcb] for key [HikariDataSource (HikariPool-1)] bound to thread Do you have any ideas how to fix this?
I want to know what are the collation type is used for viewing emoji or accept in DB what the reason behind it and how its work? >! I need a proper explain about that pls help out of this and moreover what the reason certain collation accept and other why it can't?
is there what are the collation is used for accept emoji in database
|database|collation|adminer|
null
Because when you use BuiltInTripleCamera as device type, our App will use Ultra Wide Camera as active primary device. But iPhone 12 Pro don't support Macro Photography so this device don't work well. You should set device.videoZoomFactor = device.virtualDeviceSwitchOverVideoZoomFactors.first. To let Wide Angle camera can be active primary device. And let iPhone choose camera auto. guard let virtualDeviceSwitchOverVideoZoomFactor = input.device.virtualDeviceSwitchOverVideoZoomFactors.first as? CGFloat else { return } try? input.device.lockForConfiguration() input.device.videoZoomFactor = virtualDeviceSwitchOverVideoZoomFactor input.device.unlockForConfiguration() You can see document about it: https://developer.apple.com/documentation/avfoundation/avcaptureprimaryconstituentdevicerestrictedswitchingbehaviorconditions [Screenshot of key information][1] [1]: https://i.stack.imgur.com/MrdFB.png
I encountered an issue while compiling syzkaller ([a customized version of syzkaller](https://github.com/seclab-fudan/SyzDirect/tree/main/source/syzdirect/syzdirect_fuzzer), based on syzkaller commit a371c43c33b6f901421f93b655442363c072d251,Compiling on this commit was successful). When using make fuzzer, I received a message saying ``` build constraints exclude all Go files in xxx ``` [enter image description here](https://i.stack.imgur.com/GVtIO.png) Since my environment is amd64 and Linux, I thought this would be normal; however, the compilation failed. I tried to use -x and -v to display the compilation logs, but -v did not produce any output, and the file /tmp/go-xxxxx generated by -x was empty. here is the compile command: [enter image description here](https://i.stack.imgur.com/VnZs7.png) I would like to know why the compilation fails, as it does not display any errors or warnings. Is there any way to make Go show this information? I tried to use -x and -v to display the compilation logs, but -v did not produce any output, and the file /tmp/go-xxxxx generated by -x was empty. here is the full output : ``` zec@creat2012-Inspiron-3910:~/SyzDirect/source/syzdirect/syzdirect_fuzzer$ make fuzzer go list -f '{{.Stale}}' ./sys/syz-sysgen | grep -q false || go install ./sys/syz-sysgen make .descriptions make[1]: '.descriptions' is up to date. GOOS=linux GOARCH=amd64 go build "-ldflags=-s -w -X github.com/google/syzkaller/prog.GitRevision=02c9a6504a757e6cec0f10202624d175aa474d94+ -X 'github.com/google/syzkaller/prog.gitRevisionDate=20240118-134457'" "-tags=syz_target syz_os_linux syz_arch_amd64 " -o ./bin/linux_amd64/syz-fuzzer github.com/google/syzkaller/syz-fuzzer package github.com/google/syzkaller/syz-fuzzer imports github.com/google/syzkaller/pkg/cover imports github.com/google/syzkaller/pkg/cover/backend imports github.com/google/syzkaller/pkg/host imports github.com/google/syzkaller/pkg/csource imports github.com/google/syzkaller/pkg/mgrconfig imports github.com/google/syzkaller/sys imports github.com/google/syzkaller/sys/akaros/gen: build constraints exclude all Go files in /home/zec/SyzDirect/source/syzdirect/syzdirect_fuzzer/sys/akaros/gen package github.com/google/syzkaller/syz-fuzzer imports github.com/google/syzkaller/pkg/cover imports github.com/google/syzkaller/pkg/cover/backend imports github.com/google/syzkaller/pkg/host imports github.com/google/syzkaller/pkg/csource imports github.com/google/syzkaller/pkg/mgrconfig imports github.com/google/syzkaller/sys imports github.com/google/syzkaller/sys/darwin/gen: build constraints exclude all Go files in /home/zec/SyzDirect/source/syzdirect/syzdirect_fuzzer/sys/darwin/gen package github.com/google/syzkaller/syz-fuzzer imports github.com/google/syzkaller/pkg/cover imports github.com/google/syzkaller/pkg/cover/backend imports github.com/google/syzkaller/pkg/host imports github.com/google/syzkaller/pkg/csource imports github.com/google/syzkaller/pkg/mgrconfig imports github.com/google/syzkaller/sys imports github.com/google/syzkaller/sys/freebsd/gen: build constraints exclude all Go files in /home/zec/SyzDirect/source/syzdirect/syzdirect_fuzzer/sys/freebsd/gen package github.com/google/syzkaller/syz-fuzzer imports github.com/google/syzkaller/pkg/cover imports github.com/google/syzkaller/pkg/cover/backend imports github.com/google/syzkaller/pkg/host imports github.com/google/syzkaller/pkg/csource imports github.com/google/syzkaller/pkg/mgrconfig imports github.com/google/syzkaller/sys imports github.com/google/syzkaller/sys/fuchsia/gen: build constraints exclude all Go files in /home/zec/SyzDirect/source/syzdirect/syzdirect_fuzzer/sys/fuchsia/gen package github.com/google/syzkaller/syz-fuzzer imports github.com/google/syzkaller/pkg/cover imports github.com/google/syzkaller/pkg/cover/backend imports github.com/google/syzkaller/pkg/host imports github.com/google/syzkaller/pkg/csource imports github.com/google/syzkaller/pkg/mgrconfig imports github.com/google/syzkaller/sys imports github.com/google/syzkaller/sys/netbsd/gen: build constraints exclude all Go files in /home/zec/SyzDirect/source/syzdirect/syzdirect_fuzzer/sys/netbsd/gen package github.com/google/syzkaller/syz-fuzzer imports github.com/google/syzkaller/pkg/cover imports github.com/google/syzkaller/pkg/cover/backend imports github.com/google/syzkaller/pkg/host imports github.com/google/syzkaller/pkg/csource imports github.com/google/syzkaller/pkg/mgrconfig imports github.com/google/syzkaller/sys imports github.com/google/syzkaller/sys/openbsd/gen: build constraints exclude all Go files in /home/zec/SyzDirect/source/syzdirect/syzdirect_fuzzer/sys/openbsd/gen package github.com/google/syzkaller/syz-fuzzer imports github.com/google/syzkaller/pkg/cover imports github.com/google/syzkaller/pkg/cover/backend imports github.com/google/syzkaller/pkg/host imports github.com/google/syzkaller/pkg/csource imports github.com/google/syzkaller/pkg/mgrconfig imports github.com/google/syzkaller/sys imports github.com/google/syzkaller/sys/test/gen: build constraints exclude all Go files in /home/zec/SyzDirect/source/syzdirect/syzdirect_fuzzer/sys/test/gen package github.com/google/syzkaller/syz-fuzzer imports github.com/google/syzkaller/pkg/cover imports github.com/google/syzkaller/pkg/cover/backend imports github.com/google/syzkaller/pkg/host imports github.com/google/syzkaller/pkg/csource imports github.com/google/syzkaller/pkg/mgrconfig imports github.com/google/syzkaller/sys imports github.com/google/syzkaller/sys/trusty/gen: build constraints exclude all Go files in /home/zec/SyzDirect/source/syzdirect/syzdirect_fuzzer/sys/trusty/gen package github.com/google/syzkaller/syz-fuzzer imports github.com/google/syzkaller/pkg/cover imports github.com/google/syzkaller/pkg/cover/backend imports github.com/google/syzkaller/pkg/host imports github.com/google/syzkaller/pkg/csource imports github.com/google/syzkaller/pkg/mgrconfig imports github.com/google/syzkaller/sys imports github.com/google/syzkaller/sys/windows/gen: build constraints exclude all Go files in /home/zec/SyzDirect/source/syzdirect/syzdirect_fuzzer/sys/windows/gen make: *** [Makefile:158: fuzzer] Error 1 ```
compile syzkaller fuzzer failed without any error or warning
|go|compilation|fuzzing|
null
Ignite C++ Thin Clients. The class CacheClient does not throw any ignite errors if the connection is lost during any of the get/remove/contains/insert operations. Is there an alternative mechanism to handle the connection lost scenarios? Connection Failover is ok, but if all the cluster connections are lost, how the application will be notified about the situation?
Apache Ignite c++ client 2.16. How to handle the connection lost scenarios in the middle of any cache insert/remove/get operations
|apacheignite|
For the Same wifi connection of computer and mobile. All these answers are right but they did not mention that the IP address must be the wifi IP. if you run the program locally and your wifi is from a **Wi-Fi router** then the IP should be Wi-Fi IP. [Look in image.][1] [1]: https://i.stack.imgur.com/Q1sW8.png
Currently i have this code `Private Sub Worksheet_Change(ByVal Target As Range)` `Application.EnableEvents = True ' <-- just for tests` `If Not Intersect(Target, Range("C1")) Is Nothing Then` `Select Case Target.Value` `Case "Expander 1 eff"` `CopyIncreaseRecord` `Case "Expander 2 eff"` `CopyIncreaseRecord` `Case "Pump eff"` `CopyIncreaseRecord` `Case "Net Power"` `CopyIncreaseRecordNetPower` `End Select` `End If ` `End Sub` under the Sheet5 (Graph1) view code. presently i'm using one drop down in cell C1 to tell which macro to run automatically when i select an option in cell C1, now i want to have two drop downs in cell C1 & in cell C2, for example if C1 is selected "Expander 2 eff" and C2 is selected "Cycle eff" i want macro Expander2effvsCycleeff to run if C1 is selected "Expander 2 eff" and C2 is selected "Massflowrate" i want macro Expander2effvsMassflowrate to run. pls help, thanks in advance i tried AI but it is not giving me the selection in two cells to be met
I have used the following code, and everything worked fine for me you can check your code and edit accordingly, I might work for you too. THIS IS MY PROXY SETUP IN THE vite.config.js file import { defineConfig } from 'vite' import react from '@vitejs/plugin-react' // https://vitejs.dev/config/ export default defineConfig({ server:{ proxy: { '/api': { target: 'http://127.0.0.1:3000', secure: false, }, } }, plugins: [react()], }); not the changes on the localhost in the 'target' value -Here is my post-request for the same: // submit to the backend const handleSubmit = async (e) => { e.preventDefault(); try { const res = await fetch('/api/auth/signup', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(formData), }) const data = await res.json(); console.log(data); } catch (error) { console.log(error) } }
I am trying to work with .tiff files and I want to ensure that I don't alter the files more than intended, so if I don' make any changes, I expect a 100% identical output with same file-size. To validate that I, initially read and saved a tiff-File to see if there is any unexpected change, and yes, the file-size is ~3% larger. This is my code: import tifffile as tiff image_file = "Image.tiff" output_file = "Processed_Image.tiff" image_array = tiff.imread(image_file) tags = tiff.TiffFile(image_file).pages.pages[0].tags compression = tags["Compression"].value rowsperstrip = tags["RowsPerStrip"].value tiff.imwrite(output_file, image_array, compression=compression, rowsperstrip=rowsperstrip) I can't find a way to add these two tags: tags["StripOffsets"].value tags["StripByteCounts"].value I analysed the differences of the array itself,Tiff-Object and with a tool called Exiftool.exe and found out there are differences in StripOffsets and StripByteCounts, but the compression, shape and array-values are identical (np.array_equal() returns True) I tried to pass over as many arguments to the imwrite() function as possible, so it doesn't use unwanted default values to change the image.
Reading and saving untouched .tiff-File with tifffile lib changes file-size and "StripOffsets" and "StripByteCounts" values
|python|arrays|image|computer-vision|tiff|
null
What is the maximum length for `firstname.lastname` combination for login? For example, I am observing that using combination like: **first name** - `firstname` **last name** - `lastname1234` and using `firstname.lastname1234` as user name fails, so I have to truncate it to `firstname.lastname12` so I wonder, what is the actual limit, or I am having configuration issue.
Azure DevOps firstname.lastname login length
|azure-devops|
```java class Test { public static void main(String[] args) { Optional<Y> opY = Optional.of( new Y() ) ; // ERROR Optional<X> opX = (Optional<X>) opY ; } } class X {} class Y extends X {} ``` As in the code above, because `Optional<Y>` is not an `Optional<X>`, there is an Error. But why is there no problem with the following code? ```java Optional<X> opX = Optional.of( new Y() ) ; ```
I use the React framework and react-router-dom 6 for routing. In my application, the base route is /. (login) The user is prompted to log in, and if recognized by the database, they are redirected to /home. On the other hand, if the user is unable to log in, the user remains on /login. I would simply like to protect a route: the /home route to prevent a user from accessing this route by typing in the "/home" URL. I don't really understand how to do this. I've searched everywhere on the internet but nothing works. With my current code I can't reach /home, but neither can I when I'm properly homed. ``` import React from 'react'; import './App.css'; import Login from './components/Login/Login'; import ControlPanel from './components/ControlPanel/ControlPanel'; import { BrowserRouter as Router, Routes, Route } from 'react-router-dom'; import PrivateRoutes from './components/PrivateRoute/PrivateRoute'; function App() { return ( <div className='App'> <Router> <Routes> <Route element={<PrivateRoutes />}> <Route element={<ControlPanel/>} path='/cpanel' exact/> </Route> <Route element={<Login/>} path='/'></Route> </Routes> </Router> </div> ); } export default App; ``` ``` import { Outlet, Navigate } from 'react-router-dom'; const PrivateRoutes = () => { let auth = {'token':false} return( auth.token ? <Outlet/> : <Navigate to="/"/> ) } export default PrivateRoutes ``` Concerning the Login component, I make a request with Axios and if the user is recognized then I redirect to /cpanel. Here is an excerpt of this component: ``` import React, { useState, useEffect } from 'react'; import { useNavigate } from 'react-router-dom'; import imageNice from '../../images/Nice.jpg'; import axios from 'axios'; const Login = () => { const [id, setid] = useState(''); const [pass, setpass] = useState(''); const [error, setError] = useState(''); const [message, setMessage] = useState(''); const [buttonLoading, setButtonLoading] = useState(false); const [buttonSuccess, setButtonSuccess] = useState(false); const navigate= useNavigate(); const handleLogin = async (e) => { e.preventDefault(); try { setButtonLoading(true); const response = await axios.post('https://---------------/api/connexion', { id, pass, }); if (response.data.success) { setButtonSuccess(true); setMessage('Connection success !'); navigate('/cpanel');; } else { setError('id or pass incorrect'); } } catch (error) { console.error('error to connect', error); setError('error'); } finally { setTimeout(() => { setButtonLoading(false); setButtonSuccess(false); }, 2000); } }; ```
impossible to protect a route with react-router-dom 6
|reactjs|routes|react-router-dom|
It's worth clicking the [learn more][1] link on the `[system.reactive]` tag, we put a fair bit of info there! From the intro there you can see that Rx is not a message queueing technology: > The Reactive Extensions (Rx) is a library for composing asynchronous and event-based programs using observable sequences and LINQ-style query operators. System.Reactive is the root namespace used through the library. Using Rx, developers represent asychronous data streams using LINQ operators, and parameterize the concurrency in the asynchronous data streams using Schedulers. Simply put, Rx = Observables + LINQ + Schedulers. So, Rx and message queueing are really distinct technologies that can complement each other quite well. A classic example is a stock price ticker service - this might be delivered via message queuing, but then transformed by Rx to group, aggregate and filter prices. You can go further: much as Entity Framework turns `IQueryable<T>` queries into SQL run directly on the database, you can create providers that turn Rx `IQbservable<T>` queries into native queries - for example a `Where` filter might leverage the native filtering capability that exists in many message queueing technologies to apply filters directly. This is quite a lot of work though, and hard. It's much easier, and not uncommon to see message queue messages fed into an Rx `Subject` so that incoming messages from a queue are transformed into an Rx stream for easy consumption in the client. Rx is also used extensively in GUIs to work with client side events like button presses and text box changes to make traditionally difficult scenarios like drag-n-drop and text auto-completion via asynchronous server queries dramatically easier. There's a good hands on lab covering the later scenario [here][2]. It was written against an early release of Rx, but still is very relevant. I recommend looking at this video presentation by Bart de Smet for a fantastic intro: [Curing Your Event Processing Blues with Reactive Extensions (Rx)][3] - including the classic Rx demo that writes a query over a live feed from Kinect to interpret hand-waving! [1]: https://stackoverflow.com/tags/system.reactive/info [2]: https://download.microsoft.com/download/C/5/D/C5D669F9-01DF-4FAF-BBA9-29C096C462DB/Rx%20HOL%20.NET.pdf [3]: https://learn.microsoft.com/en-us/events/teched-2012/dev413
null
i am using sox for creating synth with 100ms, this is my command: ``` /usr/bin/sox -V -r 44100 -n -b 64 -c 1 file.wav synth 0.1 sine 200 vol -2.0dB ``` now when i create 3 sine wave files and i combine all with ``` /usr/bin/sox file1.wav file2.wav file3.wav final.wav ``` then i get gaps between the files. i dont know why. but when i open for example file1.wav then i also see a short gap in front and at the end of the file. how can i create a sine with exact 100ms without gaps in front and end? and my 2nd question: is there also a possibility to create e.g. 10 sine wave synths with one command in sox? like sox f1 200 0.1, f2 210 01, f3 220 01, ... first 200hz 10ms, 210hz 10ms, 220hz 10ms thank you so much many greets i have tried some different options in sox but always each single sine file looks like that: [WAV GAP][1] [1]: https://i.stack.imgur.com/12EUp.jpg
|react-native|expo|
I wonder what database systems you are used to, if you are worried that rebuilding the primary key index could cause damage. It cannot cause damage. On the other hand, it is only rarely necessary to rebuild an index. Only do that if you know it is necessary &mdash; for example, after checking for bloat with the `pgstatindex()` function.
Launching lib\main.dart on 2201117TI in debug mode... Running Gradle task 'assembleDebug'... ../../AppData/Local/Pub/Cache/hosted/pub.dev/agora_uikit-1.3.7/lib/models/agora_rtc_event_handlers.dart:189:7: Error: Type 'LocalVideoStreamError' not found. LocalVideoStreamError error)? onLocalVideoStateChanged; ^^^^^^^^^^^^^^^^^^^^^ ../../AppData/Local/Pub/Cache/hosted/pub.dev/agora_uikit-1.3.7/lib/models/agora_rtc_event_handlers.dart:354:40: Error: Type 'RhythmPlayerErrorType' not found. RhythmPlayerStateType state, RhythmPlayerErrorType errorCode)? ^^^^^^^^^^^^^^^^^^^^^ ../../AppData/Local/Pub/Cache/hosted/pub.dev/agora_uikit-1.3.7/lib/models/agora_rtc_event_handlers.dart:446:7: Error: Type 'LocalAudioStreamError' not found. LocalAudioStreamError error)? onLocalAudioStateChanged; ^^^^^^^^^^^^^^^^^^^^^ ../../AppData/Local/Pub/Cache/hosted/pub.dev/agora_uikit-1.3.7/lib/models/agora_rtc_event_handlers.dart:521:7: Error: Type 'RtmpStreamPublishErrorType' not found. RtmpStreamPublishErrorType errCode)? onRtmpStreamingStateChanged; ^^^^^^^^^^^^^^^^^^^^^^^^^^ ../../AppData/Local/Pub/Cache/hosted/pub.dev/agora_uikit-1.3.7/lib/models/agora_rtc_event_handlers.dart:554:23: Error: Type 'ChannelMediaRelayEvent' not found. final void Function(ChannelMediaRelayEvent code)? onChannelMediaRelayEvent; ^^^^^^^^^^^^^^^^^^^^^^ ../../AppData/Local/Pub/Cache/hosted/pub.dev/agora_uikit-1.3.7/lib/models/agora_rtc_event_handlers.dart:189:7: Error: 'LocalVideoStreamError' isn't a type. LocalVideoStreamError error)? onLocalVideoStateChanged; ^^^^^^^^^^^^^^^^^^^^^ ../../AppData/Local/Pub/Cache/hosted/pub.dev/agora_uikit-1.3.7/lib/models/agora_rtc_event_handlers.dart:354:40: Error: 'RhythmPlayerErrorType' isn't a type. RhythmPlayerStateType state, RhythmPlayerErrorType errorCode)? ^^^^^^^^^^^^^^^^^^^^^ ../../AppData/Local/Pub/Cache/hosted/pub.dev/agora_uikit-1.3.7/lib/models/agora_rtc_event_handlers.dart:446:7: Error: 'LocalAudioStreamError' isn't a type. LocalAudioStreamError error)? onLocalAudioStateChanged; ^^^^^^^^^^^^^^^^^^^^^ ../../AppData/Local/Pub/Cache/hosted/pub.dev/agora_uikit-1.3.7/lib/models/agora_rtc_event_handlers.dart:521:7: Error: 'RtmpStreamPublishErrorType' isn't a type. RtmpStreamPublishErrorType errCode)? onRtmpStreamingStateChanged; ^^^^^^^^^^^^^^^^^^^^^^^^^^ ../../AppData/Local/Pub/Cache/hosted/pub.dev/agora_uikit-1.3.7/lib/models/agora_rtc_event_handlers.dart:554:23: Error: 'ChannelMediaRelayEvent' isn't a type. final void Function(ChannelMediaRelayEvent code)? onChannelMediaRelayEvent; ^^^^^^^^^^^^^^^^^^^^^^ ../../AppData/Local/Pub/Cache/hosted/pub.dev/agora_uikit-1.3.7/lib/controllers/rtc_event_handlers.dart:146:6: Error: No named parameter with the name 'onChannelMediaRelayEvent'. }, onChannelMediaRelayEvent: (code) { ^^^^^^^^^^^^^^^^^^^^^^^^ ../../AppData/Local/Pub/Cache/hosted/pub.dev/agora_rtc_engine-6.3.0/lib/src/agora_rtc_engine.dart:1576:9: Context: Found this candidate, but the arguments don't match. const RtcEngineEventHandler({ ^^^^^^^^^^^^^^^^^^^^^ Target kernel_snapshot failed: Exception FAILURE: Build failed with an exception. * What went wrong: Execution failed for task ':app:compileFlutterBuildDebug'. > Process 'command 'C:\Users\kgour\Downloads\flutter_windows_3.19.1-stable\flutter\bin\flutter.bat'' finished with non-zero exit value 1 * Try: > Run with --stacktrace option to get the stack trace. > Run with --info or --debug option to get more log output. > Run with --scan to get full insights. * Get more help at https://help.gradle.org BUILD FAILED in 11s Error: Gradle task assembleDebug failed with exit code 1 **Here is the code where i have used agora ui kit.** ``` import 'package:flutter/cupertino.dart'; import 'package:agora_uikit/agora_uikit.dart'; import 'package:flutter/material.dart'; class VideoCallScreen extends StatefulWidget{ const VideoCallScreen({Key? key}): super(key: key); @override State<VideoCallScreen> createState() => _VideoCallScreenState(); } class _VideoCallScreenState extends State<VideoCallScreen>{ final AgoraClient _client = AgoraClient(agoraConnectionData: AgoraConnectionData( appId: '305587582691460b8345fcdb4542463b', channelName: 'fluttering', tempToken: '007', ),); @override void initState() { super.initState(); _initAgora(); } Future<void>_initAgora() async{ await _client.initialize(); } @override Widget build(BuildContext context) { return WillPopScope( onWillPop: () async => false, child: Scaffold( appBar: AppBar( automaticallyImplyLeading: false, title: Text('Video Call'), ), body: SafeArea( child: Stack( children: [ AgoraVideoViewer(client: _client, layoutType: Layout.floating, showNumberOfUsers: true,), AgoraVideoButtons(client: _client, enabledButtons: [ BuiltInButtons.toggleCamera, BuiltInButtons.callEnd, BuiltInButtons.toggleMic, ],), ], ), ), ), ); } } ```
I've been delving into Ktor to learn about Websockets, but despite spending numerous hours researching similar questions, I'm still unable to pinpoint the root of my issue. I'm trying to open multiple websocket sessions using Ktor to be able to send and receive messages between the users. However, once I create a websocket session, it closes itself. I'm initializing the websocket session once the main login page of my application opens up. I've also tried understanding the answer to this [same problem](https://stackoverflow.com/questions/65314683/how-to-keep-a-kotlin-ktor-websocket-open), but they're using a html file. I there another solution to this problem? Here is the code where I create the websocket session: ``` // In CommManager object suspend fun receiveMessage(session: DefaultWebSocketSession) { var text = "" while (connected.get() == true) { try { for (othersMessages in session.incoming) { othersMessages as? Frame.Text ?: continue text = othersMessages.readText() println(text) } } catch (e: Exception) { e.printStackTrace() } } } // In the login page suspend fun createWebsocketSession() { val session = client.webSocketSession(method = HttpMethod.Get, host = "hosturl", port = 8080, path = "/webSocketSession") CommManager.connected.set(true) CommManager.receiveMessage(session) } init { // Initialize Websocket session here coroutine.launch() { createWebsocketSession() } } ``` As for the server side: ``` routing() { webSocket("/webSocketSession") { ConnectionsHandler.connectWebSocketSession(this) } } // ConnectionsHandler object fun connectWebSocketSession(session: DefaultWebSocketSession){ println("adding new user") val thisConnection = Connection(session) webSocketUserList += thisConnection println("${thisConnection.name} is connected!") } ``` After running the server and then the client, this is what I get as output from the server: ``` Route resolve result: SUCCESS @ /webSocketSession/(method:GET)/(header:Connection = Upgrade)/(header:Upgrade = websocket) 2024-03-19 09:35:25.142 [eventLoopGroupProxy-4-1] TRACE i.k.s.p.c.ContentNegotiation - Skipping because body is already converted. 2024-03-19 09:35:25.165 [eventLoopGroupProxy-3-5] TRACE io.ktor.websocket.WebSocket - Starting default WebSocketSession(io.ktor.websocket.DefaultWebSocketSessionImpl@49a741b5) with negotiated extensions: 2024-03-19 09:35:25.169 [eventLoopGroupProxy-3-5] TRACE io.ktor.server.websocket.WebSockets - Starting websocket session for /webSocketSession adding new user user0 is connected! 2024-03-19 09:35:25.218 [eventLoopGroupProxy-3-5] TRACE io.ktor.websocket.WebSocket - Sending Frame CLOSE (fin=true, buffer len = 2) from session io.ktor.websocket.DefaultWebSocketSessionImpl@49a741b5 2024-03-19 09:35:25.222 [eventLoopGroupProxy-3-5] TRACE io.ktor.websocket.WebSocket - Sending Close Sequence for session io.ktor.websocket.DefaultWebSocketSessionImpl@49a741b5 with reason CloseReason(reason=NORMAL, message=) and exception null 2024-03-19 09:35:25.251 [eventLoopGroupProxy-3-3] TRACE io.ktor.websocket.WebSocket - WebSocketSession(StandaloneCoroutine{Active}@2cea43ee) receiving frame Frame CLOSE (fin=true, buffer len = 2) ``` From my understanding, "sending Frame CLOSE" means that it is closing the websocket session, but I haven't specified any command to do so in the client or the server. Am I missing something in the server side to keep the session running? If you need more information about the problem, please tell me and I'll edit the post.
Does method Optional.of do a type conversion?
|java|generics|
I'm trying to create a dot indicator for a carousel slider using the [carousel_slider](https://pub.dev/packages/carousel_slider) package. No idea why it's not rebuilding at all. Simple carousel of images with a dot indicator at the bottom that rebuilds when based on index of image on the carousel. CODE: class Testhome extends StatelessWidget { const Testhome({super.key}); @override Widget build(BuildContext context) { CarouselController homepagecontroller = CarouselController(); final SliderController slidercontrollerinstance = SliderController(); return Scaffold( appBar: AppBar( title: Text('Welcome Alexander', style: ttextthemes.darktheme.headlineMedium), automaticallyImplyLeading: false, actions: [ // Search icon button IconButton( color: Colors.black, icon: const Icon(Icons.search), onPressed: () { // Show modal search bar using a package or custom implementation }) ]), body: SingleChildScrollView( child: Column(children: [ const SizedBox(height: Tsizes.spacebtwitems), //search bar const Tsearchbar(text: 'Search in Store'), //spacing const SizedBox(height: Tsizes.spacebtwitems), //heading const Theadingbar( text: 'Popular categories', showbutton: true, ), //spacing const SizedBox(height: Tsizes.spacebtwitems), //category icons const Homecategories(), Padding( padding: const EdgeInsets.all(Tsizes.spacebtwitems), child: Column(children: [ CarouselSlider( items: const [ CarouselImages(imageurl: Timages.onboardingimage2), CarouselImages(imageurl: Timages.onboardingimage), CarouselImages(imageurl: Timages.onboardingimage3) ], options: CarouselOptions( viewportFraction: 1, autoPlay: true, onPageChanged: (index, reason) { slidercontrollerinstance.updateController(index); }, )), const SizedBox(height: Tsizes.spacebtwitems), Consumer<SliderController>( builder: (context, slidercontrollerinstance, _) { return Row( mainAxisAlignment: MainAxisAlignment.center, children: [ for (int i = 0; i < picturescarousel.length; i++) Tcircularwidget( hieght: 4, colour: slidercontrollerinstance.currentIndex == i ? const Color.fromARGB(255, 15, 74, 104) : Colors.grey) ]); }) ])) ] // carousel ))); } } final List picturescarousel = [ const CarouselImages(imageurl: Timages.onboardingimage2), const CarouselImages(imageurl: Timages.onboardingimage), const CarouselImages(imageurl: Timages.onboardingimage3) ]; class SliderController extends ChangeNotifier { int _currentIndex = 0; int get currentIndex => _currentIndex; void updateController(int index) { _currentIndex = index; notifyListeners(); } } class Tcircularwidget extends StatelessWidget { const Tcircularwidget( {super.key, this.colour = const Color.fromARGB(255, 15, 74, 104), this.hieght = 10, this.width = 10, this.borderradius = Tsizes.boarderradiusLG, this.padding = 5, this.margin}); final Color colour; final double width, hieght; final double borderradius; final double padding; final EdgeInsets? margin; @override Widget build(BuildContext context) { return Container( width: width, height: hieght, padding: EdgeInsets.all(padding), margin: EdgeInsets.only(right: padding), decoration: BoxDecoration( color: colour, borderRadius: BorderRadius.circular(Tsizes.boarderradiusLG))); } } I don't see why it's not rebuilding. It's only a simple dot indicator. Should be very simple, all the resources im using say im doing things properly
{"Voters":[{"Id":28128,"DisplayName":"David Grayson"},{"Id":589924,"DisplayName":"ikegami"},{"Id":2756409,"DisplayName":"TylerH"}]}
null
I have an delete option in my project, now i want to create a confirmation modal, but had a problem with button printing. There is an issue, that quantity of this buttons equals of task quantity.[Screenshot of my page](https://i.stack.imgur.com/upta8.png) [Screenshot of my confirmation modal](https://i.stack.imgur.com/TAjkq.png) The point is that I want to display only one confirmation button to the task I want to delete.
Is there alternative way to print out buttons without using v-for
|laravel|vue.js|
null
While nested variable expansion is not possible in Bash, in this particular case you could use the following one-liner: ``` echo $(tr '[:lower:'] '[:upper:]' <<<${var//pattern/repl}) ```
My goal is to have a generic way to traverse a `std::tupple`, and the following code tries to show it: #include <iostream> #include <tuple> using namespace std; template <typename t, size_t t_idx, typename t_tuple> concept visit_tuple_element_value = requires(t &&p_t, const t_tuple &p_tuple) { { p_t.template operator()<t_idx>( std::declval<std::add_const_t<std::add_lvalue_reference_t<t_tuple>>>()) } -> std::same_as<bool>; }; template <typename t_tuple, typename t_function, size_t t_idx = 0> requires(visit_tuple_element_value<t_function, t_idx, t_tuple>) void traverse_tuple_values(t_function p_function, const t_tuple &p_tuple) { if constexpr (t_idx < std::tuple_size_v<t_tuple>) { if (p_function.template operator()<t_idx>(p_tuple)) { traverse_tuple_values<t_tuple, t_function, t_idx + 1>(p_function, p_tuple); } } } struct a {}; struct b {}; struct c {}; using my_tuple = std::tuple<b, a, c>; int main() { my_tuple _tuple; auto _visitor = [&]<size_t t_idx>(const my_tuple & /*p_tuple*/) { if constexpr (std::is_same_v<std::tuple_element_t<t_idx, my_tuple>, a>) { std::cout << "'a' is at index " << t_idx << std::endl; } else { std::cout << "'a' is NOT at index " << t_idx << std::endl; } return true; }; traverse_tuple_values(_visitor, _tuple); return 0; } I am getting the error: 'traverse_tuple_values<std::tuple<b, a, c>, (lambda at main.cpp:63:19), 3UL>' I do not understand why `p_function.template operator()<t_idx>(p_tuple)`, and therefore `_visitor`, is being called with `t_idx` equals to 3, if I have in `traverse_tuple_values` the line `if constexpr (t_idx < std::tuple_size_v<t_tuple>)`. `g++ --version` reports `g++ (Ubuntu 11.4.0-1ubuntu1~22.04) 11.4.0`
This question is just so that I may understand the logic of except when one attempts to avoid certain nodes. So a completely useless example follows, but it illustrates my question. Why is it that this code ``` <?xml version="1.0" encoding="UTF-8"?> <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:math="http://www.w3.org/2005/xpath-functions/math" exclude-result-prefixes="xs math" expand-text="true" version="3.0"> <xsl:strip-space elements="*" /> <xsl:mode on-no-match="shallow-copy"/> <xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/> <xsl:template match="A[1]"> <xsl:apply-templates select="/S//A/* except (B, C)" mode="P"/> </xsl:template> <xsl:template match="*" mode="P"> <M>{text()}</M> </xsl:template> </xsl:stylesheet> ``` when run on this xml ``` <?xml version="1.0" encoding="UTF-8"?> <S> <A> <B>X</B> <C>Y</C> </A> <A> <B>T</B> <C>R</C> </A> </S> ``` yields this, ``` <?xml version="1.0" encoding="UTF-8"?> <S> <M>T</M> <M>R</M> <A> <B>T</B> <C>R</C> </A> </S> ``` and this code ``` <?xml version="1.0" encoding="UTF-8"?> <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:math="http://www.w3.org/2005/xpath-functions/math" exclude-result-prefixes="xs math" expand-text="true" version="3.0"> <xsl:strip-space elements="*" /> <xsl:mode on-no-match="shallow-copy"/> <xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/> <xsl:template match="A[1]"> <xsl:apply-templates select="/S//A/*[not(self::B or self::C)]" mode="P"/> </xsl:template> <xsl:template match="*" mode="P"> <M>{text()}</M> </xsl:template> </xsl:stylesheet> ``` yields this? ``` <?xml version="1.0" encoding="UTF-8"?> <S> <A> <B>T</B> <C>R</C> </A> </S> ``` Shouldn't the result be the same? I would expect the last result from both code examples.
Logic of except in XSLT
|xslt-2.0|xslt-3.0|
To prevent this from happening, you can instruct the browser not to cache the login page. This can be achieved by adding response headers. Here is a modified version of your login function to include these headers: ``` from flask import make_response @app.route('/login', methods=['POST', 'GET']) def login(): error = None if request.method == 'POST': pass else: response = make_response(render_template('login.html', error=None)) response.headers['Cache-Control'] = 'no-cache, no-store, must-revalidate' response.headers['Pragma'] = 'no-cache' response.headers['Expires'] = '0' return response ``` These headers tell the browser not to cache the page, forcing it to make a new GET request when the user navigates back, ensuring the error message is cleared.
I need to use uitableview to draw a message list. [![expected list](https://i.stack.imgur.com/2Qszg.png)](https://i.stack.imgur.com/2Qszg.png) In each tableviewcell, I use UIHostingController to load swiftui view. I found that when the page scrolls (and the cell is reused), there will be a werid offset. I used tableView.contentInsetAdjustmentBehavior = .scrollableAxes or automatic and it returned to normal, but when I tried to add any uiview under this tableview, the problem occurred again. [![werid offset in each cell](https://i.stack.imgur.com/UgXUr.png)](https://i.stack.imgur.com/UgXUr.png) [![enter image description here](https://i.stack.imgur.com/VJ3KH.png)](https://i.stack.imgur.com/VJ3KH.png) a simple demo code: ``` import SwiftUI import Combine struct DemoView: View { let height : CGFloat var body: some View { ZStack(alignment: .top, content: { Color.random Text("RowHeight:\(height)") ZStack(alignment: .bottom) { Color.clear Text("Bottom") } }) .frame(height: height) } } class DemoTableView : UIViewController, UITableViewDelegate, UITableViewDataSource { let ROW_COUNT = 20 func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { ROW_COUNT } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return CGFloat(50 + indexPath.row*5) } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { if let cell = tableView.dequeueReusableCell(withIdentifier: "cell") { cell.contentView.subviews.forEach{ $0.removeFromSuperview() } let ht = self.tableView(tableView, heightForRowAt: indexPath) let view = DemoView(height: ht) let host = UIHostingController(rootView: view) cell.contentView.place(host.view) { v, ly in ly.inset = .zero } self.addChild(host) host.didMove(toParent: self) host.view.invalidateIntrinsicContentSize() return cell } return .init(style: .default, reuseIdentifier: "cell") } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) self.view.backgroundColor = .white //HERE: I tried to add any uiview under this tableview, then the problem occurred again self.view.addSubview(UIView()) let tableView = UITableView(frame: self.view.bounds, style: .plain) //both autoresize & autolayout has the same question // self.view.addSubview(tableView) // tableView.frame = self.view.bounds // tableView.autoresizingMask = [.flexibleWidth, .flexibleHeight] tableView.translatesAutoresizingMaskIntoConstraints = false view.addSubview(tableView) NSLayoutConstraint.activate([ // tableView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor), // tableView.leftAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leftAnchor), // tableView.rightAnchor.constraint(equalTo: view.safeAreaLayoutGuide.rightAnchor), // tableView.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor) tableView.topAnchor.constraint(equalTo: view.topAnchor), tableView.leftAnchor.constraint(equalTo: view.leftAnchor), tableView.rightAnchor.constraint(equalTo: view.rightAnchor), tableView.bottomAnchor.constraint(equalTo: view.bottomAnchor) ]) tableView.delegate = self tableView.dataSource = self tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell") tableView.separatorStyle = .none tableView.contentInsetAdjustmentBehavior = .scrollableAxes } } struct DemoPage : UIViewControllerRepresentable { func makeUIViewController(context: Context) -> some UIViewController { return DemoTableView() } func updateUIViewController(_ uiViewController: UIViewControllerType, context: Context) { } } #Preview { DemoPage().ignoresSafeArea() } ``` I would like to ask if this is a bug in iOS's bridging between uikit and swiftui. Currently, my project uses swiftui to draw each cell, but uitableview is needed to accurately control the scrolling state (swiftui is very troublesome to deal with). In addition, I need to support iOS15, so I cannot use UIHostingConfiguration. Is it a reliable and mature solution to use uitableviewcell to nest uihostingcontroller?
The content of uihostview has a weird offset when it is placed in each uitableviewcell
|ios|uitableview|uikit|uihostingcontroller|
i want to control two drop down lists to tell which macro to be run automatically
|excel|vba|macros|
null
In my angular app there can be 2 type of layout(e.g. List and Detail). I have to get the layoutConfig based on activated route. For this I'm using a route resolver. My plan is ResolveFn will return a signal not an observable. My *LayoutService* has an additional requirement, if its a List, it will get list data from layoutConfig's serviceUrl. Below is my existing code which pass url as parameter and return an observable: ``` export const LayoutResolver: ResolveFn<LayoutConfig> = ( route: ActivatedRouteSnapshot, state: RouterStateSnapshot, ) => { const _layoutService = inject(LayoutService); _layoutService.setCurrentActivatedRoute(state.url); return _layoutService.layoutConfig$; }; ``` ``` export class LayoutService { #httpClient = inject(ApiHttpService); readonly #url_layout: string = 'listConfig'; constructor() { effect(() => { console.log('currentActivatedRoute', this.CurrentActivatedRouteSig()); }); } CurrentActivatedRouteSig = signal<string | undefined>(undefined); setCurrentActivatedRoute(url: string) { this.CurrentActivatedRouteSig.set(url); } currentActivatedRoute$ = toObservable(this.CurrentActivatedRouteSig); layoutConfig$ = this.currentActivatedRoute$ .pipe( filter(Boolean), switchMap(x => this.#httpClient.GETT<LayoutConfig>(`${this.#url_layout}`) .pipe( map(x => x.data) )) ); LayoutConfigSig = toSignal(this.layoutConfig$, { initialValue: undefined }); private gridData$ = toObservable(this.LayoutConfigSig) .pipe( tap(x => console.log('gridData$ =>', x)), filter(Boolean), switchMap(x => this.#httpClient.GETT<any>(x.serviceUrl) .pipe( tap(x => console.log('serviceUrl$ =>', x.data)), map(x => x.data) )) ) GridDataSig = toSignal(this.gridData$, { initialValue: [] }); } ``` I'm expecting *LayoutConfigSig* and *GridDataSig(if List)* in my component as Signal. Also, I'm unsure whether *CurrentActivatedRoute* in my service class should be signal or a Subject?
I am accessing SQL Server using a Docker container, and have done using this step: 1. `docker run -e "ACCEPT_EULA=Y" -e "SA_PASSWORD=Password@123" -e "MSSQL_PID=Express" -p 1433:1433 -v mssqlserver_volume:/var/opt/mssql --name mssql -d mcr.microsoft.com/mssql/server:2019-CU15-ubuntu-20.04` (I use this code in cmd to create a container) 2. Continue command docker ps 3. The container able to created but the status only showed running for 1 seconds, then keep exited. The logs keeps shows this when I try to run the container: > sqlservr: This program requires a machine with at least 2000 megabytes of memory. /opt/mssql/bin/sqlservr: This program requires a machine with at least 2000 megabytes of memory. Now I not able to proceed with command this code docker exec -it mssql /opt/mssql-tools/bin/sqlcmd -S localhost -U sa -P Password@123 since the container keeps showing "exited". The methods have I tried is to restart and also swapping memory from wsl1 to wsl2 but it didn't solve my problem Kindly need assistance to solve this problem. [Logs for SQL Server container](https://i.stack.imgur.com/UBHPn.png) [The command](https://i.stack.imgur.com/EtXje.png)
Generic way for traversing a C++ std::tuple
|c++|template-meta-programming|c++-concepts|
I have a list of field name in a database table (my actual list is 15+ in length and can vary) ``` flds = ["foo", "bar", "foobar"] ``` I also have field name in a function that correspond to those values ``` foo = "red" bar = "" foobar = "green" ``` I have code be low that is the same for each variable ``` sql = "UPDATE table SET a = 1 " if foo == "": sql = sql + ", foo = NULL" elif foo is not None: sql = sql + ",foo = " + foo if bar == "": sql = sql + ", bar = NULL" elif foo is not None: sql = sql + ",bar= " + bar*** if foobar == "": sql = sql + ", foobar = NULL" elif foo is not None: sql = sql + ",foobar= " + foobar ``` The code is the exact same for each variable in the list and I don't want to have to write this segment of code for each variable every time the list changes; I want a way to create it dynamically based on the current values in the list. I have tried using the exec() command ``` for fld in flds: tmp_fld = f"{fld}" # the actual value now of tmp_fld is "foo" exec(f"tmp_fld_val = {tmp_fld}") # I want the value of tmp_fld_val to be "red" but no joy here if tmp_fld_val == "": sql = f"{sql} ,{tmp_fld} = NULL" elif tmp_fld_val is not None: sql = f"{sql} ,{tmp_fld} = '{tmp_fld_val}'" ```
I don't think that this is possible. After some research online, I ended up at Vlad Mihalcea's article on [emulating JPA auditing using Hibernate generator utility](https://vladmihalcea.com/how-to-emulate-createdby-and-lastmodifiedby-from-spring-data-using-the-generatortype-hibernate-annotation/). It's easy to implement with high degree of customization. P.S. there are a lot of changes on the library which deprecates some of its annotations, including `@GeneratorType` used in the Vlad Mihalcea's article. I'm suggesting reading the Javadoc of the interfaces.
I have a table called `Nodes` consisting of base doc, current doc, and target doc: ``` BaseDocType . BaseDocID DocType . DocID TargetDocType . TargetDocID .. ``` I want to fetch all the related nodes for any specific node. This is what I have so far: ``` WITH CTE1 (ID, BaseDocType, BaseDocID, DocType, DocID, TargetDocType, TargetDocID) AS ( SELECT ID, BaseDocType, BaseDocID, DocType, DocID, TargetDocType, TargetDocID FROM Doc.Nodes WHERE DocType = 8 AND DocID = 2 UNION ALL SELECT a.ID, a.BaseDocType, a.BaseDocID, a.DocType, a.DocID, a.TargetDocType, a.TargetDocID FROM Doc.Nodes a INNER JOIN CTE1 b ON (a.BaseDocType = a.BaseDocType AND a.BaseDocID = b.BaseDocID AND a.DocType != b.DocType AND a.DocID != b.DocID) ) SELECT * FROM CTE1 ``` But the query is not working. I get this error: > Msg 530, Level 16, State 1, Line 8 > The statement terminated. The maximum recursion 100 has been exhausted before statement completion. ![Example][1] How can I fix this? [1]: https://i.stack.imgur.com/t3q8u.jpg
SQL Server recursive query in a CTE issue
null
When talking of filter length in a gaussian filter, you must explicit "how much" sigma is your filter length. Filter length and sigma are not the same. For instance, you may implement a gaussian filter with a window length of 360 and say that this window length correspond to 6-sigma. This is an approximation to 99.7% (see https://en.wikipedia.org/wiki/Probability_theory) So in conclusion, if you want a window length of 360, you should use the sigma value of 60 in the scipy.ndimage.gaussian_filter1d function. This is the common 6-sigma implementation.
|c++|
The solution atm is to remove package from GitHub profile.
By default, Flutter itself gives some text styling to all elements that you use in UI. You can override them by just adding some more lines in your ThemeData() class in your main.dart. For example: ThemeData( appBarTheme: AppBarTheme( titleTextStyle: TextStyle(fontSize: 20), ), // .... ) Now all texts in any scaffolds appbar title will get size 20, unless you change it directly in Text("", style: TextStyle(fontSize: 15)) itself. Hope i got you correct and helped.
import Peer from "peerjs"; import { FunctionComponent, ReactNode, createContext, useEffect, useReducer, useState, } from "react"; import { useNavigate } from "react-router-dom"; import socketIO from "socket.io-client"; import { v4 as uuidV4 } from "uuid"; import { peersReducer } from "../../Actions/peerReducer"; import { addPeerAction, removePeerAction } from "../../Actions/peerActions"; export const RoomContext = createContext<null | any>(null); const WS = process.env.REACT_APP_SERVER_URL as string; const ws = socketIO(WS); interface RoomProviderProps { children: ReactNode; } export const RoomProvider: FunctionComponent<RoomProviderProps> = ({ children, }) => { const navigate = useNavigate(); const [me, setMe] = useState<Peer>(); const [stream, setStream] = useState<MediaStream | null>(null); const [peers, dispatch] = useReducer(peersReducer, {}); const [screenSharingId, setScreenSharingId] = useState(""); // const [peerConnections, setPeerConnections] = useState<DataConnection | null>( // null // ); const getUsers = ({ participants }: { participants: string[] }) => { console.log("participants", participants); }; const enterRoom = ({ roomId }: { roomId: string }) => { console.log(roomId); navigate(`/room/${roomId}`); }; const removePeer = (peerId: string) => { dispatch(removePeerAction(peerId)); }; function switchSharing(stream: MediaStream) { setStream(stream); setScreenSharingId(me?.id || ""); } useEffect(() => { // user id const meId = uuidV4(); const peer = new Peer(meId); setMe(peer); function videoPlayerHandler() { try { navigator.mediaDevices .getUserMedia({ video: true, audio: true }) .then((s) => setStream(s)); } catch (error) { console.error(error); } } videoPlayerHandler(); ws.on("room-created", enterRoom); ws.on("get-users", getUsers); ws.on("user-disconnected", removePeer); }, []); useEffect(() => { if (!me) return; if (!stream) return; ws.on("user-joined", ({ peerId }) => { const call = me.call(peerId, stream); call.on("stream", (peerStream) => { dispatch(addPeerAction(peerId, peerStream)); }); }); me.on("call", (call) => { call.answer(stream); call.on("stream", (peerStream) => { dispatch(addPeerAction(call.peer, peerStream)); }); }); }, [me, stream]); // console.log(peers); function shareScreen() { if (screenSharingId) { navigator.mediaDevices .getUserMedia({ video: true, audio: true }) .then(switchSharing) .catch((err) => console.log("Failed to play video", err)); } else { navigator.mediaDevices .getDisplayMedia({ video: true, audio: true }) .then(switchSharing) .catch((err) => console.log("Failed to share screen", err)); } Object.values(me?.connections).forEach((connection: any) => { const videoTrack = stream ?.getTracks() .find((track) => track.kind === "video"); connection[0].peerConnections .getSenders()[1] .replaceTrack(videoTrack) .catch((err: any) => console.log(err)); }); } return ( <RoomContext.Provider value={{ ws, me, stream, peers, shareScreen }}> {children} </RoomContext.Provider> ); }; I'm having trouble with screen sharing. It works when I share my screen, but the person on the other end can't see it. I tried using me?.connections, but it's outdated. I learned about an alternative approach: const peer = new MyPeer(); const connection = await peer.connect(); myConnectionsArray.push(connection); However, when I used this, it asked for arguments in peer.connect(). I'm unsure which arguments to pass. I want the screen sharing to work for both the person sharing the screen and the one receiving it. Can you assist me in fixing this issue?