text
stringlengths
15
59.8k
meta
dict
Q: How to show all rows in a GROUP BY statement? How do I get all the rows being shown in a GROUP BY statement ? Here is the query : SELECT year(feed_date) as date_year, month(feed_date) as date_month, count(*) as nb_item FROM table WHERE year(feed_date) = '2015' AND feed_title LIKE '%word%' AND source = '3' GROUP BY date_year, date_month Here is the output : ----------------- | 2015 | 7 | 5 | | 2015 | 9 | 2 | | 2015 | 10 | 4 | | 2015 | 11 | 2 | ----------------- Here is the desired output : ----------------- | 2015 | 1 | 0 | | 2015 | 2 | 0 | | 2015 | 3 | 0 | | 2015 | 4 | 0 | | 2015 | 5 | 0 | | 2015 | 6 | 0 | | 2015 | 7 | 5 | | 2015 | 8 | 0 | | 2015 | 9 | 2 | | 2015 | 10 | 4 | | 2015 | 11 | 2 | | 2015 | 12 | 0 | ----------------- A: by tag mysqli I can assume that You're using PHP. So it can be done this way: $year = '2015'; $data = []; foreach(range(1, 12) AS $month) { $data[$month] = [ 'date_year' => $year, 'date_month' => $month, 'nb_item' => 0 ]; } $q = "SELECT year(feed_date) as date_year, month(feed_date) as date_month, count(*) as nb_item FROM table WHERE year(feed_date) = '".$year."' GROUP BY date_year, date_month"; $q = mysqli_query($q); while($record = mysqli_fetch_assoc($q)) { $data[$record['date_month']]['nb_item'] = $record['nb_item']; } $data = array_values($data); print_r($data); or with mysql it will be huge query: SELECT year(table.feed_date) AS date_year, month(table.feed_date) AS date_month, COALESCE(count(*), 0) as nb_item FROM ( SELECT 1 as month UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 4 UNION ALL SELECT 5 UNION ALL SELECT 6 UNION ALL SELECT 7 UNION ALL SELECT 8 UNION ALL SELECT 9 UNION ALL SELECT 10 UNION ALL SELECT 11 UNION ALL SELECT 12 ) months LEFT JOIN table ON (months.month = month(table.feed_date)) WHERE year(table.feed_date) = '2015' GROUP BY date_year, date_month; A: You need a table containing all the year-month combinations for a LEFT JOIN. You can create it on the fly by cross joining all years and months: SELECT y.date_year, m.date_month, count(*) as nb_item FROM ( SELECT 1 as date_month UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 4 UNION ALL SELECT 5 UNION ALL SELECT 6 UNION ALL SELECT 7 UNION ALL SELECT 8 UNION ALL SELECT 9 UNION ALL SELECT 10 UNION ALL SELECT 11 UNION ALL SELECT 12 ) m CROSS JOIN ( SELECT 2015 as date_year ) y LEFT JOIN `table` t ON year(t.feed_date) = y.date_year AND month(t.feed_date) = m.date_month AND t.feed_title LIKE '%word%' AND t.source = '3' GROUP BY y.date_year, m.date_month If you have a helper table with sequence numbers you can shorten the query to: SELECT y.seq as date_year, m.seq as date_month, count(*) as nb_item FROM sequences y CROSS JOIN sequences m LEFT JOIN `table` t ON year(t.feed_date) = y.date_year AND month(t.feed_date) = m.date_month AND t.feed_title LIKE '%word%' AND t.source = '3' WHERE y.seq IN (2015) AND m.seq <= 12 GROUP BY y.seq, m.seq A: You can join the selected data with a subquery that gets all the existing years and months from the table. SELECT t1.date_year, t1.date_monthmonth, IFNULL(t2.nb_item, 0) AS nb_item FROM (SELECT DISTINCT YEAR(feed_date) AS date_year, MONTH(feed_date) AS date_month FROM table) AS t1 LEFT JOIN ( SELECT year(feed_date) as date_year, month(feed_date) as date_month, count(*) as nb_item FROM table WHERE year(feed_date) = '2015' AND feed_title LIKE '%word%' AND source = '3' GROUP BY date_year, date_month) AS t2 ON t1.date_year = t2.date_year AND t1.date_month = t2.date_month ORDER BY t1.date_year, t1.date_month
{ "language": "en", "url": "https://stackoverflow.com/questions/39966861", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to add pagination to Bootstrap grid html page getting data from pandas dataframe? I have a web page which includes Crispy Filter and "table" created in Bootstrap grid by iteration from Pandas DataFrame. Is there some way how to add pagination to this Pandas DataFrame presented in Bootstrap Grid?
{ "language": "en", "url": "https://stackoverflow.com/questions/74945451", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How many HTTPS certificates have the google reCaptcha endpoint? And where can I download them? We have a Java web application that implements reCaptcha validation against URL https://www.google.com/recaptcha/api/siteverify in a microservice in Docker. This has been working for almost 2 years, but this Tuesday 8/06/2021, the app started throwing this exception: Caused by: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target at java.base/sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:439) at java.base/sun.security.validator.PKIXValidator.engineValidate(PKIXValidator.java:306) at java.base/sun.security.validator.Validator.validate(Validator.java:264) at java.base/sun.security.ssl.X509TrustManagerImpl.validate(X509TrustManagerImpl.java:313) at java.base/sun.security.ssl.X509TrustManagerImpl.checkTrusted(X509TrustManagerImpl.java:222) at java.base/sun.security.ssl.X509TrustManagerImpl.checkServerTrusted(X509TrustManagerImpl.java:129) at java.base/sun.security.ssl.CertificateMessage$T13CertificateConsumer.checkServerCerts(CertificateMessage.java:1340) ... 89 common frames omitted Caused by: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target at java.base/sun.security.provider.certpath.SunCertPathBuilder.build(SunCertPathBuilder.java:141) at java.base/sun.security.provider.certpath.SunCertPathBuilder.engineBuild(SunCertPathBuilder.java:126) at java.base/java.security.cert.CertPathBuilder.build(CertPathBuilder.java:297) at java.base/sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:434) ... 95 common frames omitted We find that the certificate that we have in Java 11 was one of GlobalSign but with name ending in "R2": Certificate R2 in truststore However, in some cases the same Google endpoint returns one with name ending in "R1": Certificate R1 not in Truststore After we add this certificate R1, the app started to work fine, but is it normal that the same endpoint returns two different certificates? And how can I obtain or add all the possible certificates in my truststore? Is there a pool of certificates that we need to add? A: Not an answer (yet?) to the real problem, only to "is it normal", but also much too long for comments. It is possible for one SSL/TLS server to have more than one certificate, and provide different ones on connection requests, although it would be odd to so for the same domainname; this is more common on servers that support multiple domains -- either for different parts or services of one entity, or a CDN or frontend like Cloudflare or Fastly(!) that handles connections for multiple entities. However, in the specific case of www.google.com that is not a single server but hundreds or thousands, all over the world, and it is quite possible that different servers have different certificates, either intentionally (perhaps for testing) or because they are making a change which does not happen instantly everywhere. According to my notes recently www.google.com as accessed from my location was using certs under GTS CA 1O1 with this intermediate cert under GlobalSign Root CA - R2 as shown in your first image. Note that intermediate cert expires in 6 months, as does the root it is under, which is a good reason to stop using it. (https://crt.sh/?caid=10 does show two 'cross' certs for R2 under GlobalSign Root CA (see below) with longer expiration, but they are both revoked.) As of today I get a cert under GTS CA 1C3 under GTS Root R1 -- so far like your second figure -- but then crossed under GlobalSign Root CA WITHOUT R1. Specifically I get this intermediate cert for GTS CA 1C3 and this cross cert for GTS Root R1, which are valid until 2027 and 2028 and appear here on the GTS website as GTS CA 1C3 and GTS Root R1 Cross respectively. And this cert for that GlobalSign root -- which in effect is R1, since the other currently known GlobalSign roots are R2-6, but is not named R1 -- has been in at least Java and Mozilla/Firefox truststores for long time; I can't easily check history on others. crt.sh doesn't know of ANY cert named with R1. I'd note that Firefox does have in its truststore a root cert for GTS Root R1 (and also R2-R4) which means it could shorten the chain, but doesn't; AFAICS no Java has any of these GTS roots. Moreover the leaf certs I get have both CommonName and SubjectAltName www.google.com NOT *.google.com. This pretty much confirms you are getting a different server than I am. It might help if you can extract the "GlobalSign R1" cert you apparently have in some truststore, and post it to be looked at or searched for, and the rest of the chain which you can get with keytool -printcert -rfc -sslserver www.google.com and/or if you can identify which google address(es?) you are getting this cert chain from so others (like me) can try it -- although even one address might anycast to multiple physical servers. A: You can refer to Google's PKI Repository which lists 5 CAs. As per the FAQ, they actually list 36 different CAs in the roots.pem file (as of 28th April, 2022). Ideally you will need to add all those CAs to your trust store to cover all bases.
{ "language": "en", "url": "https://stackoverflow.com/questions/67992893", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to convert a png to a csv file in Java I have built a neural network that recognizes handwritten digits in java. After training the network using the mnist dataset of handwritten digits (in csv format) I have a method which querys the network for a csv file and outputs the result. I have made some custom images in microsoft paint that are saved as png files. How can I convert them to csv format. The images are 28x28 pixels in size. Each value in the csv file represents the grey scale value for the pixel, so there are a total of 784 values in each file. Here is an example csv file that evaluates as a 7 (the entire file is one line): 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,84,185,159,151,60,36,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,222,254,254,254,254,241,198,198,198,198,198,198,198,198,170,52,0,0,0,0,0,0,0,0,0,0,0,0,67,114,72,114,163,227,254,225,254,254,254,250,229,254,254,140,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,17,66,14,67,67,67,59,21,236,254,106,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,83,253,209,18,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,22,233,255,83,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,129,254,238,44,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,59,249,254,62,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,133,254,187,5,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,9,205,248,58,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,126,254,182,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,75,251,240,57,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,19,221,254,166,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,3,203,254,219,35,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,38,254,254,77,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,31,224,254,115,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,133,254,254,52,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,61,242,254,254,52,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,121,254,254,219,40,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,121,254,207,18,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 Please ask if you require any additional information. Any information helps Thanks :)
{ "language": "en", "url": "https://stackoverflow.com/questions/48102125", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How can I add large files to a Git repo? I have a Microsoft Azure / Visual studio online repo managed with Git. I am using the Git GUI application to manage it. I have a couple of files that are 535 MB and 620 MB in size. I would like to add these to the repo. I have enabled Git large file support, and i have set the global post buffer with the command: git config --global http.postBuffer 1048576000 No matter what I do, I cannot seem to add these files. The commit is fine, but when I push to the remote branch, I get: POST git-receive-pack (547584390 bytes) error: RPC failed; HTTP 503 curl 22 The requested URL returned error: 503 fatal: the remote end hung up unexpectedly fatal: the remote end hung up unexpectedly Everything up-to-date As far as I know, adjusting the buffer like this should work in this case. What am I missing? A: Activating LFS locally (git-lfs.github.com as you mention) is a good first step. Check also the prerequisites and limitations at Azure DevOps Azure Repos / Use Git Large File Storage (LFS) Finally, if you just added/committed the large file, it is better to reset that commit (assuming you don't have any other work in progress), and then track it through lfs: git reset @~ git lfs track lyLargeFile git A: After fighting with git for weeks, I have finally solved this. the answer for me was to clone the repo again using SSH instead of HTTP.
{ "language": "en", "url": "https://stackoverflow.com/questions/61715357", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Flatten json string in BigQuery I have a custom Airbyte job that fails to normalize the data, so I need to do it manually. The following data is pulled from our HR system: { "title": "My Report", "fields": [{ "id": "employeeNumber", "name": "Employee #" }, { "id": "firstName" "name": "First Name" }, { "id": "lastName" "name": "Last Name" }], "employees": [{ "employeeNumber": "1234", "firstName": "Ann", "lastName": "Perkins" }, { "employeeNumber": "5678", "firstName": "Bob", "lastName": "Builder" }] } My current bigquery table looks like this (the json is stored as a string): _airbyte_ab_id _airbyte_emitted_at _airbyte_data 123abc 2022-01-30 19:41:59 UTC {"title": "My Datawareouse", "fields": [ {"id": "employeeNumber", "name": "Employee_Number"}, {"id": "firstName", "name": "First_Name" }, { "id": "lastName", "name": "Last_Name"} ], "employees": [ { "employeeNumber": "1234", "firstName": "Ann", "lastName": "Perkins" }, { "employeeNumber": "5678", "firstName": "Bob", "lastName": "Builder" } ] } I am trying to normalize the table to look like this: _airbyte_ab_id _airbyte_emitted_at Employee_Number First_Name Last_Name 123abc 2022-01-30 19:41:59 UTC 1234 Ann Perkins 123abc 2022-01-30 19:41:59 UTC 5678 Bob Builder How to flatten the json into columns as the example above, using SQL in bigquery? (The script will be running from dbt, but for now, I am just trying to get a valid query to run) I should add that the actual json has far more fields, they might change, and I expect null values for things like "Middle Name" and the like. So, in a perfect world, I would not have to define each column name, but have it run dynamically by reading the "Fields" array. A: How to flatten the json into columns as the example above, using SQL in bigquery? Consider below approach select _airbyte_ab_id, _airbyte_emitted_at, json_value(employee, '$.employeeNumber') employeeNumber, json_value(employee, '$.firstName') firstName, json_value(employee, '$.lastName') lastName from your_table, unnest(json_extract_array(_airbyte_data, '$.employees')) employee if applied to sample data in your question - output is A: ... in a perfect world, I would not have to define each column name, but have it run dynamically by reading the "Fields" array For case when your have fields defined dynamically and potentially even different from row to row - i recommend considering below flattening approach select _airbyte_ab_id, _airbyte_emitted_at, md5(employee) employee_hash, json_value(field, "$.id") key, regexp_extract(employee, r'"' || json_value(field, "$.id") || '":"(.*?)"') value from your_table, unnest(json_extract_array(_airbyte_data, '$.employees')) employee, unnest(json_extract_array(_airbyte_data, '$.fields')) field if applied to sample data in your question - output is
{ "language": "en", "url": "https://stackoverflow.com/questions/70918897", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Visual Studio 2017 cannot find typescript compiler? I am trying to build an application in Visual Studio that uses typescript. I followed the directions here and installed the typescript compiler for the version the project requires (2.2). I did it with NPM npm install typescript I verified my installation by tsc --version and it returned Version 2.2.2 which is expected. However, when I go to build my solution I keep getting the following error: Your project specifies TypeScriptToolsVersion 2.2, but a matching compiler was not found. The latest available TypeScript compiler will be used (2.3). To remove this warning, install the TypeScript 2.2 SDK or update the value of TypeScriptToolsVersion. I have tried Google-ing and haven't had any luck. Can someone point me down the road to a solution? A: Are you on an older version of Visual Studio 2017? Make sure you are on version 15.3. 15.2 includes TypeScript 2.2, but 15.3 also allows different versions of TypeScript to be selected per project. Once you have updated, you should be able to go to Properties/TypeScript Build for your project and ensure 2.2 is selected. For future TypeScript updates you can install the TypeScript SDK for Visual Studio 2017. Check https://github.com/Microsoft/TypeScript/wiki/Updating-TypeScript-in-Visual-Studio-2017 for details. (The instructions you referred to are for Visual Studio Code.)
{ "language": "en", "url": "https://stackoverflow.com/questions/46223217", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: how do i stop ios from automatically adding cookie to my NSMutableURLRequest i am hitting a url with the following code: NSData *responseData = [NSURLConnection sendSynchronousRequest:theRequestHttp returningResponse:&theResponse error:&theError]; and i have theRequestHttp initialized here: NSMutableURLRequest *theRequestHttp = [[NSMutableURLRequest alloc] initWithURL:url]; no where do i have the cookie being added to the urlrequest... in fact, i have the following set: [theRequestHttp addValue:nil forHTTPHeaderField:@"Cookie"]; i also tried with [theRequestHttp setValue:nil forHTTPHeaderField:@"Cookie"]; is there any way to NOT add the Cookie? A: [request setHTTPShouldHandleCookies:NO]; A: I don't know if you can disable automatic addition of cookies but you can delete cookies anytime you want using the following code NSHTTPCookieStorage *storage = [NSHTTPCookieStorage sharedHTTPCookieStorage]; for (NSHTTPCookie *cookie in storage.cookies) { [storage deleteCookie:cookie]; } A: Here you go, this is a method to do this, this method sets a cookie after implementing your own cookie info, and the category below this method powers this method, this will work by sniping the EXSISTING cookie right after you make the cookie methos above and then you mutate the cookie to whatever data you want, you will still have a cookie, but it won't be useful unless you are replacing the cookie info with real info. You can just immediatley look through the array of cookies and delete them. Either way, you can make cookies NOT work and get rid of them: - (void)manipulateCookie { NSArray* cookies = [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookies]; for (NSHTTPCookie* cookie in cookies) { NSString *alipaySetCookieString = @"CAKEPHP=nil; path=#; domain=#; expires=Wed, 30-Nov-2001 01:01:01 GMT"; NSHTTPCookie * clok = [alipaySetCookieString cookie]; [[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookie:clok]; } } category: NSString+Cookie.h @interface NSString(Cookie) - (NSHTTPCookie *)cookie; @end NSString+Cookie.m #import "NSString+Cookie.h" @implementation NSString(Cookie) - (NSDictionary *)cookieMap { NSMutableDictionary *cookieMap = [NSMutableDictionary dictionary]; NSArray *cookieKeyValueStrings = [self componentsSeparatedByString:@";"]; for (NSString *cookieKeyValueString in cookieKeyValueStrings) { NSRange separatorRange = [cookieKeyValueString rangeOfString:@"="]; if (separatorRange.location != NSNotFound && separatorRange.location > 0 && separatorRange.location < ([cookieKeyValueString length] - 1)) { NSRange keyRange = NSMakeRange(0, separatorRange.location); NSString *key = [cookieKeyValueString substringWithRange:keyRange]; NSString *value = [cookieKeyValueString substringFromIndex:separatorRange.location + separatorRange.length]; key = [key stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]; value = [value stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]; [cookieMap setObject:value forKey:key]; } } return cookieMap; } - (NSDictionary *)cookieProperties { NSDictionary *cookieMap = [self cookieMap]; NSMutableDictionary *cookieProperties = [NSMutableDictionary dictionary]; for (NSString *key in [cookieMap allKeys]) { NSString *value = [cookieMap objectForKey:key]; NSString *uppercaseKey = [key uppercaseString]; if ([uppercaseKey isEqualToString:@"DOMAIN"]) { if (![value hasPrefix:@"."] && ![value hasPrefix:@"www"]) { value = [NSString stringWithFormat:@".%@",value]; } [cookieProperties setObject:value forKey:NSHTTPCookieDomain]; }else if ([uppercaseKey isEqualToString:@"VERSION"]) { [cookieProperties setObject:value forKey:NSHTTPCookieVersion]; }else if ([uppercaseKey isEqualToString:@"MAX-AGE"]||[uppercaseKey isEqualToString:@"MAXAGE"]) { [cookieProperties setObject:value forKey:NSHTTPCookieMaximumAge]; }else if ([uppercaseKey isEqualToString:@"PATH"]) { [cookieProperties setObject:value forKey:NSHTTPCookiePath]; }else if([uppercaseKey isEqualToString:@"ORIGINURL"]){ [cookieProperties setObject:value forKey:NSHTTPCookieOriginURL]; }else if([uppercaseKey isEqualToString:@"PORT"]){ [cookieProperties setObject:value forKey:NSHTTPCookiePort]; }else if([uppercaseKey isEqualToString:@"SECURE"]||[uppercaseKey isEqualToString:@"ISSECURE"]){ [cookieProperties setObject:value forKey:NSHTTPCookieSecure]; }else if([uppercaseKey isEqualToString:@"COMMENT"]){ [cookieProperties setObject:value forKey:NSHTTPCookieComment]; }else if([uppercaseKey isEqualToString:@"COMMENTURL"]){ [cookieProperties setObject:value forKey:NSHTTPCookieCommentURL]; }else if([uppercaseKey isEqualToString:@"EXPIRES"]){ NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; [dateFormatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_US"]]; dateFormatter.dateFormat = @"EEE, dd-MMM-yyyy HH:mm:ss zzz"; [cookieProperties setObject:[dateFormatter dateFromString:value] forKey:NSHTTPCookieExpires]; }else if([uppercaseKey isEqualToString:@"DISCART"]){ [cookieProperties setObject:value forKey:NSHTTPCookieDiscard]; }else if([uppercaseKey isEqualToString:@"NAME"]){ [cookieProperties setObject:value forKey:NSHTTPCookieName]; }else if([uppercaseKey isEqualToString:@"VALUE"]){ [cookieProperties setObject:value forKey:NSHTTPCookieValue]; }else{ [cookieProperties setObject:key forKey:NSHTTPCookieName]; [cookieProperties setObject:value forKey:NSHTTPCookieValue]; } } if (![cookieProperties objectForKey:NSHTTPCookiePath]) { [cookieProperties setObject:@"/" forKey:NSHTTPCookiePath]; } return cookieProperties; } - (NSHTTPCookie *)cookie { NSDictionary *cookieProperties = [self cookieProperties]; NSHTTPCookie *cookie = [NSHTTPCookie cookieWithProperties:cookieProperties]; return cookie; } @end
{ "language": "en", "url": "https://stackoverflow.com/questions/32276620", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: POST jersey with HeaderParam annotation I get null when I send a POST. Please someone know how to pass value with Angular using @HeaderParam in Jersey? I have this in backend: @POST @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public Users loginUser(@HeaderParam("username")String username,@HeaderParam("password") String password){ System.out.println("What happen"+userService.loginService(username, password)); return userService.loginService(username, password); } and this in front-end, using Angular: $scope.getUserFunction = function () { $http({ method : 'POST', url : 'http://localhost:8080/JersyBackEnd/resources/login'+data, contentType:'application/json', data : {username: "akram",password:"yes"}, }) .then(function(data) { console.log(data); }); }; I get 204 because of the null data. Can anyone help me, either using HeaderParam, PathParam or FormParm annotations in Jersey? A: data is sent as the request body. What you really want is headers. From the docs: * *data – {string|Object} – Data to be sent as the request message data. *headers – {Object} – Map of strings or functions which return strings representing HTTP headers to send to the server. If the return value of a function is null, the header will not be sent. Functions accept a config object as an argument. Example: $http({ ... headers: { username: "akram", password: "yes" } }) A: When you use @HeaderParam, you have to pass the values from .JS using headers: { 'something': 'anything' }. As i can see currently you are using data : {username: "akram",password:"yes"}. try to use headers: { 'something': 'anything' } instead of this. Please try header, hope it will solve your null issue.
{ "language": "en", "url": "https://stackoverflow.com/questions/35431536", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Dynamic memory allocation code explanation Being a beginner C/C++ programmer, I am having to spend several hours, trying to decipher the code below: Could someone walk me (step me through the code below for dynamic memory allocation) line by line. char **alloc_2d_char(const int rows, const int cols) { char *data = (char *)malloc(rows*cols*sizeof(char)); char **array= (char **)malloc(rows*sizeof(char*)); for (int i=0; i<rows; i++) array[i] = &(data[cols*i]); return array; } Pointer to Pointers is explained separately than from Pointers to Arrays. I have been able to get parts of the information from various sources, but none that stitches the lines cohesively. A: The code is using a single contiguous block of memory to hold a 2-D array. char *data = (char *)malloc(rows*cols*sizeof(char)); Ok -- this line is allocating space for the entire 2-D array. The 2-D array is rows rows by cols columns. So the total number of elements is rows * cols. Then you have to multiply that by the amount of space each element takes up, which is sizeof(char) since this is a 2-D array of char. Thus the total amount of memory to be allocated is rows * cols * sizeof(char) which is indeed the argument to malloc. The malloc call returns a pointer to the allocated memory. Since this memory will be used to hold char, you cast the return value to char *. char **array= (char **)malloc(rows*sizeof(char*)); array is being declared as type "pointer to pointer to char" because that's what it's going to do. It'll point to memory that will hold pointers to char. It will be one pointer for each row. So you have to allocate rows * sizeof(char *) memory: the number of pointers times the size of a pointer of the right type. And since this was allocated to point to pointers to char, we cast the return value to char **. for (int i=0; i<rows; i++) array[i] = &(data[cols*i]); This is the magic :). This sets each pointer in array to point to within the block of actual data allocated earlier. Consider a concrete example where rows is 2 and cols is 3. Then you have the block of 6 characters in memory: [0][1][2][3][4][5] And data[n] (for n from 0 to 5) is the n-th element and &data[n] is the *address of the n-th element. So what that loop does in this case is do: array[0] = &data[0]; array[1] = &data[3]; So array[0] points to the sub-block starting at [0] and array[1] points to the sub-block starting at [3]. Then when you add the second subscript you're indexing from the start of that pointer. So array[0][2] means "get the pointer stored in array[0]. Find what it points to, then move ahead 2 elements from there.: array[0] points to [0][1][2] (well, actually points to [0]). Then you move two elements ahead and get [2]. Or if you start with array[1][1], array[1] points to [3][4][5] (and actually points at [3]. Move one element ahead and get [4]. A: The first malloc is getting memory for the 2D character array. The second malloc is getting memory for rows index. The for loop is setting the pointer to each row. Finally the row index is returned. A: You can think of the 2-D array that it is creating as an array of single-dimensional arrays. Each row entry points to an array of char that represents the column data for that row. The following is the original code with comments added to attempt to describe each step: char **alloc_2d_char(const int rows, const int cols) { // This allocates the chunk of memory that stores that actual data. // It is a one single-dimensional array that has rows*cols characters. char *data = (char *)malloc(rows*cols*sizeof(char)); // This allocates an array of pointers that will then be assigned to the // individual rows (carved out of the previous allocation). char **array= (char **)malloc(rows*sizeof(char*)); // This assigns each row to the appropriate position in the data array. // The &(data[cols*i]) bit of it is the address of a portion in the // memory pointed to by data. The cols*i is the offset to the portion that // represents row i. for (int i=0; i<rows; i++) array[i] = &(data[cols*i]); // After doing this, then you can assign a value such as: // array[r][c] = 'x'; // That statement would store 'x' into data[r*c + c] return array; } A: Is not hard to decipher... char *data = (char *)malloc(rows*cols*sizeof(char)); simple memory allocation char **array= (char **)malloc(rows*sizeof(char*)); memory allocation of #row char pointers array[i] = &(data[cols*i]); every array[i] is a pointer, a pointer to data[cols*i] A: Each * in a declaration refers to one level of pointer indirection. so int ** means a pointer to a pointer to an int. So your function: char **alloc_2d_char(const int rows, const int cols) { returns a pointer to a pointer to a char. char *data = (char *)malloc(rows*cols*sizeof(char)); This declares a pointer to a char. The pointer is called data. The initialization calls malloc, which allocates a number of bytes equal to the value of the argument. This means there are rows*cols*sizeof(char) bytes, which will be equal to rows*cols, since a char is 1 byte. The malloc function returns the pointer to the new memory, which means that data now points to a chunk of memory that's rows*cols big. The (char *) before the call to malloc just casts the new memory to the same type as the pointer data. char **array= (char **)malloc(rows*sizeof(char*)); array is a pointer to a pointer to a char. It is also being assigned using malloc. The amount of memory being allocated this time is rows*sizeof(char), which is equal to rows. This means that array is a pointer to a pointer to a chunk of memory big enough to hold 1 row. for (int i=0; i<rows; i++) array[i] = &(data[cols*i]); The rest of your code initializes each element of array to hold the address of the corresponding row of the big chunk of memory. Your data pointer will point to a chunk of memory that looks like this: col: 0 1 2 3 ... cols-1 row: 0 * 1 * 2 * 3 * . . . rows-1 * And your array pointer will point to a chunk of memory with a list of pointers, each of which points to one of the asterisks in the memory chunk above. return array; } This just returns your array pointer to a pointer, which matches the return type of the alloc_2d_char function: char **. This means that the caller of the function will essentially obtain an array of pointers, and each of these pointers points to one of the rows of the 2D array.
{ "language": "en", "url": "https://stackoverflow.com/questions/6379945", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Not able pass array value in wso2 BPS My Input Request is: <body> <p:UpdateEntID xmlns:p="http://tempuri.org/"> <!--1 or more occurrences--> <xs:OldID xmlns:xs="http://tempuri.org/">GenreID_002</xs:OldID> <xs:OldID xmlns:xs="http://tempuri.org/">GenreID_0021</xs:OldID> <!--Exactly 1 occurrence--> <xs:NewID xmlns:xs="http://tempuri.org/">GenreID_001</xs:NewID> </p:UpdateEntID> </body> How to assign both the input values i.e OldID to wsdl's Input variable EquivalentEntPLRequest? My assign is: <bpel:assign validate="no" name="AssignInputForUpdateID"> <bpel:copy> <bpel:from> <bpel:literal> <ns0:UpdateEntID xmlns:ns0="http://tempuri.org/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"><ns0:newid>ns0:newid</ns0:newid> <ns0:oldid>ns0:oldid</ns0:oldid> </ns0:UpdateEntID> </bpel:literal> </bpel:from> <bpel:to variable="EquivalentEntPLRequest" part="parameters"></bpel:to> </bpel:copy> <bpel:copy> <bpel:from part="parameters" variable="clientRequest6"> <bpel:query queryLanguage="urn:oasis:names:tc:wsbpel:2.0:sublang:xpath1.0"><![CDATA[tns:NewID]]></bpel:query> </bpel:from> <bpel:to part="parameters" variable="EquivalentEntPLRequest"> <bpel:query queryLanguage="urn:oasis:names:tc:wsbpel:2.0:sublang:xpath1.0"> <![CDATA[ns3:newid]]> </bpel:query> </bpel:to> </bpel:copy> <bpel:copy> <bpel:from part="parameters" variable="clientRequest6"> <bpel:query queryLanguage="urn:oasis:names:tc:wsbpel:2.0:sublang:xpath1.0"><![CDATA[tns:OldID[1]]]></bpel:query> </bpel:from> <bpel:to part="parameters" variable="EquivalentEntPLRequest"> <bpel:query queryLanguage="urn:oasis:names:tc:wsbpel:2.0:sublang:xpath1.0"><![CDATA[ns3:oldid[1]]]></bpel:query> </bpel:to> </bpel:copy> </bpel:assign> By the above assign i am able to map single value of request to single value of response.So how can i map multiple inputs of bpel input to multiple input of wsdl input?Thanks in advance
{ "language": "en", "url": "https://stackoverflow.com/questions/16793209", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: ValueError: Input 0 of layer "model_1" is incompatible with the layer: expected shape=(None, 5312), found shape=(None, 168) I am unable to train the model. Someone, please help!!!!! Here is the code I am trying. While running model_history = model_final.fit([X_weather, X_soil], y,batch_size=16, epochs=100) I am getting this error. X_weather.shape (25345, 168) X_soil.shape (25345, 66) input1 = Input(shape=(168,1)) input2 = Input(shape=(66,1)) model_1D = Conv1D(16, kernel_size= 9 , strides=1, activation='relu')(input1) model_1D = tf.keras.layers.AveragePooling1D(pool_size= 2, strides=2)(model_1D) model_1D = Conv1D(32, kernel_size= 3 , strides=1, activation='relu')(model_1D) model_1D = tf.keras.layers.AveragePooling1D(pool_size= 2, strides=2)(model_1D) model_1D = Conv1D(48, kernel_size= 3 , strides=1, activation='relu')(model_1D) model_1D = tf.keras.layers.AveragePooling1D(pool_size= 2, strides=2)(model_1D) model_1D = Conv1D(64, kernel_size= 3 , strides=1, activation='relu')(model_1D) model_1D = tf.keras.layers.AveragePooling1D(pool_size= 2, strides=2)(model_1D) model_1D = Flatten()(model_1D) model_s = Dense(10 , activation='relu')(input2) model_s = Dense(10 , activation='relu')(model_s) model_s = Flatten()(model_s) merged = Concatenate()([model_1D, model_s]) output = Dense(128, activation='relu')(merged) output = Dense(32 , activation='relu')(output) output = Dense(1 , activation='relu')(output) model_final = Model(inputs=[model_1D, model_s], outputs=[output]) model_final.compile( optimizer = RMSprop(learning_rate=0.02,rho=0.9,epsilon=None,decay=0), loss = 'mean_squared_error', metrics=['accuracy'] ) model_history = model_final.fit([X_weather, X_soil], y,batch_size=16, epochs=100)```
{ "language": "en", "url": "https://stackoverflow.com/questions/72929294", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: C# enque random int I have three threads which are supposed to add a random int to a queue, a fourth that dequeues an int, and a fifth that prints the numbers within it. I'm using threads because they will eventually be needed for the scope of this program and to enqueue/dequeue far more numbers, but having issues with generating a random int. I'm using a class RandomGenerator to create the number, and creating an instance of this class then invoking its GetRandom method to set an int field to a random number. I'm then passing this field into the first three threads which invoke the method to enqueue. The int that prints is not random and I realize this is because I'm simply calling the method at the beginning of the program and passing the same exact number to all three threads. I'm relatively new to C# and realize I may be making a basic mistake. I also realize the fourth thread sometimes accesses the queue when it's empty but isn't as important at the moment. I have tried a number of different things with this and could also have the number generator in the Program class. Here is the code: ... class Program { static void Main() { Program p = new Program(); RandomGenerator rg = new RandomGenerator(); Queue<int> numberQueue = new Queue<int>(); int randomNumber = rg.GetRandom(1, 10); Thread T1 = new Thread(delegate () { p.EnqueueNumber(numberQueue, randomNumber); }); Thread T2 = new Thread(delegate () { p.EnqueueNumber(numberQueue, randomNumber); }); Thread T3 = new Thread(delegate () { p.EnqueueNumber(numberQueue, randomNumber); }); Thread T4 = new Thread(delegate () { p.DequeueNumber(numberQueue); }); Thread T5 = new Thread(delegate () { p.PrintNumbers(numberQueue); }); T1.Start(); T2.Start(); T3.Start(); T4.Start(); T5.Start(); T1.Join(); T2.Join(); T3.Join(); T4.Join(); T5.Join(); } public void EnqueueNumber(Queue<int> numberQueue, int randomNumber) { numberQueue.Enqueue(randomNumber); } public void DequeueNumber(Queue<int> numberQueue) { numberQueue.Dequeue(); } public void PrintNumbers(Queue<int> numberQueue) { foreach (int i in numberQueue) { Console.Write(i); } Console.ReadKey(); } } public class RandomGenerator { private static Random _random = new Random(); private static object syncLock = new object(); public int GetRandom(int min, int max) { lock (syncLock) { return _random.Next(min, max); } } } ... A: You are passing the return value of the GetRandom() method of your single RandomGenerator instance to each of the threads. You need to pass a reference to the RandomGenerator to each of the threads instead, so GetRandom() can be called each time. Thread T1 = new Thread(delegate () { p.EnqueueNumber(numberQueue, rg); }); If you create a RandomGenerator per thread you can also stop using locks which are overkill for this use case. Finally if you insist on concurrent multi-write to, single-read from the same queue, you should also look at ConcurrentQueue rather than Queue as it is thread-safe.
{ "language": "en", "url": "https://stackoverflow.com/questions/61021366", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Launching UFT application makes Cortana use a lot more CPU and react a lot slower I'm using version 14.03. Anytime I open UFT, Cortana, or even Windows Shell Experience Host if I remove Cortana, starts being very slow and CPU hungry. It stays that way until I log off or reboot. Cortana is the process that handles the start menu and searches so it's very noticeable when it is slower. the installation guide mentions that Cortana should be disabled during UFT install, which I tried. It seemed to have fixed the issue at first, Cortana stayed responsive for a while after I opened UFT but it ended up going back to being slow later on. Now, after a reboot, it reverted back to the old behaviour of being slow as soon as UFT is launched Another thing worth noting is that as soon as I uninstall UFT, Cortana works well again (no reboot). What could be causing this? A: * *I'd suggest moving this subject to https://superuser.com/ community. *It indeed sounds like a real conflict between Unified Functional Testing and Cortana. not sure that you, as an end-user, can solve it. * *First, I'd suggest the obvious - contact support of both companies, and update to the latest versions. *Second, try to collect as much information as you can: * *Process Monitor - filter by the relevant processes (Cortana process name is SearchUI.exe, but I don't know about UTF). *Microsoft Event Viewer - try to seek for events in the exact time of the issue.
{ "language": "en", "url": "https://stackoverflow.com/questions/59202876", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Apache Camel pollEnrich using selector on JMSCorrelationID I'm trying to use pollEnrich to consume a specific message from an endpoint based upon the JMSCorrelationID value. I've found many older posts that indicated that pollEnrich did not support this but according to the latest manual pollEnrich now supports dynamic urls Camel manual for pollEnrich. I can't however get it working in my code with a selector and I'm not sure if it is a syntax issue or if I am doing something else wrong. Initially I had it using a dynamic value in the selector but I can't even get it working with a static value. Code snippet of my route: <route id="receive_start"> <from uri="direct:receive_start"/> <pollEnrich> <simple>seda:resources?selector=JMSCorrelationID%3D'1234'</simple> </pollEnrich> <recipientList> <simple>direct:respond_end</simple> </recipientList> </route> When I pass a message through this route I get the following error: Failed delivery for (MessageId: ID-1582783414063-0-11 on ExchangeId: ID-1582783414063-0-10). Exhausted after delivery attempt: 1 caught: org.apache.camel.ResolveEndpointFailedException: Failed to resolve endpoint: seda://resources?+selector=JMSCorrelationID+%3D+%271234%27 due to: Failed to resolve endpoint: seda://resources?+selector=JMSCorrelationID+%3D+%271234%27 due to: There are 1 parameters that couldn't be set on the endpoint. Check the uri if the parameters are spelt correctly and that they are properties of the endpoint. Unknown parameters=[{selector=JMSCorrelationID = '1234'}] Without the selector I can retrieve from the resources endpoint but I need to be able to retrieve a specific message from this endpoint out of all the ones there. The broader context here is that I am processing a message then storing a copy at another endpoint so that later messages may retrieve it if required to extract additional information from it for their own processing.
{ "language": "en", "url": "https://stackoverflow.com/questions/60427651", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Multi-threading with Linq to SQL I am building an application which requires me to make use of DataContext's inside threads. My application keeps throwing InvalidOperationException's similar to: There is already an open DataReader associated with this Command which must be closed first ExecuteReader requires an open and available Connection. The connection's current state is connecting These exceptions are intermittant. Here is a snippet of my code: var repo = new Repository(); var entities = repo.GetAllEntities(); foreach (var entity in entities) { ThreadPool.QueueUserWorkItem( delegate { try { ProcessEntity(entity); } catch (Exception) { throw; } }); } I think it may have something to with passing an entity to a thread from the main thread as the error seems to throw as soon as I try and access a property of entity. Anyone have any idea's why this is happening and how I can resolve it? Update Here is what I decided to go with: var events = new Dictionary<int, AutoResetEvent>(); var repo = new Repository(); var entities = repo.GetAllEntities(); foreach (var entity in entities) { events.Add(entity.ID, new AutoResetEvent(false)); ThreadPool.QueueUserWorkItem( delegate { var repo = new Repository(); try { ProcessHierarchy(repo.GetEntity(entity.ID), ReportRange.Weekly); } catch (Exception) { throw; } finally { events[entity.ID].Set(); } }); } WaitHandle.WaitAll(events.Values.ToArray()); Improvements/Suggestions welcome, but this seems to have done the trick. A: The exception is thrown since some properties of entity executes new query while a previous reader has not been closed yet. You cannot execute more than one query on the data context at the same time. As a workaround you can "visit" the properties you access in ProcessEntity() and make the SQL run prior to the thread. For example: var repo = new Repository(); var entities = repo.GetAllEntities(); foreach (var entity in entities) { var localEntity = entity; // Verify the callback uses the correct instance var entityCustomers = localEntity.Customers; var entityOrders = localEntity.Orders; var invoices = entityOrders.Invoices; ThreadPool.QueueUserWorkItem( delegate { try { ProcessEntity(localEntity); } catch (Exception) { throw; } }); } This workaround will execute the SQL only on the main thread and the processing will be done in other threads. You loose here some of the efficiency since all the queries are done in the single thread. This solution is good if you have a lot of logic in ProcessEntity() and the queries are not very heavy. A: Try creating the Repository inside the new thread instead of passing it in. A: Be aware that a SqlConnection instance is NOT thread safe. Whether you still have an open reader or not. In general, the access of a SqlConnection instance from multiple threads will cause you unpredictable intermittent problems. See: http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlconnection.aspx A: The solution for me was LightSpeed Persistence framework, which is free until 8 entities. Per thread create the unitwork. http://www.mindscapehq.com/products/LightSpeed/default.aspx
{ "language": "en", "url": "https://stackoverflow.com/questions/1815537", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: How to get the textbox's id by cursor position I have multiple textboxes inside a div element. I want to insert some text one of the textbox by cursor position on a button click. I am successfully inserted text if I know the id of a textbox, but i am having problem to know the element wheres the cursor currently positioned. <div> <input type="text" id="txt1" /> <input type="text" id="Text2" /> <input type="text" id="Text3" /> <input type="button" value="Add" id="btnAdd" /> </div> $('#btnAdd').click(function () { insertDataVarables(document.getElementById('txt1'), 'insertedText') }); function insertDataVarables(myField, myValue) { //IE support if (document.selection) { myField.focus(); sel = document.selection.createRange(); sel.text = myValue; } //MOZILLA and others else if (myField.selectionStart || myField.selectionStart == '0') { var startPos = myField.selectionStart; var endPos = myField.selectionEnd; myField.value = myField.value.substring(0, startPos) + myValue + myField.value.substring(endPos, myField.value.length); myField.selectionStart = startPos + myValue.length; myField.selectionEnd = startPos + myValue.length; } else { myField.value += myValue; } } So how could I know the textbox id by cursor position. Thanks in advance A: To catch the focused input when clicking a button, you have to listen to the mousedown event as it fires before the input loses focus. The click event is too late, the input has already lost focused by that time. To get the currently focused (active) element, one can use document.activeElement. So something like this : $('#btnAdd').on('mousedown', function() { var el = document.activeElement; insertDataVarables(el, 'insertedText') }); FIDDLE A: When a cursor is positioned in a textbox save it in a global variable. The on button click insert the value to the saved element. Hope following code snippet will help you. var selctedElm; $(document).on('click', '#btnAdd', function () { selctedElm && selctedElm.val('insertedText'); }); $(document).on('click', 'input[type=text]', function() { selctedElm = $(this); }); <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div> <input type="text" id="txt1" /> <input type="text" id="Text2" /> <input type="text" id="Text3" /> <br/><br/> <input type="button" value="Add" id="btnAdd" /> </div> A: This is the answer given by adeneo $('#btnAdd').on('mousedown', function() { var el = document.activeElement; insertDataVarables(el, 'insertedText') }); function insertDataVarables(myField, myValue) { //IE support if (document.selection) { myField.focus(); sel = document.selection.createRange(); sel.text = myValue; } //MOZILLA and others else if (myField.selectionStart || myField.selectionStart == '0') { var startPos = myField.selectionStart; var endPos = myField.selectionEnd; myField.value = myField.value.substring(0, startPos) + myValue + myField.value.substring(endPos, myField.value.length); myField.selectionStart = startPos + myValue.length; myField.selectionEnd = startPos + myValue.length; } else { myField.value += myValue; } } <div> <input type="text" id="txt1" /> <input type="text" id="Text2" /> <input type="text" id="Text3" /> <input type="button" value="Add" id="btnAdd" /> </div>
{ "language": "en", "url": "https://stackoverflow.com/questions/34063148", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Unable to write files in a GCP bucket using gcsfuse I have mounted a storage bucket on a VM using the command: gcsfuse my-bucket /path/to/mount After this I'm able to read files from the bucket in Python using Pandas, but I'm not able to write files nor create new folders. I have tried with Python and from the terminal using sudo but get the same error. I have also tried Using the key_file from the bucket: sudo mount -t gcsfuse -o implicit_dirs,allow_other,uid=1000,gid=1000,key_file=Notebooks/xxxxxxxxxxxxxx10b3464a1aa9.json <BUCKET> <PATH> It does not through errors when I run the code, but still I'm not able to write in the bucket. I have also tried: gcloud auth login But still have the same issue. A: I ran into the same thing a while ago, which was really confusing. You have to set the correct access scope for the virtual machine so that anyone using the VM is able to call the storage API. The documentation shows that the default access scope for storage on a VM is read-only: When you create a new Compute Engine instance, it is automatically configured with the following access scopes: * *Read-only access to Cloud Storage: https://www.googleapis.com/auth/devstorage.read_only All you have to do is change this scope so that you are also able to write to storage buckets from the VM. You can find an overview of different scopes here. To apply the new scope to your VM, you have to first shut it down. Then from your local machine execute the following command: gcloud compute instances set-scopes INSTANCE_NAME \ --scopes=storage-rw \ --zone=ZONE You can do the same thing from the portal if you go to the settings of your VM, scroll all the way down, and choose "Set Access for each API". You have the same options when you create the VM for the first time. Below is an example of how you would do this:
{ "language": "en", "url": "https://stackoverflow.com/questions/73722570", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: How to get value from database on list item click according to position of list item I can add to a db and list as a listview. When I click a list item using onListItemClick, what statement do I need to get the value? package cabs.h; import android.widget.SimpleCursorAdapter; import android.widget.Toast; import android.widget.AdapterView.AdapterContextMenuInfo; public class planner extends ListActivity { private static final int ACTIVITY_CREATE=0; private static final int ACTIVITY_EDIT=1; private static final int INSERT_ID = Menu.FIRST; private static final int DELETE_ID = Menu.FIRST + 1; private NotesDbAdapter mDbHelper; private Long mRowId; private ServerResponce AllList; // private DeviceListAdapter AllList; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.listonruntime); mDbHelper = new NotesDbAdapter(this); mDbHelper.open(); fillData(); registerForContextMenu(getListView()); String responce = null ; // startManagingCursor(responce); //AllList = new ServerResponce(responce); } private void fillData() { Cursor notesCursor = mDbHelper.fetchAllNotes(); startManagingCursor(notesCursor); // Create an array to specify the fields we want to display in the list (only TITLE) String[] from = new String[]{NotesDbAdapter.KEY_BODY,NotesDbAdapter.KEY_TITLE,NotesDbAdapter.KEY_NUMBER}; int[] to = new int[]{R.id.toptext,R.id.middletext,R.id.circle}; SimpleCursorAdapter notes = new SimpleCursorAdapter(this, R.layout.row, notesCursor, from, to); setListAdapter(notes); } @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { super.onCreateContextMenu(menu, v, menuInfo); menu.add(0, DELETE_ID, 0, R.string.menu_delete); } @Override public boolean onContextItemSelected(MenuItem item) { switch(item.getItemId()) { case DELETE_ID: AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo(); mDbHelper.deleteNote(info.id); fillData(); return true; } return super.onContextItemSelected(item); } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); saveState(); outState.putSerializable(NotesDbAdapter.KEY_ROWID, mRowId); } @Override protected void onPause() { super.onPause(); saveState(); } @Override protected void onResume() { super.onResume(); } // ServerResponce servresp=new ServerResponce(); String responceId = Activity1.getData(); String responceno = Activity2.getData(); String city = cabbookingapplication.Selection; String area = cabbookingapplication.Selection2; String exactadd = cabbookingapplication.Selection3; String nearby = cabbookingapplication.Selection4; private void saveState() { String title =("FROM LOC::"+city+","+area+","+exactadd+","+nearby); String body = ("TO LOC::"+city+","+area+","+exactadd+","+nearby); String number = (""+responceno+",,"+responceId); if (mRowId == null) { long id = mDbHelper.createNote(title, body, number); if (id > 0) { mRowId = id; } } else { mDbHelper.updateNote(mRowId, title, body,number); } } @Override protected void onListItemClick(ListView l, View v, int position, long thisID) { super.onListItemClick(l, v, position, thisID); String resposponseid = Activity2.getData(); Object o = this.getListAdapter().getItemId(position); // String device_name = (String) (planner.this). getListAdapter().getItem(position); Toast.makeText(this, "this row responceid is= " + " " + keyword, Toast.LENGTH_LONG).show(); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent intent) { super.onActivityResult(requestCode, resultCode, intent); fillData(); } } and on list item click i want retrive value of saved in list item according to row position what to do @Override **protected void onListItemClick(ListView l, View v, int position, long thisID) { super.onListItemClick(l, v, position, thisID); String resposponseid = Activity2.getData(); Object o = this.getListAdapter().getItemId(position); Toast.makeText(this, "this row responceid is= " + " " + keyword, Toast.LENGTH_LONG).show(); }** A: If you check the documentation for the method onListItemClick() you can see that the last parameter is the row id of the clicked item. This method will be called when an item in the list is selected. Subclasses should override. Subclasses can call getListView().getItemAtPosition(position) if they need to access the data associated with the selected item. Parameters l: The ListView where the click happened v: The view that was clicked within the ListView position: The position of the view in the list id: The row id of the item that was clicked But to get a proper row id it is important that the cursor which was passed to the adapter contains a row called '_id' representing unique id for each row in the table.
{ "language": "en", "url": "https://stackoverflow.com/questions/5604175", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: java vCenter SDK how to multiple network to a vApp? I'm testing the vCloud Java SDK and I have some problems with the network settings. I've achieved to create the vApp from a template, but the problem is that the vApp gets the wrong network interfaces. I have two interfaces named (see the picture): 1.) 4PM-GR-test-Routed 2.) 4PM-GR-test-LAN-servers-arc-VLAN I when I create the vApp via the template with Vapp vapp = vdc.instantiateVappTemplate(instVappTemplParams); if I control the instVappTemplParams there are both network in the params but the final created vApp has two networks both named 4PM-GR-test-Routed I use the folowing code : public static Vapp newvAppFromTemplate(ReferenceType vAppTemplateReference, Vdc vdc) throws VCloudException { System.out.println("Instantiating " + vAppTemplateReference.getName() + " " + vAppTemplateReference.getHref()); System.out.println("-------------------------------"); // get the href of the OrgNetwork to which we can connect the vApp network if (vdc.getAvailableNetworkRefs().size() == 0) { System.out.println("No Networks in vdc to instantiate the vapp"); System.exit(0); } List<ReferenceType> networks = new ArrayList<ReferenceType>(vdc.getAvailableNetworkRefs()); // fill in the NetworkConfigSection NetworkConfigSectionType networkConfigSection = new NetworkConfigSectionType(); MsgType networkInfo = new MsgType(); networkConfigSection.setInfo(networkInfo); List<VAppNetworkConfigurationType> vAppNetworkConfigs = networkConfigSection.getNetworkConfig(); // specify the NetworkConfiguration for the vApp network Iterator<ReferenceType> networkIterator = vdc.getAvailableNetworkRefs().iterator(); while(networkIterator.hasNext()){ ReferenceType networkReference = networkIterator.next(); System.out.println(networkReference.getName()); NetworkConfigurationType networkConfiguration = new NetworkConfigurationType(); networkConfiguration.setParentNetwork(networkReference); networkConfiguration.setFenceMode(FenceModeValuesType.BRIDGED.value()); VAppNetworkConfigurationType vAppNetworkConfiguration = new VAppNetworkConfigurationType(); vAppNetworkConfiguration.setConfiguration(networkConfiguration); vAppNetworkConfiguration.setNetworkName(networkReference.getName()); vAppNetworkConfigs.add(vAppNetworkConfiguration); } // fill in remaining InstantititonParams (name, Source) InstantiationParamsType instantiationParams = new InstantiationParamsType(); List<JAXBElement<? extends SectionType>> sections = instantiationParams.getSection(); sections.add(new ObjectFactory().createNetworkConfigSection(networkConfigSection)); // create the request body (InstantiateVAppTemplateParams) InstantiateVAppTemplateParamsType instVappTemplParams = new InstantiateVAppTemplateParamsType(); instVappTemplParams.setName("4pm-test-00004"); instVappTemplParams.setSource(vAppTemplateReference); instVappTemplParams.setInstantiationParams(instantiationParams); // make the request, and get an href to the vApp in return Vapp vapp = vdc.instantiateVappTemplate(instVappTemplParams); return vapp; } And when I call the method to set the filan IP-s I got two networks with the same name as I said before. The code for setting the ip-a is: public static void configureVMsIPAddressingMode(ReferenceType vappRef,Vdc vdc) throws VCloudException, TimeoutException { System.out.println(" Configuring VM Ip Addressing Mode"); Vapp vapp = Vapp.getVappByReference(vcloudClient, vappRef); List<VM> childVms = vapp.getChildrenVms(); for (VM childVm : childVms) { NetworkConnectionSectionType networkConnectionSection = childVm.getNetworkConnectionSection(); List<NetworkConnectionType> networkConnections = networkConnectionSection.getNetworkConnection(); for (NetworkConnectionType networkConnection : networkConnections) { String neteworkName = vdc.getAvailableNetworkRefs().iterator().next().getName(); networkConnection.setIpAddressAllocationMode(IpAddressAllocationModeType.MANUAL.value()); networkConnection.setNetwork(neteworkName); System.out.println(neteworkName); if(neteworkName.equals("4PM-GR-test-Routed")){ networkConnection.setIpAddress("192.168.135.4"); }else{ networkConnection.setIpAddress("10.30.1.4"); } } childVm.updateSection(networkConnectionSection).waitForTask(0); for (String ip : VM.getVMByReference(vcloudClient,childVm.getReference()).getIpAddressesById().values()) { System.out.println(" " + ip); } } } A: I figured out that it was a bug in my code this code was giving me always the same name String neteworkName = vdc.getAvailableNetworkRefs().iterator().next().getName(); it should be String neteworkName = networkConnection.getNetwork();
{ "language": "en", "url": "https://stackoverflow.com/questions/15021048", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to route on basis of Http headers in Envoy Proxy I am sending an http request with below header. Header = {"InstanceId" : "1"} How to route to an cluster(endpoint) using this header value i.e. 1 What i actually want to do in envoy.yaml : If (header. InstanceId == 1) Route to cluster A Else If (header. InstanceId == 2) Route to cluster B Can someone please help me out. Thanks in advance. A: If you want to redirect traffic to different clusters based on the headers, you can define the following listener (the interesting part is the static_resources.listeners[0].filter_chains[0].filters[0].route_config.virtual_hosts[0].routes part, with the two matches defined) : static_resources: listeners: - address: socket_address: address: 0.0.0.0 port_value: 8080 filter_chains: - filters: - name: envoy.filters.network.http_connection_manager typed_config: "@type": type.googleapis.com/envoy.extensions.filters.network.http_connection_manager.v3.HttpConnectionManager codec_type: AUTO stat_prefix: ingress_http route_config: name: local_route virtual_hosts: - name: backend domains: - "*" routes: - match: prefix: "/" headers: - name: "InstanceId" exact_match: "1" route: cluster: clusterA - match: prefix: "/" headers: - name: "InstanceId" exact_match: "2" route: cluster: clusterB http_filters: - name: envoy.filters.http.router
{ "language": "en", "url": "https://stackoverflow.com/questions/70959882", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Python loops in Kivy I'm just now learning Kivy for some UI options when creating stuff with Python. The thing I'm strugling right now are loops and how to make them work with Kivy. Example below is a very straightforward loop that should print each number to a Kivy label (replacing previous). Currently when pressing the button I only get the last digit on screen because the entire function runs completely - which makes sense. But my question is how can I setup the button so that when I press it, it runs only one iteration of the loop. My .py file: from kivy.app import App from kivy.core.window import Window from kivy.lang import Builder from kivy.uix.widget import Widget Window.size=(300,300) Builder.load_file('loop.kv') class MyLayout(Widget): def loop(self): for i in range(10): self.ids.label_print.text = str(i) pass class LoopApp(App): def build(self): return MyLayout() if __name__=='__main__': LoopApp().run() My .kv file: <MyLayout> BoxLayout: orientation: 'vertical' size: root.height, root.width Label: id: label_print font_size: 32 Button: text: 'Loop' on_press: root.loop() Currently it only shows 9 as a result and I would expect to go from 0 and add 1 for each button press: A: Basically your loop works correctly, but happens immediately so you only see the 9 and not a sequence or anything. What you can do is to use kivy.clock to schedule an interval to a callback function, specify the interval time and stop the schedule at a certain point. If you would skip the kivy.clock part, your GUI is frozen until the function is finished. Example: from kivy.app import App from kivy.core.window import Window from kivy.lang import Builder from kivy.uix.widget import Widget from kivy.clock import Clock from timeit import time Window.size=(300,300) Builder.load_file('loop.kv') class MyLayout(Widget): loop_thread = None def callback_to_loop(self, dt): # dt is the interval-time # this is required because initially the text is an empty string try: current = int(self.ids.label_print.text) except: current = 0 # simply add up the numbers self.ids.label_print.text = str(current+1) # stop at a certain point and unschedule the thread if current == 11: Clock.unschedule(self.loop_thread) def loop(self): # schedule the thread with an interval-time = 1 self.loop_thread = Clock.schedule_interval(self.callback_to_loop, 1) pass class LoopApp(App): def build(self): return MyLayout() if __name__=='__main__': LoopApp().run()
{ "language": "en", "url": "https://stackoverflow.com/questions/69101512", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Rails inserting multiple records for single model How shall I set the form fields to be able to insert multiple rows in the database for a single model. I am updating a div with another link and cannot use the form helper. So I need to set the field names manually. I have a post model and it has a title field. I want to insert i posts to db like post[0][title] But when I name the form field like this It gets 0 as string and does not record. Also I tried to set the Array my self from Rails Console like post = Array.new post << [:title => "title 1"] post << [:title => "title 2"] sav = Post.new(post) sav.save And still nothing is saved. A: posts = Array.new posts << {:title => "title 1"} posts << {:title => "title 2"} Post.create(posts) A: is this what you're trying to do? posts = [] posts << Post.new(:title => "title 1") posts << Post.new(:title => "title 2") posts.each do |post| post.save end
{ "language": "en", "url": "https://stackoverflow.com/questions/4495705", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Check for a valid guid How can you check if a string is a valid GUID in vbscript? Has anyone written an IsGuid method? A: This function is working in classic ASP: Function isGUID(byval strGUID) if isnull(strGUID) then isGUID = false exit function end if dim regEx set regEx = New RegExp regEx.Pattern = "^({|\()?[A-Fa-f0-9]{8}-([A-Fa-f0-9]{4}-){3}[A-Fa-f0-9]{12}(}|\))?$" isGUID = regEx.Test(strGUID) set RegEx = nothing End Function A: This is similar to the same question in c#. Here is the regex you will need... ^[A-Fa-f0-9]{32}$|^({|()?[A-Fa-f0-9]{8}-([A-Fa-f0-9]{4}-){3}[A-Fa-f0-9]{12}(}|))?$|^({)?[0xA-Fa-f0-9]{3,10}(, {0,1}[0xA-Fa-f0-9]{3,6}){2}, {0,1}({)([0xA-Fa-f0-9]{3,4}, {0,1}){7}[0xA-Fa-f0-9]{3,4}(}})$ But that is just for starters. You will also have to verify that the various parts such as the date/time are within acceptable ranges. To get an idea of just how complex it is to test for a valid GUID, look at the source code for one of the Guid constructors. A: In VBScript you can use the RegExp object to match the string using regular expressions. A: Techek's function did not work for me in classic ASP (vbScript). It always returned True for some odd reason. With a few minor changes it did work. See below Function isGUID(byval strGUID) if isnull(strGUID) then isGUID = false exit function end if dim regEx set regEx = New RegExp regEx.Pattern = "{[0-9A-Fa-f-]+}" isGUID = regEx.Test(strGUID) set RegEx = nothing End Function A: there is another solution: try { Guid g = new Guid(stringGuid); safeUseGuid(stringGuid); //this statement will execute only if guid is correct }catch(Exception){}
{ "language": "en", "url": "https://stackoverflow.com/questions/133493", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Extract text inside HTML tags using XSLT I have an XML file that has some CDATA with html tags. Example: <TextElement> <Data> <![CDATA[ <h2>My Header Text</h2> ]]> </Data> </TextElement> I need to be able to display "My Header Text" without the H2 tag. Thank you! A: Using <xsl:param name="start-tag"><![CDATA[<h2>]]></xsl:param> <xsl:param name="end-tag"><![CDATA[</h2>]]></xsl:param> and then a substring-after(substring-before combination <xsl:template match="Data"> <xsl:value-of select="substring-before(substring-after(., $start-tag), $end-tag)"/> </xsl:template> should do. http://xsltransform.net/naZXpY6.
{ "language": "en", "url": "https://stackoverflow.com/questions/47167822", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Grails persistence in Spring's "Async" annotated methods not working I have a problem on persisting Grails domain objects in Spring Async annotated service methods. Here is the simplified code: class DocumentService { @Async def process(Long documentId, Organization organization) { ... def organizationCari = new OrganizationCari(organization: organization, active: true) organizationCari.save(flush: true, failOnError: true) print "Document processing..." ... print "Document processed..." } } I have the method running asynchronously, but then I can't seem to get anything printed on the console, since thread ends upon save operation. I get no errors and the domain object is still not persisted. Removing Async annotation solves the problem, but I have to run the method asynchronously. I'm using Grails 2.1.1 with Spring 3.1.2. A: The problem is that there is no hibernate session in the new asynchronous thread, and the default AsyncTaskExecutor is not logging the exception. You can verify this yourself by putting a try/catch block inside your @Async method and logging the exception yourself. The solution is to use Domain.withNewSession around the GORM code in your service method: import org.springframework.scheduling.annotation.Async class MyService { @Async void myAsyncMethod() { MyDomain.withNewSession { MyDomain m = new MyDomain(...) m.save() } } } If you have many asynchronous methods, you may consider creating your own AsyncTaskExecutor as in this SO answer.
{ "language": "en", "url": "https://stackoverflow.com/questions/15549808", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: advice on the best method of positioning my active tab link correctly and consistently I'm having trouble trying to place my active anchor tab over the main content area border, i have tried adding position: relative etc but have had no joy, the tab also has to be positioned over the ul border so i think i may have set this up wrong, can anyone give me some pointers on how I could achieve this effect correctly? My link http://jsfiddle.net/eBnUt/1/ Thanks Kyle A: You just need to add margin-top: -2px; to .boxBody. Live example: http://jsfiddle.net/tw16/eBnUt/2/ .boxBody{ border: 2px solid #343434; background: #fff; /*width: 100%;*/ min-height: 70px; padding: 20px; margin-top: -2px; /* add this */ -webkit-border-bottom-right-radius: 10px; -webkit-border-bottom-left-radius: 10px; -moz-border-radius-bottomright: 10px; -moz-border-radius-bottomleft: 10px; border-bottom-right-radius: 10px; border-bottom-left-radius: 10px; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7310626", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: ionic: HTML5 audio tag not working on iOS 11 I am developing an ionic framework test app which streams audio from a server using the HTML5 audio tag. I've been testing it in some Android and iOS devices and it works just fine. Today I got an iOS 11 device to test and I found that the stream does not work. I created a simple web to test the device with safari and worked. I uploaded the app to ionic view and worked too. Is there something new on iOS 11 that disables streamings on apps? Is it something with the HTML5 audio tag? A: I solved the issue by adding type="audio/mpeg" to the audio tag.
{ "language": "en", "url": "https://stackoverflow.com/questions/49174023", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: what is the meaning of "n/n/n" in the header of csv file? how can I make a data frame from this file? Dataframe after importing csv file [Kunde;Produkt;Kampagne;Vermarkter/Verlag;Werbeträger;Datum von;Datum bis;Platzierung;Werbeform;Menge;Einheit;n/n/n;Tracking-ID;AdGap-ID] I am trying to expand this data to a pandas data frame, but I am confused about this header. After importing this *.csv file into my python data frame there are two columns. So far I have made two data frame, using the first column and second column. But how I can combine them? what is the relation between this two data frames? Data frame 1 Data frame 2
{ "language": "en", "url": "https://stackoverflow.com/questions/71361478", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: What is the cost of try catch blocks? How much better is: if (condition) { try { //something } catch(SomeEx ex) {} } instead of this: try { if (condition) { //something } } catch(SomeEx ex) {} What actually JVM do when I enter try block ? EDIT: I don't want to know that in second example always go in to try... Please answer the question. A: try {if (condition) {...}} catch(SomeEx ex) {} Here you handled the exception if it is arised condition of if also if arised inside if-block. if (condition) {try {...} catch(SomeEx ex) {}} Here you handle exception if is arised only inside the if-block. If something goes wrong in if condition then it will not be handled. So it is depends upon the actual senario. A: Execution wise at run time, as long as there is no exception, try does not cost you anything. It only costs run time as soon as an exception occurs. And in that situation it is much slower that an if evaluation. In the JVM spec, you see that there is no extra byte code generated on the execution path: http://docs.oracle.com/javase/specs/jvms/se7/html/jvms-3.html#jvms-3.12 A: From the perfomance point of view it should be the same. Throwing of the exception is a costly operation (for starters, the stacktrace must be created and populated). The mere existence of the try block has no (or negligible) performance penalty. See Should java try blocks be scoped as tightly as possible. What actually JVM do when I enter try block ? From JLS 14.20.1. Execution of try-catch: A try statement without a finally block is executed by first executing the try block. Then there is a choice: * *If execution of the try block completes normally, then no further action is taken and the try statement completes normally. *If execution of the try block completes abruptly because of a throw of a value V, then there is a choice: * *If the run-time type of V is assignment compatible with (§5.2) a catchable exception class of any catch clause of the try statement, then the first (leftmost) such catch clause is selected. The value V is assigned to the parameter of the selected catch clause, and the Block of that catch clause is executed, and then there is a choice: * *If that block completes normally, then the try statement completes normally. *If that block completes abruptly for any reason, then the try statement completes abruptly for the same reason. *If the run-time type of V is not assignment compatible with a catchable exception class of any catch clause of the try statement, then the try statement completes abruptly because of a throw of the value V. *If execution of the try block completes abruptly for any other reason, then the try statement completes abruptly for the same reason. EDIT: For a complete Exception description see the JVM 2.10 link in The New Idiot's answer. A: if (condition) { try { //something } catch(SomeEx ex) {} } is better to use since it executes the try block if the condition is ok.JVM compiles the try block and validated the catch block or a finally block. I think advantage is not in the compile time but in the run time. Compile time I think no advantage at all A: Exceptions should be exceptional case , not every time the code runs. So better to check for the condition before trying ! if (condition) { try { //something } catch(SomeEx ex) {} } Make sure , if (condition) itself doesn't throws an Exception. It depends on your usage and functionality . For example this would be better : if (someObject!=null) { try { someObject.getSomething(); // getSomething() potentially throws some Exception } catch(SomeEx ex) {} } What actually JVM do when I enter try block ? Read JVM spec 2.10. A: If you see oracle docs >try { code } catch and finally blocks . . . The segment in the example labeled code contains one or more legal lines of code that could throw an exception. So,If you feel doubt on your If condition that it will throw an exception put it inside.Otherwise put outside.
{ "language": "en", "url": "https://stackoverflow.com/questions/17966265", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: JavaScript's functions and objects assignment to other variables I was going through some practice sessions and I came to learn that in JS, functions are also object. So I tried the following. function say() { console.log("hi") } var obj1 = say; obj1.hello = "hello"; console.log(say.hello); // hello then I tried doing the same with an object, but got undefined and I expected to get winter. var obj2 = { weather: "summer", time: "noon" }; var name = obj2; name.favoriteWeather = "winter"; console.log(name.favoriteWeather); //undefined Why JS behaves the way it does? how can I get winter as result from name.favoriteWeather
{ "language": "en", "url": "https://stackoverflow.com/questions/44584123", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How do I debug a Xamarin app + webapi + SQL Server set-up? I'm brand new to Xamarin.Forms and Visual Studio (2017 on PC). I'm working with code another (experienced) dev wrote in C# and .NET. I have a Xamarin app. The app asks me to input data. Then, it saves that data to a SQL Server database via a Web API. Next, later, the app gets that data back from the database to do something. I can build and publish all projects and the app runs on Android simulator. However, it looks like the data I input is either: * *Not sent to the DB *Not used by the DB I can tell because when I get the data back from the database, the "something" is wrong. So here's my question: how do I debug that set-up? I'm familiar with debugging my Xamarin app inside VS 2017, but I don't know how to debug the Web API, or how to look inside the database to see if the data I input are recorded correctly. At this point, I'm not sure where the bug is, or how to find it. Thanks for your help! A: Xamarin application: As you already mentioned, you can debug your Xamarin app in Visual Studio just like you would any other .Net projects. Web API: Similarly, you can also debug your Web API project in Visual Studio. * *Run the Web API project locally. *Note the address from the address bar and use that in Postman or other similar tools to send/receive the API requests/response. SQL Server Database: You cannot technically 'debug' a database, but you can verify the CRUD operations using SQL Server Management Studio (or SSMS) provided you have the necessary access/credentials. To find where the error is, I would suggest: * *Start from your Xamarin application and verify if the app is sending the JSON as expected; *Then send the same JSON from postman to your Web API and verify if it is accepting/processing the JSON as expected; *And finally, check your database tables in SSMS if the data is stored as expected. Refer the following links: https://www.c-sharpcorner.com/article/asp-net-web-api-with-fiddler-and-postman/ https://learn.microsoft.com/en-us/azure/sql-database/sql-database-connect-query-ssms Hope it helps. Cheers! A: Found out you can debug a web API using Visual Studio almost the same way you debug a Xamarin app. Here's a nice tutorial for that: https://learn.microsoft.com/en-us/azure/app-service/web-sites-dotnet-troubleshoot-visual-studio#remotedebug
{ "language": "en", "url": "https://stackoverflow.com/questions/51697543", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Trouble Installing Plone on Solaris 11 I am new to Plone and Solaris - I'm attempting to install Plone 5 on Solaris 11. Seems to be hanging up on the Zope install. Here is the install.log: Detailed installation log Starting at Wed Oct 14 11:41:13 AKDT 2015 The directory '/home/dotasdis/.cache/pip/http' or its parent directory is not owned by the current user and the cache has been disabled. Please check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag. The directory '/home/dotasdis/.cache/pip' or its parent directory is not owned by the current user and caching wheels has been disabled. check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag. Processing ./packages/zc.buildout-2.4.3.tar.gz Requirement already satisfied (use --upgrade to upgrade): setuptools>=8.0 in /opt/plone/zinstance/lib/python2.7/site-packages (from zc.buildout==2.4.3) Installing collected packages: zc.buildout Running setup.py install for zc.buildout Successfully installed zc.buildout-2.4.3 /opt/plone/zinstance/lib/python2.7/site-packages/pip/_vendor/requests/packages/urllib3/util/ssl_.py:90: InsecurePlatformWarning: A true SSLContext object is not available. This prevents urllib3 from configuring SSL appropriately and may cause certain SSL connections to fail. For more information, see https://urllib3.readthedocs.org/en/latest/security.html#insecureplatformwarning. InsecurePlatformWarning Creating directory '/opt/plone/zinstance/parts'. Creating directory '/opt/plone/zinstance/develop-eggs'. Not found: /opt/plone/buildout-cache/downloads/dist/ZODB3/ Not found: /opt/plone/buildout-cache/downloads/dist/ZODB3/ Getting distribution for 'ZODB3==3.10.5'. gcc: cg: No such file or directory gcc: unrecognized option '-Qoption' gcc: unrecognized option '-KPIC' gcc: language O5 not recognized gcc: language O5 not recognized error: Setup script exited with error: command '/usr/gcc/4.5/bin/gcc' failed with exit status 1 An error occurred when trying to install ZODB3 3.10.5. Look above this message for any errors that were output by easy_install. While: Installing. Getting section instance. Initializing section instance. Installing recipe plone.recipe.zope2instance. Getting distribution for 'ZODB3==3.10.5'. Error: Couldn't install: ZODB3 3.10.5 Any help is greatly appreciated.
{ "language": "en", "url": "https://stackoverflow.com/questions/33135685", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Error installing jira on pip I am trying to install jira on pip, but am getting the following errors: /usr/lib64/nagios/plugins]#python -m pip install jira Collecting jira Retrying (Retry(total=4, connect=None, read=None, redirect=None)) after connection broken by 'ProtocolError('Connection aborted.', gaierror(-2, 'Name or service not known'))': /simple/jira/ Retrying (Retry(total=3, connect=None, read=None, redirect=None)) after connection broken by 'ProtocolError('Connection aborted.', gaierror(-2, 'Name or service not known'))': /simple/jira/ Retrying (Retry(total=2, connect=None, read=None, redirect=None)) after connection broken by 'ProtocolError('Connection aborted.', gaierror(-2, 'Name or service not known'))': /simple/jira/ Retrying (Retry(total=1, connect=None, read=None, redirect=None)) after connection broken by 'ProtocolError('Connection aborted.', gaierror(-2, 'Name or service not known'))': /simple/jira/ Retrying (Retry(total=0, connect=None, read=None, redirect=None)) after connection broken by 'ProtocolError('Connection aborted.', gaierror(-2, 'Name or service not known'))': /simple/jira/ Retrying (Retry(total=4, connect=None, read=None, redirect=None)) after connection broken by 'ProtocolError('Connection aborted.', gaierror(-2, 'Name or service not known'))': /simple/jira/ Retrying (Retry(total=3, connect=None, read=None, redirect=None)) after connection broken by 'ProtocolError('Connection aborted.', gaierror(-2, 'Name or service not known'))': /simple/jira/ Retrying (Retry(total=2, connect=None, read=None, redirect=None)) after connection broken by 'ProtocolError('Connection aborted.', gaierror(-2, 'Name or service not known'))': /simple/jira/ Retrying (Retry(total=1, connect=None, read=None, redirect=None)) after connection broken by 'ProtocolError('Connection aborted.', gaierror(-2, 'Name or service not known'))': /simple/jira/ Retrying (Retry(total=0, connect=None, read=None, redirect=None)) after connection broken by 'ProtocolError('Connection aborted.', gaierror(-2, 'Name or service not known'))': /simple/jira/ Could not find a version that satisfies the requirement jira (from versions: ) No matching distribution found for jira Any help would be highly appreciated. A: The ProtocolError says that pip is trying to resolve /simple/jira/ as a DNS hostname instead of pypi.python.org. The problem may reside in ~/.pip/pip.conf. Are you in a container by any chance?
{ "language": "en", "url": "https://stackoverflow.com/questions/36333500", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Two onPointerOver events conflict in React My screen is divided in two zones: left zone and right zone. The left zone appears always. When you point over the left zone, it should make appear the right zone. Once the right zone is displayed, both zones should make the right zone display. But its not working as expected, the right zone disappear when "trying" to point over it. Check the demo HERE export default function App() { const [pointOverLeftZone, setPointOverLeftZone] = useState(false); const [pointOverRightZone, setPointOverRightZone] = useState(false); const shouldDisplayRightZone = pointOverLeftZone || pointOverRightZone; return ( <div className="App"> <div className="zone light-cyan" onPointerOver={() => { if (!pointOverLeftZone) setPointOverLeftZone(true); }} onPointerOut={() => { if (pointOverLeftZone) setPointOverLeftZone(false); }} > <p>Point over here to display the right zone</p> </div> {shouldDisplayRightZone && ( <div className="zone light-yellow" onPointerOver={() => { if (!pointOverRightZone) setPointOverRightZone(true); }} onPointerOut={() => { if (pointOverRightZone) setPointOverRightZone(false); }} > <p> Once open the right zone, both zones should activate the display of this right zone, but the bug is here: when you mouse the move here it dissapear </p> </div> )} </div> ); } A: Value of shouldDisplayRightZone depends on value of pointOverLeftZone, pointOverRightZone so you should make it an independent state and wrap into an useEffect and update whenever there are changes in pointOverLeftZone, pointOverRightZone const [shouldDisplayRightZone, setShouldDisplayRightZone] = useState( pointOverLeftZone || pointOverRightZone ); useEffect(() => { setShouldDisplayRightZone(pointOverLeftZone || pointOverRightZone); }, [pointOverLeftZone, pointOverRightZone]); Forked codesandbox A: import React, { useState } from "react"; import "./styles.css"; export default function App() { const [pointOverLeftZone, setPointOverLeftZone] = useState(false); const [pointOverRightZone] = useState(false); const shouldDisplayRightZone = pointOverLeftZone || pointOverRightZone; return ( <div className="App"> <div className="zone light-cyan" onPointerOver={() => setPointOverLeftZone(true)} > <p>Point over here to display the right zone</p> </div> {shouldDisplayRightZone && ( <div className="zone light-yellow" onPointerOut={() => setPointOverLeftZone(false)} > <p> Once open the right zone, both zones should activate the display of this right zone, but the bug is here: when you mouse the move here it dissapear </p> </div> )} </div> ); } Something like this? A: import React, { useState } from "react"; import "./styles.css"; export default function App() { const [pointOverLeftZone, setPointOverLeftZone] = useState(false); const [pointOverRightZone, setPointOverRightZone] = useState(false); const [flag, setFlag] = useState(true); const [int, setIni] = useState(false); const shouldDisplayRightZone = pointOverLeftZone || pointOverRightZone; return ( <div className="App"> {flag === true ? ( <div className="zone light-cyan" onPointerOver={() => { if (!pointOverLeftZone) { setPointOverLeftZone(true); } }} > <p>Point over here to display the right zone</p> </div> ) : ( <div> <div>right zone open</div> <p> Once open the right zone, both zones should activate the display of this right zone, but the bug is here: when you mouse the move here it dissapear </p> </div> )} {shouldDisplayRightZone && ( <div className="zone light-yellow" onPointerOver={() => { if (!pointOverRightZone) { setFlag(false); setPointOverRightZone(true); } }} onPointerOut={() => { if (pointOverRightZone) setPointOverRightZone(false); }} > <p> Once open the right zone, both zones should activate the display of this right zone, but the bug is here: when you mouse the move here it dissapear </p> </div> )} </div> ); } i have changed the code in sandbox you can check it there.Let me know if it works
{ "language": "en", "url": "https://stackoverflow.com/questions/63788620", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Regular expression for two following proper nouns I am trying to build a script that should give you a list of the proper names of a text. I want to build a regular expression that matchs every word that starts with a capital letter and that doesn't start a stence. An example from the text: "But while he thought about these things, behold, an angel of the Lord appeared to him in a dream, saying: Joseph, son of David, do not be afraid to take to you Mary your wife, for that which is conceived in her is of the Holy Spirit. She is going to have a son. You must give him the name Jesus. That’s because he will save his people from their sins. I want that the regexp matches: "Lord", "Joseph", "David", "Mary", "Holy" and "Spirit". It should not match "But", "She", "You" or "That". So I did this: [a-z,;:] +([A-Z][a-z]+)[\W] This matchs Lord, Joseph, David, Mary and Holy, BUT not Spirit. And that is my problem: after finding "Holy", the regexp keeps going searching in the text the pattern; to find "Spirit", the regexp should take the "y" of "Holy" in consideration for the first square bracket. So, after finding "Holy" should restart not after "Holy". I have tried it also with non matching groups, like: (?:[a-z,;:]) +([A-Z][a-z]+)[\W] But that is also not the answer. I would be very thankful if anyone would help. Regards! A: Regex (?<=[a-z,;:] )([A-Z][a-z]+) Demo Output: MATCH 1 1. [65-69] `Lord` MATCH 2 1. [106-112] `Joseph` MATCH 3 1. [121-126] `David` MATCH 4 1. [160-164] `Mary` MATCH 5 1. [221-225] `Holy` MATCH 6 1. [226-232] `Spirit` A: You can try (?<![.!?;]) ([A-Z]\w+) demo
{ "language": "en", "url": "https://stackoverflow.com/questions/36005794", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Accessing $scope variable from another method in the same controller Angularjs how can I call/access $scope.mydata from another method in the same controller in Angularjs? My scenario is .controller("myCtryl", function($scope, $http) { $scope.functionA = function(){ $scope.data = "some data"; } $scope.functionB = function(){ //access $scope.data here// } } A: It is fine to access $scope in that function. .controller("myCtryl", function($scope, $http) { $scope.functionA = function(){ $scope.data = "some data"; } $scope.functionB = function(){ $scope.data //this id valid } } A: You can just access $scope.data in functionB the same way you access it in functionA. It will work. The $scope variable is in the same lexical scope for both functions.
{ "language": "en", "url": "https://stackoverflow.com/questions/28139972", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: What is the difference between ASM LHI and LGHI? In the *.s file of a compiled cpp code by gcc, there are some LHI and LGHI command. I know they mean load address, very similar to LA, but what is the exact difference between them? Is there any document about this? Thanks!
{ "language": "en", "url": "https://stackoverflow.com/questions/32084973", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Calculation of Latitude and Longitude from given point and radius I have latitude, longitude and a radius. Can you please help me in finding the another latitude and longitude from given points (latitude and longitude) and radius. A: Are you trying to find out if another latitude and longitude is within a certain radius of your initial latitude and longitude? If so, check out this other StackOverflow post. A: You will need more information than a point and a radius. You are also going to need the angle of the point in the circle. Using the radius and the angle you have to apply trigonometric laws and draw and imaginary triangle with dimensions radius, height and width. The height and width will give you the distance from the current latitude and longitude. For example: for (int angle = 0; angle < 360; angle++){ double x = getDistanceX(radius, angle); double y = getDistanceY(radius, angle); if (angle > 180) x *= -1; if (angle > 90 && angle < 270) y *= -1; double newLatitude = getCalculateLatitude(latitude, x); double newLongitude = getCalculateLatitude(longitude, y); }
{ "language": "en", "url": "https://stackoverflow.com/questions/10247279", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: background is divided for some reason can someone take a look at my webpage and help me figure out what is wrong for some a reason the background gradient is divided and start a new one again. I want the gradient to continue to the entire page. this is the html https://www.csupomona.edu/~lannguyen/Test/Template.html this is the css for it https://www.csupomona.edu/~lannguyen/Test/mystyle.css Thanks A: Get a tool like Firebug for Firefox and learn to use it. It makes finding issues like this simple. The answer is clear, once you have the right tool: the gradient, which is applied to the body element, does not extend all the way down because the body element does not go the full height of the browser. Add: html, body { height: 100%; } and it will be fixed.
{ "language": "en", "url": "https://stackoverflow.com/questions/19440753", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Function to check if the db value matches the current Select option I am creating a customer account page which displays the relevant information in the database and allows customers to edit their information. The code below retrieves and displays the customer's account information from the database and pre-selects the values matching their information, but since there are a few hundred select and/or multiselect elements I'd like to create a function which would check if the db value (i.e. $rows['gift_privacy']) matches the current option. <?php try { $stmt = $conn->prepare("SELECT * FROM customer_info WHERE user_id = :user_id"); $stmt->bindValue(':user_id', $user_id); $stmt->execute(); }catch(PDOException $e) {echo $e->getMessage();} $row = $stmt->fetch(); ?> <form action="account_information-exec.php" method="post"> <select name="gift_privacy"> <option value="Standard" <?php if($row['gift_privacy']=='Standard') echo "selected='selected'"; ?>>Standard</option> <option value="Gift_ID_Req" <?php if($row['gift_privacy']=='Gift_ID_Req') echo "selected='selected'"; ?>>Require program ID</option> <option value="Not_Enrolled" <?php if($row['gift_privacy']=='Not_Enrolled') echo "selected='selected'"; ?>>Do not enroll</option> </select> <input type="submit" value="submit"> </form> Edit - The code differs slightly for the multiselect elements. The element names are followed by square brackets (i.e. name="notifications[]"), and values are inserted into the database as imploded arrays implode(',', $_POST['notifications']). Those commas are then stripped from fetched values in order to properly compare them to the option's values $row1 = str_replace(',', '', $row); Existing Function This function applies selected="selected" to the correct options, but it's too cumbersome for me to use with so many elements and I'm not sure how to modify the code so that it could be easily applied to all the select and/or multiselect elements. Also, since the page currently uses standard select elements with hard-coded options I'm hoping for a solution that doesn't require creating arrays for each element. <select name="gift_privacy"> <?php $gifts = array("Standard" => "Standard", "Gift_ID_Req" => "Require Program ID", "Not_Enrolled" => "Do not Enroll"); $gift = $row['gift_privacy']; foreach($gifts as $key => $value) { if($key == $gift) { echo '<option selected="selected" value="'. $key .'">'. $value .'</option>'; } else { echo '<option value="'. $key .'">'. $value .'</option>'; } } ?> </select> A: I faced the same problem once and solved it by creating a function (or a class static method) to handle my option lists. To print out your options you will have to cycle through them anyway, so while you cycle there is nothing bad in checking for each one if it must be the currently selected. Just create a function like: function printSelectOptions($dataArray, $currentSelection) { foreach ($dataArray as $key => $value) { echo '<option ' . (($key == $currentSelection) ? 'selected="selected"' : '') . ' value="' . $key . '">' . $value . '</option>'; } } Giving $dataArray as your key/value options array, and $currentSelection as the key of the selected option. So in your code you will have just calls to this function, like: <select id='mySelect' name='mySelect'> <?php echo printSelectOptions($gifts, $gift); ?> </select> This should do the work! EDIT: Adding sample to work with select multiple... <?php $options = array( 1 => "Test 1", 2 => "Test 2", 3 => "Test 3"); $selected = array(1, 3); function printSelectOptions($dataArray, $selectionArray) { foreach ($dataArray as $key => $value) { echo '<option ' . (in_array($key, $selectionArray) ? 'selected="selected"' : '') . ' value="' . $key . '">' . $value . '</option>'; } } ?> <select multiple> <?php echo printSelectOptions($options, $selected); ?> </select> The trick is passing the selected values as an array of keys, instead of a single key. In the sample I provided dummy arrays, but obviously you'll have to build yours from database... :) EDIT: Select multi with arrays taken from the question... <?php $gifts = array("Standard" => "Standard", "Gift_ID_Req" => "Require Program ID", "Not_Enrolled" => "Do not Enroll"); $gift = array($row['gift_privacy']); function printSelectOptions($dataArray, $selectionArray) { foreach ($dataArray as $key => $value) { echo '<option ' . (in_array($key, $selectionArray) ? 'selected="selected"' : '') . ' value="' . $key . '">' . $value . '</option>'; } } ?> <select multiple> <?php echo printSelectOptions($gifts, $gift); ?> </select> EDIT: Explode multiple selected values If you have mutliple selected values as a comma separated string, you just have to explode it before passing to the function I provided... $selectedOptionsArray = explode(',', $selectedOptionsString); So the ending code will look like... <?php $gifts = array("Standard" => "Standard", "Gift_ID_Req" => "Require Program ID", "Not_Enrolled" => "Do not Enroll"); $gift = explode(',', $row['gift_privacy']); function printSelectOptions($dataArray, $selectionArray) { foreach ($dataArray as $key => $value) { echo '<option ' . (in_array($key, $selectionArray) ? 'selected="selected"' : '') . ' value="' . $key . '">' . $value . '</option>'; } } ?> <select multiple> <?php echo printSelectOptions($gifts, $gift); ?> </select> A: You could use a function like this to simplify it: <?php function renderOption($key, $value, $current) { echo '<option value="' . $key . '"' . ($key == $current ? ' selected="selected"' : '') . '>' . $value. '</option>'; } ?> <select name="gift_privacy"> <?php $gifts = array("Standard" => "Standard", "Gift_ID_Req" => "Require Program ID", "Not_Enrolled" => "Do not Enroll"); $gift = $row['gift_privacy']; foreach($gifts as $key => $value) renderOption($key, $value, $gift); ?> </select> A: Use simpler method: <?php echo '<option '.($key == $gift ? 'selected="selected" ' : '').'value="'. $key .'">'. $value .'</option>'; ?> Edit: second option echo '<option '.selected_option($key, $gift).'value="'. $key .'">'. $value .'</option>'; function selected_option($val1, $val2){ if($val1 == $val2){ return 'selected="selected" '; }else{ return ''; } } A: There is nothing wrong with what you have, and this, or something very similar is the typical approach to this problem. You would/could wrap it in an actual function, say print_select( $array, $selected ); which would/could print out the entire <select> including the select themselves. The final code might be: print_select( $gifts, $selected_gift ); print_select( $colors, $selected_color ); // etc
{ "language": "en", "url": "https://stackoverflow.com/questions/14848744", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Problems displaying content generated by php, wordpress build in IE Here's the site http://www.therustyzip.com/ I just can't seem to get it working at all A: From the source of your page it can be seen that your problem start with: <html> lang="en"> you need to change that to: <html lang="en">
{ "language": "en", "url": "https://stackoverflow.com/questions/11743495", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-4" }
Q: Why is QCameraImageCapture saving an image to the hard drive? Part of an application I have written has the ability to capture pictures from the webcam. I am using a QCamera with a QCameraViewfinder to display the current view, and then when a shutter button is clicked, it snaps a picture with a QCameraImageCapture set to capture to buffer, then handles it from there. I have just discovered that it is also saving a copy of the image in the local Pictures folder. Why is this happening, and how can I stop it? A: This is just my point of observation: Based on the documentation, after you call capture, irrespective of destination location ( I mean CaptureToFile or CaptureToBuffer) the image is saved to a file. note this statemet in below link: If an empty file is passed, the camera backend choses the default location and naming scheme for photos on the system. http://doc.qt.io/qt-5/qcameraimagecapture.html#capture The additional advantage with "CaptureToBuffer", your image is saved in some specified buffer format. My wild guess, if at all they are not supporting ( as i am unable to find any offical information on it) only capture to buffer, the reason could be, the user is allowed to set the bufferformat using setBufferFormat. And the device may not support the buffer format (isCaptureDestinationSupported() is there to check it.). May be because of this they are saving to local pictures folder always. If this saving is unavoidable by capture, and if your business strictly needs not to maintain those saved files, when your buffer is doing good, probably you can delete them in below slot. QObject::connect(YOURCAMERACAPTUREOBJECT, SIGNAL(imageSaved), this,SLOT(saved(int id, const QString &fileName))); void saved(int id, const QString &fileName) { //Delete the file by checking you have content in buffer. //to check the buffer probably you can use "imageAvailable" signal } A: I believe that bug you are describing were in GStreamer camerabin plugin. When you look to https://code.qt.io/cgit/qt/qtmultimedia.git/tree/src/plugins/gstreamer/camerabin/camerabinsession.cpp?h=5.15#n587 m_imageFileName is setup independently on capture destination. File is saved by this filter then https://code.qt.io/cgit/qt/qtmultimedia.git/tree/src/plugins/gstreamer/mediacapture/qgstreamercapturesession.cpp?h=5.15#n404 edit: This bug seems to be fixed somehow in Qt 5.15.
{ "language": "en", "url": "https://stackoverflow.com/questions/43123752", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: MissingSchemaError: Schema hasn't been registered for model "Blog" I am getting above error which I am stuck I am a beginner of mongodb, expressjs My Index.js: const mongoose= require('mongoose') let modelspath ='./models' fs.readdirSync(modelspath).forEach(function(file){ if(~file.indexOf('.js')) console.log(file) require(modelspath +'/' + file) //if block checks weather file ending with .js ext }) my controller file const BlogModel = mongoose.model('Blog') let testRoute = (req, res) => { console.log(req.params) res.send(req.params) } my model.blog.js file const mongoose = require('mongoose') const Schema = mongoose.Schema; let blogSchema =new Schema( { blogId :{ type: string, unique:true }, mongoose.model('Blog',blogSchema); my routing file const express =require('express') //here we can find routees logic path const control =require('./../controllers/controller') let setRouter =(app) =>{ //here we are getting our logics and assigning for a Http verbs (get,post,put,del) app.get('/test/route/:param1/:param2',control.testRoute) app.get('/example',control.example) // app.post('/hello', control.postmethod) } module.exports={ setRouter:setRouter } Can anyone help me out of this error
{ "language": "en", "url": "https://stackoverflow.com/questions/54901518", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Saving file to remote domain I'd like to host an uploading script on one server but have it store the uploaded files to a remote server. Currently I have a script that saves to a writable folder on my server. This works fine, but when I change it to the absolute link (ie. "http://www.somedomain.com/uploads/" instead of "/uploads/") it says the folder is not writable. The permissions on the folder are 0777. Am I doing something wrong? Eventually I would like to save the uploads to a remote server (ie. "http://www.someotherdomain.com/uploads/"). Any insights? How could I do this with password permissions to eliminate the potential for anybody to upload files to this folder? Thanks in advance! A: Following is an option: Upload a file temporarily to your server. Once uploaded to localhost, use curl to upload the file to remote server. For password protection you can use an access token which expires every 1 hour or so. Pass access_token as a variable with your upload request. Remote server verifies that access_token exists and has not expired before accepting the upload. Set a username and password for the access. If access token does not exist or has expired use curl to post username and password to remote server, which will verify if username and password are valid and returns new access_token. A: Try in via ftp http://php.net/manual/de/book.ftp.php A: I think I have ever experience this problem. If I am not wrong to understand your issue, my issue is like this. I create upload.php in server A and receive in server A too, let's say the file is receive.php (it works normally). Then I upload the receive file (receive.php) to server B, and modify the upload.php in server A (which is the upload.php destination's is server B). Is it the issue? If the issue like this, it might be firewall issue. But the server that I use both of them is centos. What I do then is, I switch off selinux, and use firehol to adjust the firewall in my centos. Then it's work fine. Other option, you can still receive file in your server A. Then in your receive you transfer the file via ftp to server B, but I think this need more effort to do. Cause you need to adjust the ftp configuration (is it ftp, sftp, or sftp using pem / pkk).
{ "language": "en", "url": "https://stackoverflow.com/questions/5688778", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: How does this print a reversed linked list How does this piece of code print a linked list reversed? I'm pretty curious how the new list comes to this way. class Empty: def __init__ (self): self.IsEmpty = True Empty = Empty() class Node: def __init__ (self,value,tail): self.IsEmpty = False self.value = value self.tail = tail l = Node(1,Node(2,Node(3,Node(4,Empty)))) c = l nl = Empty while not l.IsEmpty: nl = Node(l.value,nl) l = l.tail while not nl.IsEmpty: print(nl.value) nl = nl.tail A: It doesn't print reversed, nl is built reversed: while not l.IsEmpty: nl = Node(l.value,nl) l = l.tail each new nl is the tail of the next one. So 1 is the tail for 2, and so on. A: Think about what is happening in the first while loop. It builds a new list in reverse. We start with Empty. Then each iteration: new_list = Node(l.current_value, Node(l.previous_value)) Where previous_value is the value encountered first while iterating through the original list. So, this could be expanded to: Node(l.last_value, Node(l.second_to_last, Node(...Node(l.first_value, Empty)...))) A: It builds a forwards list l = Node(1,Node(2,Node(3,Node(4,Empty)))) Then builds a backwards list from that forwards list nl = Empty while not l.IsEmpty: nl = Node(l.value,nl) l = l.tail Then prints that list out in order, which is the reverse of the first list. This is a pretty convoluted way of doing things. Better would be something recursive, like: def printer(curr): if curr.isEmpty: return printer(curr.tail) print(curr.value)
{ "language": "en", "url": "https://stackoverflow.com/questions/41173195", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Chrome extensions disable reopening of an extension created tab I couldn't find any similar question to this, but is it possible to create a new tab within chrome extension (using chrome.tabs.create) and then after closing it using the same extension prohibit user from reopening it using ctrl+shift+t or undo close tab command? A: You can open an incognito tab; it will have the requested behavior. I don't think you can clear session data, and simply clearing history does not prevent reopening.
{ "language": "en", "url": "https://stackoverflow.com/questions/40947193", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Printing Average Score for Unique ID's I have a table id | playerID | score 1 | 1 | 100 2 | 1 | 155 3 | 5 | 132 etc.. What I want to do is get the Average 'score' for each unique playerID. I can get the DISTINCT playerIDs SELECT DISTINCT playerID FROM dbo.scores and I can get the average of all scores, SELECT AVG(score) FROM dbo.scores but I can't seem to figure out how to combine the two. A: Use group by! SELECT playerID, AVG(score) AS avg_score FROM dbo.scores GROUP BY playerID A: The use of dbo suggests that you are using SQL Server. SQL Server does an integer average of integer values, so the average of 0 and 1 is 0, not 0.5. I would recommend: SELECT s.playerID, AVG(10. * s.score) AS avg_score FROM dbo.scores s GROUP BY s.playerID
{ "language": "en", "url": "https://stackoverflow.com/questions/65281987", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: running bash shell code in IPython notebook I am trying to run a code in jupyter notebook Python3 see below: %% bash rm rvd2.txt rm rvd22.txt rm lsfdout.lsf cat wrench.txt | sed 's/[[:space:]]/\n/g' | sed 's/^[ \t]*//' | sed 's/[ \t]*$//' | \ sed '/^$/d'| tr -cd '[:alnum:] [:space:]' >> rvd2.txt awk 'length>3' < rvd2.txt > rvd22.txt cat rvd22.txt | sort | uniq -c | sort -nr | head -n 250 > lsfdout.lsf The error I get is this, File "<ipython-input-33-7c6457f6d2eb>", line 2 %% bash ^ SyntaxError: invalid syntax I am totally out of clue why this happens, as a multiline code is supposed to be using double percent sign before bash
{ "language": "en", "url": "https://stackoverflow.com/questions/49755433", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Java Packages and Subpackages printed in alphabetical order I need to get Packages and Subpackages of Java printed in alphabetical order. I did this: import java.util.Arrays; public class J0602 { public static void main (String args[]) { Package[] packs = Package.getPackages(); String[] packageNames =new String[packs.length]; int i=0; for (Package pack:packs){ packageNames[i] = pack.getName(); System.out.println(pack.getName()); i++; } Arrays.sort(packageNames); } } ..but it doesn't work. Is there anything I'm missing about Packages? Why Arrays.sort(); doesn't work here? Thank you in advance! A: It could be because you are Sorting your array after you have printed out the elements. Try arranging your code this way Arrays.sort(packageNames); for (Package pack:packs){ System.out.println(pack.getName()); } Alternatively you could Dump your array in a TreeSet and Iterate through it vis tr TreeSet<Package> packages = new TreeSet<Package>(Arrays.asList(packageNames)); then for (Package pack:packages){ System.out.println(pack.getName()); } Note that this will remove duplicate packages from your array.
{ "language": "en", "url": "https://stackoverflow.com/questions/14936466", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: Show Image after choosing it from html form I am trying to show picture after choosing it from html form following this code: http://jsfiddle.net/LvsYc/ and my code is: <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags --> <meta name="description" content=""> <meta name="author" content=""> <link rel="icon" href="bootstrap/favicon.ico"> <title>Image Test</title> <link href="bootstrap/dist/css/bootstrap.min.css" rel="stylesheet"> <script src="bootstrap/jquery.min.js"></script> <link href="bootstrap/signin.css" rel="stylesheet"> <script> function readURL(input) { if (input.files && input.files[0]) { var reader = new FileReader(); reader.onload = function(e) { $('#blah').attr('src', e.target.result); } reader.readAsDataURL(input.files[0]); } } $("#imgInp").change(function() { readURL(this); }); </script> </head> <body> <div class="container"> <form id="form12" runat="server"> <input type='file' id="imgInp" /> <img id="blah" src="#" alt="your image" /> </form> <script src="../../assets/js/ie10-viewport-bug-workaround.js"></script> </body> </html> But the chosen image is not shown. What am I doing wrong? It looks almost like the example above.
{ "language": "en", "url": "https://stackoverflow.com/questions/36356610", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Duplicate property '' for [simple type, on Deserialization I'm currently facing an issue using Jackson 2.4.4 with the xml module. The XML I want to deserialize looks like this: <product> <sku>1000668-1</sku> <name/> <image>/url/or/something.jpg</image> <brand>test</brand> <sizeCM>36 mm / 19.5 cm</sizeCM> <colors> <color id="335061" name="Green"/> </colors> <genders> <gender id="362843" name="M"/> </genders> <occasions> <occasion id="322620" name="First"/> <occasion id="322621" name="Second"/> <occasion id="322627" name="Thrid"/> <occasion id="322628" name="..."/> <occasion id="322630" name="next"/> <occasion id="369680" name="and again"/> </occasions> <categories> <category id="CGO_010_002" name="Stackoverflow"/> </categories> </product> And my Product Class looks like this: @JsonInclude(JsonInclude.Include.NON_NULL) @JsonIgnoreProperties(ignoreUnknown = true) @JacksonXmlRootElement(localName = "product") @JsonPropertyOrder({ "sku", "image", "brand", "sizeCM", "colors", "genders", "occasions", "categories" }) public class Product { @JsonProperty("sku") @JacksonXmlText private String sku; @JsonProperty("image") @JacksonXmlText private String image; @JsonProperty("brand") @JacksonXmlText private String brand; @JsonProperty("sizeCM") @JacksonXmlText private String sizeCM; @JsonProperty("colors") @JacksonXmlProperty(localName = "colors") private Colors colors; @JsonProperty("genders") @JacksonXmlProperty(localName = "genders") private Genders genders; @JsonProperty("occasions") @JacksonXmlProperty(localName = "occasions") private Occasions occasions; @JsonProperty("categories") @JacksonXmlProperty(localName = "categories") private Categories categories; // setter & getter ... Next step was to map it during reading it from a file: public static void main(String[] args) { JacksonXmlModule module = new JacksonXmlModule(); XmlMapper xmlMapper = new XmlMapper(module); xmlMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); product(xmlMapper); } public static void product(XmlMapper xmlMapper){ String s = "/tmp/product.xml"; Product test = null; try { test = xmlMapper.readValue(new File(s), Product.class); } catch (Exception e) { e.printStackTrace(); } System.out.println(test.getSku()); } After trying it like that I facing this exception: com.fasterxml.jackson.databind.JsonMappingException: Duplicate property '' for [simple type, class com.example.jackson.model.Product] at com.fasterxml.jackson.databind.deser.DeserializerCache._createAndCache2(DeserializerCache.java:266) at com.fasterxml.jackson.databind.deser.DeserializerCache._createAndCacheValueDeserializer(DeserializerCache.java:241) at com.fasterxml.jackson.databind.deser.DeserializerCache.findValueDeserializer(DeserializerCache.java:142) at com.fasterxml.jackson.databind.DeserializationContext.findRootValueDeserializer(DeserializationConexample.java:394) at com.fasterxml.jackson.databind.ObjectMapper._findRootDeserializer(ObjectMapper.java:3169) at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:3062) at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:2115) at com.example.jackson.main.TheMain.product(TheMain.java:32) at com.example.jackson.main.TheMain.main(TheMain.java:23) Next thing is - same Method - same ObjectMapper - another pojo + xml works fine (even the list's). Any Help or Hint wanted, I really don't know what I should do - because the exception Duplicate property '' isn't so great because the '' are really empty! A: Solution for this was that I switched from @JacksonXmlTextto @JacksonXmlProperty. I misunderstood how @JacksonXmlTextshould be used. @JsonInclude(JsonInclude.Include.NON_NULL) @JsonIgnoreProperties(ignoreUnknown = true) @JacksonXmlRootElement(localName="product") @JsonPropertyOrder({ "sku", "image", "brand", "sizeCM", "colors", "genders", "occasions", "categories" }) public class Product { @JsonProperty("sku") @JacksonXmlProperty(localName="sku") private String sku; @JsonProperty("image") @JacksonXmlProperty(localName="image") private String image; @JsonProperty("brand") @JacksonXmlProperty(localName="brand") private String brand; @JsonProperty("sizeCM") @JacksonXmlProperty(localName="sizeCM") private String sizeCM; @JsonProperty("colors") @JacksonXmlProperty(localName = "colors") @XmlElement(name="colors") private Colors colors; Allowed me to parse the xml without any problem.
{ "language": "en", "url": "https://stackoverflow.com/questions/28488937", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: union in c++ with a single non trivial type I have a simple struct that can carry either a result, or error, never both. Both are the same type, but I want two members just for clarity. From reading cppreference.com it looks like the following code snippet would be valid c++? With a placement delete in the union destructor to tidy up the non trivial class (std::string in this instance). struct Result { union { std::string resultText; std::string errorText; ~(){ resultText.~string();} }; }; It looks like, to use this, the containing struct would need to implement the rule-of-5 members to explicitly copy/move resultText. A: A union is just going to decrease readability of your code. And depending on how you use it will increase maintenance too. Actually the fact that you mentioned "implementing the rule of 5" despite having a std::string member suggests that your class is going to be a nightmare to maintain. I would look at these options (not enough detail in the question to determine what would be best): * *Use an exception. You can make a custom exception by deriving from std::exception *Use Boost.Optional. boost::optional<std::string> do_something() { ... }; std::string result = do_something().value_or("error!");
{ "language": "en", "url": "https://stackoverflow.com/questions/37167417", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Updating a Server Side Text File via Android I'm building an app that needs to periodically append lines to a server side text file. So far, the best way I've come up with for doing this is using the Dropbox API, where the user has to download the text file, update it, and then upload it back - obviously this is not ideal. What would be the best (free) way to do something like this? I'd like a solution where I don't have to personally host a server, but can use some third party cloud (like Dropbox). A: Google's Android Backup Service seems appropriate for this, and is free.
{ "language": "en", "url": "https://stackoverflow.com/questions/16513967", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to use XCode Distribute App Development Method when i archive and start to distribute my app in Xcode, there is 4 choice App Store Connect, Ad Hoc, Enterprice and Development. i've been wondering how to use the development method, i have upload all the file generated from the xcode to my site but it just return error "The server encountered something unexpected that didn't allow it to complete the request", of course i open the url using safari. i also have check the box "include manifest for over the air installation" but i have no idea how to use this. most tutorial is only upload to app store or ad hoc. just wondering how this development thingy work Is there any addition work to do this?
{ "language": "en", "url": "https://stackoverflow.com/questions/67054241", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: CDI Injection into a Servlet not working I have a Controller with a producer. @Named @SessionScoped public class UserController{ private User user; //other methods @Produces @User public User produceUser() { return user; } } If I inject the user into a Servlet, I get always the same user(I compared the object IDs) - also in different sessions. If I inject the User in a CDI Bean, it's working and I get the user of the current session. A: UserController is session-scoped, but the producer is not. I.e. the producer has @Dependent scope, so the User bean gets injected once when the servlet is initialized. Try adding @SessionScoped to your producer method.
{ "language": "en", "url": "https://stackoverflow.com/questions/24647516", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Setting global array from inside readFile I'm probably missing something simple here, but for some reason, when I set an array's value from inside a function, I can no longer read that array once outside of that function. var threadArray = []; function getThreads() { var fs = require('fs'); // read list of threads fs.readFile('./database/threadList.txt', function(err, data) { var threadIds = data.toString().split("\n"); for(i in threadIds) { threadArray[i] = threadIds[i].split(","); } console.log("This works: " + threadArray[0]) }) console.log("This does not work: " + threadArray[0] + " Returns [undefined]") } What am I missing here? I'm assuming something to do with the way I declared the array? A: This is a timing issue. fs.readFile is an asynchronous operation - your second console.log that doesn't work is getting processed immediately after fs.readFile starts running and your threadArray is not yet populated. You can use fs.readFileSync instead try { var threads = fs.readFileSync('./database/threadList.txt'); var threadIds = threads.toString().split('\n'); for(i in threadIds) { threadArray[i] = threadIds[i].split(","); } console.log("This works: " + threadArray[0]); } catch (e) { console.error("Error reading file: ", e); }
{ "language": "en", "url": "https://stackoverflow.com/questions/42839588", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Responsive image shrink I have somewhat of a dilemma right now with responsive images. Right now, the amount of images shown per pixel is correct, however the images seem to shrink tremendously. Is there something I can do to fix this? img { max-width: 200%; height: auto; margin: 0 0 10px 0; } /* Section Inner */ div.section-inner { max-width: 1100px; height: auto padding: 0 75px; margin: 0 auto; } /* Body Content */ div.body-content { padding: 50px 0; background-color: #FFF; } /* Thirds */ div.thirds { padding-bottom: 50px; } div.one-third { width: 15%; float: left; margin-right: 5%; } div.one-third-last { margin: 0; } @media screen and (max-width: 1000px) { div.one-third { width: 30%; } div.one-third-second { margin: 0; } div.one-third-last { margin: 0; } img { width: 100%; height: auto; } } div.nav ul li { width: 25%; border-bottom: 1px solid #bababa; } @media screen and (max-width: 600px) { div.nav ul li { width: 33%; } div.one-third { width: 50%; margin: 0; } div.one-third-second { margin: 0; } } @media screen and (max-width: 500px) { div.nav ul li { width: 33%; } div.one-third { width: 33%; margin: 0; } div.one-third-second { margin: 0; } } <!-- header --> <!-- body-content --> <div class="body-content"> <div class="section-inner"> <!-- thirds --> <div class="thirds clearfix"> <!-- one-third --> <div class="one-third mobile-collapse"> <figure> <img src="https://via.placeholder.com/1100x800" alt="China" width="1000" height="750"> <figcaption>Chinese_Dragon</figcaption> </figure> </div> <!--/one-third--> <!-- one-third --> <div class="one-third one-third-second mobile-collapse"> <figure> <img src="https://via.placeholder.com/1100x800" alt="Gringotts" width="1000" height="750"> <figcaption>Gringotts_dragon</figcaption> </figure> </div> <!--/one-third--> <!-- one-third --> <div class="one-third one-third-last mobile-collapse"> <figure> <img src="https://via.placeholder.com/1100x800" alt="Hydra" width="1000" height="750"> <figcaption>Hydra</figcaption> </figure> </div> <div class="one-third one-third-last mobile-collapse"> <figure> <img src="https://via.placeholder.com/1100x800" alt="Ice" width="1000" height="750"> <figcaption>Ice_dragon</figcaption> </figure> </div> <div class="one-third one-third-last mobile-collapse"> <figure> <img src="https://via.placeholder.com/1100x800" alt="Monday" width="1000" height="750"> <figcaption>The "I_Hate_Mondays" Dragon</figcaption> </figure> </div> <div class="one-third one-third-last mobile-collapse"> <figure> <img src="https://via.placeholder.com/1100x800" alt="Sassy" width="1000" height="750"> <figcaption>Sassy_Dragon</figcaption> </figure> </div> <!--/one-third--> </div> <!--/thirds--> <!-- two-columns --> </div> </div> <!--/body-content--> <!-- footer -->
{ "language": "en", "url": "https://stackoverflow.com/questions/73897314", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to send array of data to controller with ajax in laravel I want send arrays of data to back-end at once but i can't. issue 1. this is what i send currently array:5 [ "_token" => "S5s5ZTTnnP93MyXgCql0l9vhHsiqt5VWaFyEedXj" "product_id" => "21" "specification_id" => "6" "text_dec" => "1" "longtext_dec" => null ] It should be like: Array [ 0 = [ data ] 1 = [ data ] 2 = [ data ] ] *I always get same ID as specification_id while each row in my blade has different ID Code appending script <script defer> $(document).ready(function() { //select the category $('select[name="selectset"]').on('change', function() { var id = $(this).val(); if(id) { $.ajax({ url: '{{ url('admin/selectset') }}/'+encodeURI(id), type: "GET", dataType: "json", success:function(result) { //sort the results result.sort(function(a,b) { return (a.position > b.position) ? 1 : ((b.position > a.position) ? -1 : 0); }); $.each(result, function(key1, value1) { var vvvid = value1.id; //textfield and textareafield are part of my issue (appended rows) if(value1['type'] == 'textfield'){ var my_row = $('<div class="row mt-20 ccin">'); $('div#dataaa').append(my_row); }else{ var my_row = $('<div class="row mt-20 ccin">'); $('div#dataaa').append(my_row); } // second data (get values) $.ajax({ url: '{{ url('admin/findsubspecification') }}/'+value1['id'], type: "GET", dataType: "json", success:function(data) { // Check result isnt empty var helpers = ''; $.each(data, function(key, value) { helpers += '<option value="'+value.id+'">'+value.title+'</option>'; }); //this is the part of my issue if(value1['type'] == 'textfield'){ var my_html = '{{ Form::open() }}<input name="product_id" id="product_id" type="hidden" value="{{$product->id}}"><input name="specification_idd" class="specification_idd" id="specification_idd" type="hidden" value="'+vvvid+'"><div class="col-md-4">'+value1.title+'</div>'; my_html += '<div class="col-md-6"><input id="text_decc" name="text_decc" placeholder="text field" class="text_decc form-control"></div>'; my_html += '<div class="col-md-2"><button type="button" id="custmodalsaveee" class="custmodalsaveee btn btn-xs btn-success">Save</button>{{Form::close()}}</div>'; my_row.html(my_html); }else{ //second part of my issue var my_html = '{{ Form::open() }}<input name="product_id" id="product_id" type="hidden" value="{{$product->id}}"><input name="specification_idd" class="specification_idd" id="specification_idd" type="hidden" value="'+vvvid+'"><div class="col-md-4">'+value1.title+'</div>'; my_html += '<div class="col-md-6"><textarea id="longtext_decc" name="longtext_decc" placeholder="text area field" class="longtext_decc form-control"></textarea></div>'; my_html += '<div class="col-md-2"><button type="button" id="custmodalsaveee" class="custmodalsaveee btn btn-xs btn-success">Save</button>{{Form::close()}}</div>'; my_row.html(my_html); } } }); // second data }); } }); } }); }); </script> result of code above is like: saving script the part that should be fixed <script> $(document).ready(function() { $("body").on("click", ".custmodalsaveee", function(e){ var id = $('input[name="product_id"]').val(); $.ajax({ type: "post", url: "{{ url('admin/addnewcustomsubspecifications') }}", data: { '_token': $('input[name=_token]').val(), 'product_id': id, 'specification_id': $('.specification_idd').val(), 'text_dec': $('.text_decc').val(), 'longtext_dec': $('.longtext_decc').val(), }, success: function (data) { alert('Specification added successfully in your product!'); }, error: function (data) { console.log('Error!', data); } }); }); }); </script> controller public function addnewcustomsubspecifications(Request $reqss){ dd($reqss->all()); // $this->validate($reqss, array( // 'product_id' => 'required', // 'specification_id' => 'required', // 'text_dec' => 'nullable', // 'longtext_dec' => 'nullable', // )); // $add = CustomProductSpecification::create([ // 'product_id' => $reqss->product_id, // 'specification_id' => $reqss->specification_id, // 'text_dec' => $reqss->text_dec, // 'longtext_dec' => $reqss->longtext_dec, // ]); // $parent = Specification::where('id', '=', $reqss->specification_id)->first(); // return response()->json(array('data'=>$add,'parent'=>$parent)); } Any idea? Update html output Update2 So based on suggestions i've used .map() here is my code and the results script $(document).ready(function() { $("body").on("click", ".custmodalsaveee", function(e){ var id = $('input[name="product_id"]').val(); var specification_idd = $( ".ccin" ).map(function() { return $( this ).find('.specification_idd').val(); return $( this ).find('.text_decc').val(); return $( this ).find('.longtext_decc').val(); }).get(); var text_decc = $( ".ccin" ).map(function() { return $( this ).find('.text_decc').val(); }).get(); var longtext_decc = $( ".ccin" ).map(function() { return $( this ).find('.longtext_decc').val(); }).get(); console.log(specification_idd); console.log(text_decc); console.log(longtext_decc); $.ajax({ //rest of it as it was... and the console results Question * *How do i get related results together? specification_id and text fields as 1 array *how I avoid of empty values? if text_dec and longtext_dec are empty for each specification_id doesn't need to be send example specification 40 doesn't have any value in longtext_dec or text_dec no need to be send A: Robert, you should directly return view from your Ajax call in your laravel method and just bind html response from the view with your new data. That is pretty easy way of doing it.
{ "language": "en", "url": "https://stackoverflow.com/questions/52446532", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Best practices for using containers I develop a Vaadin application which has to deal with a lot of tables in its UI. Most of the tables use sensitive data which is updated frequently. Connectivity to the database is acquired using SQLContainers, therefore each UI table is binded to one of these SQLContainers. Some of these database tables have to be displayed in different contexts with different filters. The UI is based mostly on tabsheets so sometimes one database table has to be in a few tabs simultaneously (but with different filters). I tried updating the filters on tab selection change, but this solution doesn't look clean. What is the best approach for displaying one database table in many places when only one of these tables is visible at any given time? A: Usually, you have different containers for different table instances. Although, in some cases, you may want to share the same container instance between different components. It is totally possible and acceptable, as long as you understand the consequences: Filtering and sorting is done on the container level, meaning, that if you apply a filter on the container in one view and then navigate to another view, the container will be filtered there as well. Not understanding this may lead to "weird bugs" and lots of WTFs. The benefits of sharing the same container instance has to do with minimizing the memory footprint of your application - the more containers you have, the more memory you will consume. Note that both the table and the SQLContainer are lazy loading - meaning the table won't render more rows to the browser than what is needed to fill the table's area (+ some buffer), the SQLContainer won't fetch more rows than what are needed by the table --> your container won't actually contain in-memory more than a few dozen of items (* your mileage may vary). From a performance perspective (CPU), in your case, I don't see much benefit from sharing the same container instance in multiple views, since every time you switch a view, you need to apply new filters, thus triggering a new database query and fetching the needed data every time you switch views - even when going back to a view that was previously already filtered. So how about that best practice? Personally, I'd start with multiple container instances (one per view), do some profiling and optimize if needed. Premature optimization is the root of all evil. A: I don't believe it is possible to use the same container instance in multiple tables with different filter - (not 100% sure, but it's very strong instinct) With that in mind, I'd be inclined to do something like * *Create/use some kind of event bus to broadcast/subscribe messages saying "I've updated table XYZ" *Create an extension of SQLContainer overrides #fireContentsChange to broadcast when the table is updated, and that also reacts to the eventbus, calling #fireContentsChange (if the sourve of the event bus message isn't this) There's probably a more sophisticated/better way of doing this with a single shared Container.ItemSetChangeEvent, but it's tricky to think this through when typing into a browser text box. In short, on all containers, you want to propogate the ItemSetChangeEvent to all of the other containers that look at the same underlying table.
{ "language": "en", "url": "https://stackoverflow.com/questions/18822957", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Remove HttpContext.Current.Session I have an application which stores session variables. When I do the logout I call the RemoveAll() method on available sessions. The method seems not working. Do you know how it is possible to force removing a Session variable? Regards. A: Session.Abandon() cancels the current session Session.Clear() will just clear the session data and the the session will remain alive more Details: Session.Abandon() method destroys all the objects stored in a Session object and releases their resources. If you do not call the Abandon method explicitly, the server destroys these objects when the session times out(I may add:Session_OnEnd event is triggered) http://msdn.microsoft.com/en-us/library/ms524310.aspx Session.Clear() just removes all values (content) from the Object. The session with the same key is still alive.
{ "language": "en", "url": "https://stackoverflow.com/questions/6927766", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Serialize data on mysql data types What is the best data types for serialize data? A: if you know how long the serialized data will be you can use varchar, otherwise id use text. it might just be best to use text anyways. A: It depends on how big the data you want to serialize is. It could be text or longtext. Btw, very often (but not always) storing of serialized data is a bad design, which should be reimplemented using N:M or 1:N (many-to-many or one-to-many) relations A: If the data is just a generic pile of bytes, such as an image, then use a BLOB. If it's a pile of text, use one of the TEXT types. Otherwise, it depends upon what kind of data you're dealing with.
{ "language": "en", "url": "https://stackoverflow.com/questions/5671981", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: android - "id cannot be resolved or is not a field" - error after cleaning project Picture one: http://www.directupload.net/file/d/3572/gkx2b7ge_jpg.htm Picture two: http://www.directupload.net/file/d/3572/knljgb8m_jpg.htm Hey Community. I have a Problem as follows: After i cleaned my Project Test2 in Eclipse, Eclipse doesn`t seem to find any views or xml files from R.java anymore. The Problem message for every view or xml: "view name or xml" cannot be resolved or is not a field. What i've tried so far: * *I cleaned the project several times, and built it again - doesn't work. *I disabled automatic building and tried again - does´t work. *I deleted the project from the workspace and imported it again - doesn't work. *I deleted Eclipse, set up a whole new workspace and imported my project - doesn't work. I tried this solution ("id cannot be resolved or is not a field" error?) checking if i imported R manually. Which i did. After i took it out of the code the problem is still there though. Trying to update Eclipse failed. It seems to not find any updated. My code was working fine just before i cleaned the Project. As you can see in the second Picture, there is no errors concerning any other Problems. A: If R does not generate after a build anymore. It means that you have errors in your xml files. Try right click on your project -> click Android Tools -> Fix Project Properties
{ "language": "en", "url": "https://stackoverflow.com/questions/22624192", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Display the message written in log file on webpage after every 3 seconds So i have built an web application which perform a task which may take upto 10 minutes. I want to show the current status to user on the webpage. I have log.info(), log.debug() and log.error() message used within my webapp for logging the status. How should i go about displaying the log message on webpage using minimum effort. ? A: Look at extending log4j classes http://logging.apache.org/log4j/2.x/manual/extending.html In you custom loggers you can also write to the web page as well as keeping normal log4j functionality and configuration.
{ "language": "en", "url": "https://stackoverflow.com/questions/20367638", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: SQL query with "group by with cube" and NULL values I have a table like: +------+------+------+ | col1 | col2 | col3 | +------+------+------+ | A | 1 | foo | | A | 1 | foo | | A | 2 | foo | | B | 1 | foo | | B | 2 | foo | | B | NULL | foo | | NULL | 1 | foo | +------+------+------+ I want to see numbers of foo grouped by col1 and col2: +-------+---+---+------+-------+ | | A | B | NULL | TOTAL | +-------+---+---+------+-------+ | 1 | 2 | 1 | 1 | 4 | | 2 | 1 | 1 | 0 | 2 | | NULL | 0 | 1 | 0 | 1 | | TOTAL | 3 | 3 | 1 | 7 | +-------+---+---+------+-------+ I use a query like this: select col1, col2, count(col3) from table group by col1, col2 with cube And I have 4 rows with col1, col2 and NULL that say for NULL/NULL, NULL/TOTAL, TOTAL/NULL, TOTAL/TOTAL but the totals for sql has NULL value. Is possible set a custom value different from NULL for the totals in the query? A: I would use some conditional aggregation for this as well as a subquery since you want to use the "null" as an actual value. select col2 = Isnull(col2, 'Total'), A = sum(case when col1 = 'A' then 1 else 0 end), B = sum(case when col1 = 'B' then 1 else 0 end), NullVal = sum(case when col1 = 'Null' then 1 else 0 end), count(col1) Total from ( select col1 = Isnull(col1, 'Null'), col2 = isnull(cast(col2 as varchar(5)), 'Null'), col3 from yourtable ) d group by col2 with cube; See SQL Fiddle with Demo. This uses a CASE expression to get the totals for both the A, B, and null values in Col1 and then uses the CUBE to rollup the totals. Giving the result: | COL2 | A | B | NULLVAL | TOTAL | |-------|---|---|---------|-------| | 1 | 2 | 1 | 1 | 4 | | 2 | 1 | 1 | 0 | 2 | | Null | 0 | 1 | 0 | 1 | | Total | 3 | 3 | 1 | 7 |
{ "language": "en", "url": "https://stackoverflow.com/questions/26143339", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: docker-compose set environment per-service profile I recently discovered docker-compose profiles, which seem great for allowing optional local resources for testing However, it's not clear if it's possible to provide a container with a different environment depending on the profile; what is a sensible way (if any) to switch environmental vars by-service profile? Perhaps * *using extends (which appears deprecated, but may work for me anyways Extend service in docker-compose 3) *the profile value is or can be made available to the container so it can switch internally *this was never intended or considered in the design (probe local connection on startup, volume mounting tricks..) Specifically, I'm trying to prefer an address and some keys via env var under some testing profile, but prefer a .env file otherwise. Normal structure services: webapp: ... env_file: - .env Structure with test profile services: db-service: image: db-image profiles: ["test"] ... webapp: ... environment: - DATABASE_HOST=db-service:1234 A: I can say with certainty that this was never an intended use case for profiles :) docker-compose has no native way to pass the current profile down to a service. As a workaround you could pass the COMPOSE_PROFILES environment variable to the container. But this does not work when specifying the profiles with the --profiles flag on the command line. Also you had to manually handle having multiple active profiles corretly. The best solution for your specific issue would be to have different services for each profile: services: webapp-prod: profiles: ["prod"] #... env_file: - .env db-service: image: db-image profiles: ["test"] #... webapp-test: profiles: ["test"] #... environment: - DATABASE_HOST=db-service:1234 This only has the downside of different service names for "the same" service with different configurations and they both need assigned profile(s) so none of them will start by default, i.e. with every profile. Also it has some duplicate code for the two service definitions. If you want to share the definition in the file you could use yaml anchors and aliases: services: webapp-prod: &webapp profiles: ["prod"] #... env_file: - .env webapp-test: <<: *webapp profiles: ["test"] environment: - DATABASE_HOST=db-service:1234 db-service: image: db-image profiles: ["test"] #... Another alternative could be using multiple compose files: # docker-compose.yml services: webapp: #... env_file: - .env # docker-compose.test.yml services: db-service: image: db-image #... webapp: environment: - DATABASE_HOST=db-service:1234 This way you can start the production service normally and the instances by passing and merging the compose files: docker-compose up # start the production version docker-compose -f docker-compose.yml -f docker-compose.test.yml # start the test version A: Arcan's answers has a lot of good ideas. I think another solution is to just pass a variable next to your --profile tag on your docker commands. You can then for instance set an -e TESTING=.env.testing in your docker-compose command and use env_file:${TESTING:-.env.default} in your file. This allows you to have a default env file added on any none profile actions and runs the given file when needed. Since I have a slightly different setup I am adding a single variable to a container in my docker-compose so I did not test if it works on the env-file: attribute but I think it should work.
{ "language": "en", "url": "https://stackoverflow.com/questions/68549227", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: R data.table to calculate new columns from existing columns bases in certain conditions Let's say I have the following data table: dta <- data.table( criteria = c('A', 'A', 'B', 'A', 'A', 'B'), phase = list('block3', c('block1', 'block2'), 'block2', 'block2', 'block3', 'block1'), start_val = c(12.0, 1.0, 7.0, 7.0, 12.0, 1.0), end_val = c(15.0, 11.0, 11.0, 11.0, 15.0, 6.0), max_val = c(13.0, 8.0, 9.5, 11.0, 15.0, 6.0) ) from which I need the resulting table with two additional column's, cor_start and cor_end dtb <- data.table( criteria = c('A', 'A', 'B', 'A', 'A', 'B'), phase = list('block3', c('block1', 'block2'), 'block2', 'block2', 'block3', 'block1'), start_val = c(12.0, 1.0, 7.0, 7.0, 12.0, 1.0), end_val = c(15.0, 11.0, 11.0, 11.0, 15.0, 6.0), max_val = c(13.0, 8.0, 9.5, 11.0, 15.0, 6.0), cor_start = c(12.0, 1.0, 8.0, 9.5, 13.0, 6.0), cor_end = c(13.0, 8.0, 9.5, 11.0, 15.0, 6.0) ) the new columns need to be calculated with reference to phases column by checking if there is any previous row with the current matching phase value. For better understanding, in this example: * *row 3 has a matching phase of block2 in row 2 *row 4 has a matching phase of block2 in row 3 *row 5 has a matching phase of block3 in row 1 *row 6 has a matching phase of block1 in row 2 however row 1 and row 2 have no previous matching phase rows. Note that the phase is of type list. So, when there is a previous matching row, below are the conditions: if (max_val in previous matching row is < end_val in current row) cor_start = previous matching row max_val cor_end = current row end_val if (max_val in previous matching row is > end_val in current row) cor_start = current row end_val cor_end = current row end_val and when there is no previous matching row, below are the conditions: cor_start = current row start_val cor_end = current row max_val I looked into shift(), but could not figure out on how to set the above conditions ? Thanks! A: Something like: dta_transformed <- dta[,.(rn = .I, phase = unlist(phase)), by = setdiff(names(dta), 'phase')][ , shifted_max := shift(max_val), by = phase][ shifted_max < end_val, `:=` (cor_start = shifted_max, cor_end = end_val), by = phase][ shifted_max > end_val, `:=` (cor_start = end_val, cor_end = end_val), by = phase][ is.na(cor_start), `:=` (cor_start = start_val, cor_end = max_val), by = phase][ , phase := paste(phase, collapse = ","), by = rn][!duplicated(rn),][ , c("rn", "shifted_max") := NULL] However, the output I get is: criteria phase start_val end_val max_val cor_start cor_end 1: A block3 12 15 13.0 12.0 13 2: A block1,block2 1 11 8.0 1.0 8 3: B block2 7 11 9.5 8.0 11 4: A block2 7 11 11.0 9.5 11 5: A block3 12 15 15.0 13.0 15 6: B block1 1 6 6.0 6.0 6 Could it be that in row number 3 the cor_end should be 11 in your desired output? As the previous matching row (2) has lower max_val, therefore the current end_val (11) should be taken? Also the tidyverse approach, slightly more readable: library(tidyverse) dta %>% mutate(rn = row_number()) %>% unnest(phase) %>% group_by(phase) %>% mutate( cor_start = case_when( lag(max_val) < end_val ~ lag(max_val), lag(max_val) > end_val ~ end_val, TRUE ~ start_val ), cor_end = if_else(!is.na(lag(max_val)), end_val, max_val) ) %>% group_by(rn) %>% mutate( phase = paste(phase, collapse = ",") ) %>% ungroup() %>% select(-rn) %>% distinct() A: Here is a different approach which uses pmin() instead of ifelse() and utilises the fill parameter of the shift() function. Furthermore, it reduces the number of grouping operations: library(data.table) dta[, rn := .I] dta[dta[, .(phase2 = unlist(phase)), by = rn], on = "rn"][ , `:=`(cor_start = pmin(shift(max_val, fill = start_val[1]), end_val), cor_end = max_val), by = phase2][ , .SD[1], by = rn][ , c("rn", "phase2") := NULL][] criteria phase start_val end_val max_val cor_start cor_end 1: A block3 12 15 13.0 12.0 13.0 2: A block1,block2 1 11 8.0 1.0 8.0 3: B block2 7 11 9.5 8.0 9.5 4: A block2 7 11 11.0 9.5 11.0 5: A block3 12 15 15.0 13.0 15.0 6: B block1 1 6 6.0 6.0 6.0
{ "language": "en", "url": "https://stackoverflow.com/questions/53265871", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to download files from Folders inside Azure Blob storage? I would like to know how to download files from folders that are created inside azure blob. A schematic diagram is shown below: MyContainer (Container) --> HomeFolder--> Sample.txt (Blob) If There is no folder and only sample.txt file is there, then I am able to download the file, but not when the file is inside a folder. On stackeoverflow, I see most of issues are related to file directly under container. Could any one guide me on above request? 2) Another question is I want to do it via latest azure sdk [Azure.Storage.Blobs], but it would be fine if someone is using [Microsoft.Azure.Storage.Blob] dll. Below code that I am currently writing with [Microsoft.Azure.Storage.Blob] class. class Program { static void Main(string[] args) { string storageAccount_connectionString = "DefaultEndpointsProtocol=https;AccountName=<account key>;EndpointSuffix=core.windows.net"; CloudStorageAccount storageAccount = CloudStorageAccount.Parse(storageAccount_connectionString); CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient(); CloudBlobContainer container = blobClient.GetContainerReference("lbdemocontainers"); string blobPrefix = null; bool useFlatBlobListing = false; var listOfFileNames = new List<string>(); var blobs = container.ListBlobs(blobPrefix, useFlatBlobListing, BlobListingDetails.None); //var folders = blobs.Where(b => b as CloudBlobDirectory != null).ToList(); //foreach (var folder in blobs) //{ // var blob = (CloudBlockBlob)folder; // blob.FetchAttributes(); // listOfFileNames.Add(blob.Name); //} //var downloads = blobs.Select(blob => blob.Uri.Segments.Last()).ToList(); var blobNames = blobs.OfType<CloudBlockBlob>().Select(b => b.Name).ToList(); Console.ReadLine(); } } From above code it provides me Folder name HomeFolder/ only. Thanks in advance
{ "language": "en", "url": "https://stackoverflow.com/questions/60299207", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Flutter - Building for iOS, but the linked and embedded framework 'App.framework' was built for iOS Simulator After updating to Catalina 10.15.4 beta with Xcode 13.4 beta, which also updated Simulator to 13.4 (921.4). The application compiles and runs correctly on a physically attached device, but no simulators of any devices can pass this stage. I got the errors Building for iOS, but the linked and embedded framework 'App.framework' was built for iOS Simulator. or Building for iOS Simulator, but the linked and embedded framework 'App.framework' was built for iOS. How can I fix this? A: Xcode 11.4 changed the way frameworks are linked and embedded, and you may experience issues switching between iOS devices and simulators. Flutter v1.15.3 and later will automatically migrate your Xcode project. To get unstuck, follow the instructions below; * *Quick fix (make your simulator work) rm -rf ios/Flutter/App.framework * *Official recommended Steps to migrate manually * *From the Flutter app directory, open ios/Runner.xcworkspace in Xcode. *In the Navigator pane, locate the Flutter group and remove App.framework and Flutter.framework. *In the Runner target build settings Build Phases > Link Binary With Libraries confirm App.framework and Flutter.framework are no longer present. Also confirm in Build Phases > Embed Frameworks. *Change the Runner target build settings Build Phases > Thin Binary script as follows: /bin/sh "$FLUTTER_ROOT/packages/flutter_tools/bin/xcode_backend.sh" embed /bin/sh "$FLUTTER_ROOT/packages/flutter_tools/bin/xcode_backend.sh" thin *In the Runner target Build Settings > Other Linker Flags (OTHER_LDFLAGS) add $(inherited) -framework Flutter Hope it helps! A: Xcode 11.4 changed the way frameworks are linked and embedded, which is causing issues switching between iOS devices and simulators. Please follow official guide on how to migrate your project. A: After several days trying to find a solution to test the Flutter app on iOS device, I finally found this: flutter clean flutter build ios -Open xCode and run app on your device. A: Updated to Xcode 11.4. Ios 13.4, Iphone X. App just fetches data using API. App started on white screen and then finally crashes, both on simulator and device. I followed the offical guide (I also rm -rf ios/Flutter/App.framework) flutter.dev/docs/development/ios-project-migration. I ran several times flutter clean I also tried deleting Pods/ folder and Podfile.lock, then reinstalling using pod install in the ios folder. As I am using async data I also added as 1st line in main() WidgetsFlutterBinding.ensureInitialized(); No help, app did not started either simulator. Then I removed ios/ and android/ folders. After that in project folder I ran command flutter create . that regenerates mentioned folders. After this my app started fine both on simulator and on device. I hope this would be help to others. NOTE!! if you have done any modifications manually to those folders please take backup or commit beforehand. A: * *Select your Target from "TARGETS" *Select 'Build Settings' *Under 'Build Options' -> Set 'Validate Workspace' To 'YES' *After successfully building, set it back to 'NO' Reason : "In Xcode 12+, the default option for Validate Workspace is internally not set. We need to set it manually to avoid this kind of error. There is no problem in setting back to the default 'NO' option. A: I have tried the solution on the official website of flutter but it didn't work for me, so I found a temporary solution which worked for me, but it took me some hard works: Here is my example with project stuck_framework which is a fresh new project (first time run on the simulator) * *I created 2 folders inside flutter project called "ios_simulator" and "ios_real_device". enter image description here *Now my first build was for the simulator, then I want to switch to a real device, I will move ios folder inside Flutter project to the "ios_simulator" *I open the project with visual studio code and run "flutter create ." and now I will choose a real device to rebuild the project ( if your simulator is online, please quit ). enter image description here *Now I wait for the build finish and run on the real device without any errors. Now I have 2 ios project 1 for simulators and one for real devices. *Next time when I want to run on the simulator again, I just remove the current ios folder and copy the ios folder which I placed on "ios_simulator" back out to flutter project folder. Hope this help A: Manually upgrading flutter to version 1.15 solve this issue as well. Running flutter version v1.15.17 helped me. Also, you can switch to beta or dev channels by running flutter channel command but be sure you check your code against all BC changes... A: In my case, it works only simulator(debug). if you want to deploy your app on the app store(release) i highly recommend you to upgrade flutter version using flutter version v1.15.17 otherwise you would encounter crashed app with white screen. just upgrade flutter version then all things work well A: This error is caused by the Xcode 11.4 and can be resolved by Removing / Re-Embedding frameworks and adding a new Run Script Phase. * *Under General -> "Frameworks, Libraries, and Embedded Content" * *Delete the frameworks that are causing errors. *After deleting, re-embed the frameworks in the same location. *Under Build Phases add a new run script phase. * *Select the "+" button in the "Build Phases" pane to create a "New Run Script Phase". *Confirm the script is the bottommost build phase, and configure its fields. * *The Shell text field should read /bin/sh (which is the default value). *In the text-input area, enter the shell command rm -r "FRAMEWORK_DIRECTORY/YOUR_FRAMEWORK.framework/" A: None of the other solutions here worked for me. In my case, the problem was fixed by searching my project for ONLY_ACTIVE_ARCH and changing them all to YES. I found my solution here: https://developer.apple.com/forums/thread/656509
{ "language": "en", "url": "https://stackoverflow.com/questions/60881764", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "35" }
Q: Convert plaintext to perform elgamal encryption Hi i'm writing a program in java to test a variant of the elgamal encryption, however my problem is not the encryption/decryption chain itself, but how to perform the operations on the input given: a text file. I have a text file with some words in it (for example the content can be: "Hello world, this is a test") and i need to perform numeric operations on them like this: ciphertext= (message * y) mod p where y and p are two biginteger. I tried this conversion chain: (reading one string at time): String->Hexadecimal->Decimal Then perform the encrypt operation, and then the inverse: Decimal->Hexadecimal->String But this doesn't work all the time (i'm currently investigate on this issue). fixed. My question is, there is a better way to do this? I was reading about the byte array's but i'm not sure how to use them. [i can post an example of the encryption/decryption chain if needed] A: BigInteger has a constructor taking a byte array as argument. Any String can be converted to a byte array, without loss, using (for example), UTF-8 encoding: byte[] bytes = string.getBytes(StandardCharsets.UTF_8); Combine both, and you have an easy way to transform a String into a BigDecimal. For the reverse operation, use BigInteger.toByteArray(), and then new String(bytes, StandardCharsets.UTF_8).
{ "language": "en", "url": "https://stackoverflow.com/questions/30647542", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Err HTTP 200 in Node.Js on Windows Server 2012 I created an application that is running correctly, but when run on the server this error is occurring. Server: Windows Server 2012. Any suggestion? iisnode encountered an error when processing the request. HRESULT: 0x2 HTTP status: 500 HTTP subStatus: 1002 HTTP reason: Internal Server Error You are receiving this HTTP 200 response because system.webServer/iisnode/@devErrorsEnabled configuration setting is 'true'. In addition to the log of stdout and stderr of the node.exe process, consider using debugging and ETW traces to further diagnose the problem. The node.exe process has not written any information to stderr or iisnode was unable to capture this information. Frequent reason is that the iisnode module is unable to create a log file to capture stdout and stderr output from node.exe. Please check that the identity of the IIS application pool running the node.js application has read and write access permissions to the directory on the server where the node.js application is located. Alternatively you can disable logging by setting system.webServer/iisnode/@loggingEnabled element of web.config to 'false'.
{ "language": "en", "url": "https://stackoverflow.com/questions/60798886", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: What is _GLIBCXX_USE_NANOSLEEP all about? A preprocessor macro called _GLIBCXX_USE_NANOSLEEP appears in two standard header files: * *c++/4.7.1/x86_64-unknown-linux-gnu/bits/c++config.h *c++/4.7.1/thread In a default build of GCC 4.7.1 (Linux, 64-bit) the only thing c++config.h includes is this comment: /* Defined if nanosleep is available. */ /* #undef _GLIBCXX_USE_NANOSLEEP */ Whereas in thread, the definition of std::this_thread::sleep_for() and std::this_thread::sleep_until() depend on the macro to be defined. If it isn't defined, both functions – although required by the C++ Standard – won't be defined either. On my system (glibc 2.15), the macro is not defined, although the nanosleep() function (declared in ctime) exists and is operational. I'd like to know what this is all about and how to deal with it. Specifically: * *Is there a configuration option that should be used when building GCC to activate this macro by default, as suggested by this post? (I couldn't find any in the online documentation of the build process.) *Is there really a relation between the nanosleep() function and the macro? The declaration of nanosleep() in ctime/time.h does not seem to depend on, or define, the macro. *Is there any specific risk involved in defining the macro in my own header files, or as a -D option on the command line (as suggested in this related question)? What if I do this on a system where nanosleep() is not available, and how can I actually find out? Update From GCC 4.8 onwards, support for std::this_thread::sleep_for() and the like is automatically included in libstdc++. No configuration flag is required any more. From the GCC 4.8 change log: this_thread::sleep_for(), this_thread::sleep_until() and this_thread::yield() are defined without requiring the configure option --enable-libstdcxx-time; But note the further details on this for GCC 4.8 and 4.9 given in Jonathan's answer. A: When libstdc++ is built its configure script tests your system to see what features are supported, and based on the results it defines (or undefines) various macros in c++config.h In your case configure determined that the POSIX nanosleep() function is not available and the macro is not defined. However, as you say, nanosleep() is available on your system. The reason it's not enabled by configure is that the checks for it don't even run unless you use the --enable-libstdcxx-time option (documented in the Configuration chapter of the libstdc++ manual, not the GCC configure docs) * *Is there a configuration option that should be used when building GCC to activate this macro by default, as suggested by this post? (I couldn't find any in the online documentation of the build process.) Yes, --enable-libstdcxx-time * *Is there really a relation between the nanosleep() function and the macro? The declaration of nanosleep() in ctime/time.h does not seem to depend on, or define, the macro. The declaration of glibc's function doesn't depend on libstdc++'s macro, no. But the macro tells libstdc++ whether to use the function or not. * *Is there any specific risk involved in defining the macro in my own header files, or as a -D option on the command line (as suggested in this related question)? What if I do this on a system where nanosleep() is not available, and how can I actually find out? It's naughty and is unsupported, but will work. The macro is an internal implementation detail that should be set by configure and not by users and changing the definition of the implementation's internal macros can break things. But in this case it won't because the only code that depends on it is in a header, no library code in libstdc++.so is affected. But it would be better to reinstall GCC and use the --enable-libstdcxx-time option, or if that's not possible edit your c++config.h to define the macro to true. If you define it on a different system where nanosleep() isn't available you'll get a compilation error when you #include <thread>. I have some ideas for improving that configuration, so nanosleep() and sched_yield() will be checked for by default, but I haven't had time to work on them yet. Update: I've committed some changes so that building GCC 4.8 without --enable-libstdcxx-time will still define std::this_thread::yield() (as a no-op) and will implement std::this_thread::sleep_for() and std::this_thread::sleep_until() using the lower resolution ::sleep() and ::usleep() functions instead of ::nanosleep(). It's still better to define --enable-libstdcxx-time though. Another update: GCC 4.9.0 is out and now defaults to automatically enabling nanosleep and sched_yield on platforms that are known to support them. There is no longer any need to use --enable-libstdcxx-time.
{ "language": "en", "url": "https://stackoverflow.com/questions/12523122", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "46" }
Q: Apachebench making more requests than I ask for I am trying to use apachebench to make a number of requests to test my server. However it often times makes a ton more requests than I ask for. I am using this to test a node.js server which uses express. ab -n 1 http://myserver/ It seems finicky as sometimes it will make only one request, but other it will make 10s to 100s of requests. The bad part is that it still just reports it made only one request. Am I doing something wrong? Does this have anything to do with node.js being asynchronous? Anyone else had problems using 'ab' to benchmark a node.js server? A: Looks like a problem with ab on OSX Lion: http://simon.heimlicher.com/articles/2012/07/08/fix-apache-bench-ab-on-os-x-lion That fixed my problem.
{ "language": "en", "url": "https://stackoverflow.com/questions/15911301", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: how to download and install an APK file by an intent? I am making my app to be updated via my own file server instead of Google Play-store. However, it does not work well. After confirming to "update", APK file is downloaded, it is not opened correctly. Please check the demonstration https://youtu.be/qDSGZ9fQ1Oo class MainActivity : Activity() { private fun checkUpdate(){ val jsonObjectRequest = JsonObjectRequest( Request.Method.GET, "https://myserver/release.json", null, Response.Listener { response -> if(response.getInt("version") > versionCode){ val builder = AlertDialog.Builder(this, R.style.Theme_AppCompat_Dialog_Alert) builder.setTitle("Update to v" + response.getString("version") + " ?") builder.setMessage(response.getString("note")) builder.setPositiveButton("Yes") { _, _ -> downloadUpdate(response.getString("version")) } builder.setNegativeButton("No") { _, _ -> showUserInteraction() } builder.setCancelable(false) builder.show() }else{ showUserInteraction() } }, Response.ErrorListener{ _ -> showUserInteraction() } ) requestQueue.add(jsonObjectRequest) } private fun downloadUpdate(versionCode: String) { registerReceiver(onDownloadComplete(), IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE)) val request = DownloadManager .Request(Uri.parse("https://myserver/app-release.apk")) .setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE) .setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "myapp_v" + versionCode + ".apk") downloadManager = getSystemService(DOWNLOAD_SERVICE) as DownloadManager downloadId = downloadManager.enqueue(request) } private class onDownloadComplete: BroadcastReceiver() { override fun onReceive(context: Context, intent: Intent) { val c = downloadManager.query(DownloadManager.Query().setFilterById(downloadId)) if(c != null){ c.moveToFirst() val fileUri = c.getString(c.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI)) val mFile = File(Uri.parse(fileUri).path!!) val fileName = mFile.absolutePath context.unregisterReceiver(this) val intent = Intent(Intent.ACTION_VIEW) var contentUri: Uri if (SDK_VER >= Build.VERSION_CODES.N) { intent.flags = Intent.FLAG_GRANT_READ_URI_PERMISSION contentUri = FileProvider.getUriForFile(context, BuildConfig.APPLICATION_ID + ".fileProvider", File(fileName)) }else{ contentUri = Uri.fromFile(File(fileName)) intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK } intent.setDataAndType(contentUri, "application/vnd.android.package-archive") startActivity(context, intent, null) } } } } May anyone please point out my mistake? Thanks. A: You need to add below permission in your manifest.xml file. If an app uses a targetSdkLevel of 26 or above and prompts the user to install other apps, the manifest file needs to include the REQUEST_INSTALL_PACKAGES permission: <uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES" /> You can see below link why it's needed * *Link1 *Link2
{ "language": "en", "url": "https://stackoverflow.com/questions/58318872", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: why is that there is a dark area around the buttons when they are tapped on mobile devices the code is: https://codesandbox.io/s/gatsby-starter-default-og782 I used styled-component to style a <a> tag to be my button. for example, const CloseButton = styled.a` position: relative; font-size: 30px; top: 30vh; ` And I implemented a hover effect with the <a> tag with transform: translateY(-3px); a { outline: none; font-size: ${fontSizes.medium}; ${media.phablet` font-size: ${fontSizes.small};`} font-weight: 500; display: inline-block; text-decoration: none; text-decoration-skip-ink: auto; color: inherit; position: relative; transition: ${theme.transition}; cursor: pointer; margin: 0 auto; padding: 7px; &:hover, &:focus { transform: translateY(-3px); } -webkit-user-select: none; -moz-user-select: none; -ms-user-select: none; user-select: none; } Now it works fine on desktop. But when I view it on mobile devices(you can try the demo here https://og782.sse.codesandbox.io/) There is a dark area around the buttons when they are tapped Could someone please help me to get rid of this? A: Most likely this is because of -webkit-tap-highlight-color You can try to make a transparent style: a { -webkit-tap-highlight-color: rgba(0, 0, 0, 0); }
{ "language": "en", "url": "https://stackoverflow.com/questions/57779629", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Identify all objects of given class for further processing Assume you are working with a large working environment and you aren't great about keeping up with your environment variables, or you have some process that generates a lot objects automatically. Is there a way to scan your ls() to identify all objects that have a given class? Consider the following simple example: #Random objects in my environment x <- rnorm(100) y <- rnorm(100) z <- rnorm(100) #I estimate some linear models for fun. lm1 <- lm(y ~ x) lm2 <- lm(y ~ z) lm3 <- lm(y ~ x + z) #Is there a programmatic way to identify all objects in my environment #that are of the "lm" class? Or really, any arbitrary class? outList <- list(lm1, lm2, lm3) #I want to look at a bunch of plots for all the lm objects in my environment. lapply(outList, plot) A: Use the class function: Models <- Filter( function(x) 'lm' %in% class( get(x) ), ls() ) lapply( Models, function(x) plot( get(x) ) ) (Modified slightly to handle situations where objects can have multiple classes, as pointed out by @Gabor in the comments). Update. For completeness, here is a refinement suggested by @Gabor's comment below. Sometimes we may want to only get objects that are of class X but not class Y. Or perhaps some other combination. For this one could write a ClassFilter() function that contains all of the class filterling logic, such as: ClassFilter <- function(x) inherits(get(x), 'lm' ) & !inherits(get(x), 'glm' ) Then you get the objects that you want: Objs <- Filter( ClassFilter, ls() ) Now you can process the Objs whatever way you want. A: You can use Filter with inherits and ls in mget to get a named list of in this case of lm objects. L <- Filter(\(x) inherits(x, "lm"), mget(ls())) #L <- Filter(\(x) inherits(x, "lm") & !inherits(x, "glm"), mget(ls())) #In case glm need to be excluded identical(unname(L), outList) #[1] TRUE lapply(L, plot)
{ "language": "en", "url": "https://stackoverflow.com/questions/5158830", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "12" }
Q: Spark SQL take 4 consecutive time intervals it's my table: +--------+----+----------+----+ | station|temp| dateS|hour| +--------+----+----------+----+ |Roma | 2.2|2018-10-02| 1| |Roma | 1.5|2018-10-02| 2| |Roma | 1.4|2018-10-02| 3| |Roma | 1.4|2018-10-02| 4| |Milano | 0.6|2018-11-02| 12| |Milano | 1.0|2018-11-02| 13| |Napoli | 0.3|2018-12-02| 20| |Napoli | 0.0|2018-12-02| 21| |Napoli | 1.8|2018-12-02| 4| |Napoli | 2.0|2018-12-03| 5| |Napoli | 1.8|2018-12-03| 6| +--------+----+----------+----+ I want take the station that are present in record for 4 hours consecutive(4 consecutive hours obviously on the same day). For example only show Roma because there are 4 consecutive hour in the same day(2018-10-02)... I try to write the query but nothing... A: I have tried using lead window function. I arranged the dataframe by partitioning on station and dateS and ordering by hour and calculated the difference with the previous hour. If we are considering for 4 consecutive hours, there should be three 1's in the difference column one after another. To find out that, I have collected all the diffs based on station and dateS and checked if it contains " 1 1 1 ". The code for the same is shown below. I hope it is helpful. //Creating Test Data val df = Seq(("Roma",2.2,"2018-10-02",1 ) , ("Roma",1.5,"2018-10-02",2 ) , ("Roma",1.4,"2018-10-02",3 ) , ("Roma",1.4,"2018-10-02",4 ) , ("Milano",0.6,"2018-11-02",12 ) , ("Milano",1.0,"2018-11-02",13 ) , ("Napoli",0.3,"2018-12-02",20 ) , ("Napoli",0.0,"2018-12-02",21 ) , ("Napoli",1.8,"2018-12-02",4 ) , ("Napoli",2.0,"2018-12-03",5 ) , ("Napoli",1.8,"2018-12-03",6)) .toDF("station", "temp", "dateS", "hour") val filterDF = df.withColumn("hour_lead", lead($"hour", 1) .over(Window.partitionBy("station","dateS") .orderBy(col("hour"))) .filter($"hour_lead".isNotNull) .withColumn("hour_diff", $"hour_lead" - $"hour") .groupBy("station","dateS") .agg(collect_list($"hour_diff".cast("string")).as("hour_diff_list")) .withColumn("hour_diff_list_str", concat(lit(" "), concat_ws(" ", $"hour_diff_list"), lit(" "))) .filter($"hour_diff_list_str".contains(" 1 1 1 ")) filterDF.show(false) +-------+----------+--------------+------------------+ |station|dateS |hour_diff_list|hour_diff_list_str| +-------+----------+--------------+------------------+ |Roma |2018-10-02|[1, 1, 1] | 1 1 1 | +-------+----------+--------------+------------------+
{ "language": "en", "url": "https://stackoverflow.com/questions/55271258", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Internet Explorer 9 in compatibility-mode shows error While testing my jQuery script in IE 9 it shows error in jquery-1.6.2.js -- SCRIPT5022: Exception thrown and not caught jquery-1.6.2.js, line 548 character 3 My js file used to work with no problems in other browsers - firefox 3.6, 5.0, opera 11, chromium, chrome. I do not understand. Is there a bug in the jquery source or is there a bug in my js file ? How do I find it ? It hasen't been long since I started in this area so please I would really appreciate some ideas. Thank you in advance. [edited] I've added the complete code. I've learnt from : http://net.tutsplus.com/tutorials/javascript-ajax/how-to-create-a-jquery-image-cropping-plug-in-from-scratch-part-ii/ I don't know which part to add. The whole code does not fit in stackoverflow's submit. says "body is limited to 3000 characters; you entered 42121 " [2nd edit] I have used 'error' in my ajax submit. //jquery ajax submit for resizing function submit(myform,e){ $n.val($image.attr('src').replace(/^[^,]*\//,'')); var mydata = myform.serialize(); $.ajax({ url: $myform.attr('action'), cache: false, type:$myform.attr('method'), data: mydata, success: function(response){ var img = $("<img />").attr('src', 'images/'+response+'?'+ e.timeStamp) //<-- img name here .load(function() { if (!this.complete || typeof this.naturalWidth == "undefined" || this.naturalWidth == 0) { alert('Incorrect image.'); } else { $("#result").html(img); //<-- put cropped img here. } }); }, error: function(){ //<-- error used here $('#result').html("Err. Loading Image"); } }); }; A: I traced out my problem. IE prevented changing of attribute which let to the jQuery error. Note: jQuery prohibits changing the type attribute on an or element and will throw an error in all browsers. This is because the type attribute cannot be changed in Internet Explorer." from http://api.jquery.com/attr, just after 1st warning notice. So I changed my code from earlier $('input').clone() to $('<input />').attr({'type':'hidden'}) and it solved my problem. Thanks everyone. A: Just a guess, but do you somewhere use $.error() inside your code? If yes: don't use it. <edit> However, this error comes from jQuery.error(). The original error-function looks like this: error: function( msg ) { throw msg; } You may test it without jquery: (function( msg ) { throw msg; })('errormessage'); You'll get the same error. If you don't use jQuery.error() maybe you use some plugin that uses it. You may override this (buggy?) function by executing the following right after the embedded jquery.js: jQuery.error=function(){} </edit> A: jQuery.error() (which throws the message passed as an argument), is totally different to the error handler specified in an AJAX call. jQuery.error() is used internally by jQuery (search for "error("). You should debug your code and follow the stack trace to find which of your methods is calling the jQuery method which is erroring.
{ "language": "en", "url": "https://stackoverflow.com/questions/7077471", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Fedlet Service Provider and CA Siteminder Identity Provider Has anyone used Fedlet as their service provider and CA Siteminder as their identity provider? Our client is using CA Siteminder Federation Security services and we need to configure our end to be a service provider that can accept SAMLv2 assertions with attribute mapping. Is the IDP iniatiated SSO possible with this setting? I was only able to make Fedlet work with an OpenSSO identity provider, but not with the CA Siteminder. The client only gave the idp and sp ID to use, their metadata, protocol and binding standard and nothing else. I gave them our Assertion consumer service URL (I got from the sp.xml on our Fedlet conf) and the relay state url where we will redirect the user upon successful login on their side. Or do you recommend a different technology to use as a service provider for the CA siteminder IDP? Please advise. A: The Fedlet is pretty bare bones and was designed by Sun (now Oracle) to work with OpenSSO as the IDP. While it is probably compliant to some degree, I would imagine that it may not be a full implementation of SAML 2.0 SP-Lite but a sub-set of that. I'd check out PingFederate from PingIdentity if you are looking for a more robust option. We have dozens of SPs who are integrating with CA SM FSS as the IDP (and vice versa) using SAML 1.x and 2.0. It has a very light footprint, can support a multitude of development languages/platforms and can be setup and in Production extremely quickly. HTH - IanB A: If you already have a SiteMinder installation setup then SMFSS is the fastest, easiest and most robust solution, IMHO but then I support it. I am able get new customers up and running in less than a day for SAML 2.0 POC when they already have a working SiteMinder architecture in place and there are no known issues with OpenSSO. If you have a particular issue you should give a fiddler trace with HTTPS decryption enabled and logs so we can assist. Also, the R12 SP3 or SM6 SMFSS docs have the chapter on what settings need to match, the setting up the IDP and SP for SAML 2.0 chapters which are step by step as long as you have the settings for the matching values chapter which is the second to last chapter and chapter number changes depending on version of the docs. You can also do Authorization on the SP side using the Attribute Authority we provide if your SP implements the Attribute Query SAML specification. In other words, if there was no attribute authority then you would need to store attributes on the SP side for use later. With that being said, if you used an SMFSS (SiteMinder Federation Security Services) SP you could use the Session Store on the SP side and store the assertions attributes there at authentication time. Let me know if you have any more questions on this. The thing I like about SMFSS is you really get a good idea of what your doing and can become quite proficient where a lot of other products seem to use a lot of the MetaData to add stuff into their UI's which IMHO results in people not really understanding the federation that they are setting up and administering. I am wondering if IanB is my old co-worker Ian Barnett of Ping? If so hello!!! Crissy Krueger Stone SiteMinder Support est. 5/1/2000
{ "language": "en", "url": "https://stackoverflow.com/questions/4458084", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to remove a large number of rows from Excel spreadsheet based on time? I have an Excel spreadsheet with over 44,000 rows (sensor readings taken each minute for a month). I want to reduce them to every 15 minutes. I want to remove rows where Time -column does not end in : 01 16 31 46 A: We can do something using two main figures: * *openpyxl package to retrieve the data from the Excel sheet. pip3 install openpyxl *String Operation to compare the value if its == 15 minutes: *Insert into a list. *If you want to appened it into the Excel sheet, again. Please, check this reference writing into Excel using openpyxl # importing openpyxl module import openpyxl # Give the location of the file path = "C:\\Users\\Admin\\Desktop\\demo.xlsx" # workbook object is created wb_obj = openpyxl.load_workbook(path) sheet_obj = wb_obj.active m_row = sheet_obj.max_row aList = [] # Loop will print all values # of first column for i in range(2, m_row + 1): cell_obj = sheet_obj.cell(row = i, column = 1) if (cell_obj.value[:-2] == 15): aList.append(cell_obj.value) For more information about openpyxl, please check this hyperlink; How to read from Excel sheet using openpyxl A: I managed to find a solution using Python, so this is no longer an issue. Thank you. data2 = data.set_index('Time').resample('15T').mean() data2
{ "language": "en", "url": "https://stackoverflow.com/questions/65005024", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: Inserting arrays into SQL table from form I was trying to insert arrays from my form, let's say for example I have select with options such as A, B, C, D, E for first select group, and 1, 2, 3, 4, 5 for second select group. When selecting options from these two select group, I should have the values to be inserted as: letter number A 1 B 1 A 2 B 2 There's also a default number of 0 to be included during insertion. I have tried this code I have seen: $statement = $conn->prepare("INSERT INTO letter_num_tag (default_zero, letter_tag, number_tag) VALUES (?,?,?)"); foreach ($_POST as $row) { $statement->bind_param($row['default_zero_post'], $row['letter_tag_post'], $row['number_tag_post']); $statement->execute(); } However, this will result in this error: Uncaught TypeError: trim(): Argument #1 ($string) must be of type string, array given This is what my form submit looked like: $default_zero_var = $_POST["default_zero_post"]; $letter_tag_var = $_POST['letter_tag_post']; $number_tag_var = $_POST['number_tag_post']; if (empty(trim($_POST["letter_tag_post"]))) { $letter_tag_var_err = "Please enter event date."; } else { $letter_tag_var = trim($_POST["letter_tag_post"]); } if (empty(trim($_POST["number_tag_post"]))) { $number_tag_var_err = "Please enter event date."; } else { $number_tag_var = trim($_POST["number_tag_post"]); } My form looks like this: <ul> <li>A</li><input type='checkbox' name='letter_tag_post[]' value='A'> <li>B</li><input type='checkbox' name='letter_tag_post[]' value='B'> <li>C</li><input type='checkbox' name='letter_tag_post[]' value='C'> <li>D</li><input type='checkbox' name='letter_tag_post[]' value='D'> <li>E</li><input type='checkbox' name='letter_tag_post[]' value='E'> </ul> <ul> <li>1</li><input type='checkbox' name='number_tag_post[]' value='1'> <li>2</li><input type='checkbox' name='number_tag_post[]' value='2'> <li>3</li><input type='checkbox' name='number_tag_post[]' value='3'> <li>4</li><input type='checkbox' name='number_tag_post[]' value='4'> <li>5</li><input type='checkbox' name='number_tag_post[]' value='5'> </ul> Help is greatly appreciated. Thanks!
{ "language": "en", "url": "https://stackoverflow.com/questions/74488031", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: textfield Validation in blackberry java i am validating a password field where it has to contain atleast one capital letter and one number.i used below code but its not working? for (int i = 0;i<Password.getText().length(); i++) { char i1 = Password.getText().charAt(i); boolean valid; if ( valid=(i1!='A'||i1!='B'||i1!='C'||i1!='D'||i1!='E'||i1!='F'||i1!='G'||i1!='H'||i1!='I'||i1!='J'||i1!='K'||i1!='L'||i1!='M'||i1!='N'||i1!='O'||i1!='P'||i1!='Q'||i1!='R'||i1!='S'||i1!='T'||i1!='U'||i1!='V'||i1!='W'||i1!='X'||i1!='Y'||i1!='Z')&&(i1!='1'||i1!='2'||i1!='3'||i1!='4'||i1!='5'||i1!='6'||i1!='7'||i1!='8'||i1!='9'||i1!='0')) { if(valid=true){ return true; }else{ return false; } } } A: If your password must have at least one capital letter and at least one number your logic is wrong. You should have two booleans. boolean hasCapitalLetter = false; boolean hasNumber = false; for (int i = 0;i<Password.getText().length(); i++) { char i1 = Password.getText().charAt(i); if (!hasCapitalLetter) { hasCapitalLetter = Character.isUpperCase(i1); } if (!hasNumber) { hasNumber = Character.isDigit(i1); } if (hasCapitalLetter && hasNumber) { return true; } } return false;
{ "language": "en", "url": "https://stackoverflow.com/questions/31905303", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How do I return a value from my Node.js module AFTER it has been updated by an async function? Forgive me, but as an extremely new developer I fail to see how this is an exact duplicate of the questions referred to. I have no idea what ajax is, and I certainly don't understand how to adapt the proposed solutions to work in my situation. I'm writing a very simple node app that gets a stock price from a web api, get a currency conversion value from another web api, and converts the stock price from USD to AUD. I had this working perfectly in a single file, but I've chosen to split it out in to several modules to make it easier. And now I've broken it :) Basically I pass the ticker I wish to lookup into my GetStockPrice() function, which then perform the necessary query and returns the result.....in theory. This is how I call my module: var returned = GetStockPrice('AMZN'); console.log(returned); The returned value is always 10, as it's not being updated in my GetStockPrice module. Here is the code in my module: var http = require('http'); var stockPrice = 10; function GetStockPrice(ticker) { var options = { host: 'dev.markitondemand.com', port: 80, path: '/MODApis/Api/v2/Quote/json?symbol=' + ticker, method: 'GET' }; http.request(options, function(res) { console.log('STATUS: ' + res.statusCode); res.setEncoding('utf8'); res.on('data', function(chunk) { const json = JSON.parse(chunk); stockPrice = json.LastPrice; }); }).end(); return (stockPrice) }; module.exports = GetStockPrice; I understand what I'm doing wrong, the http.request is being run asynchronously, so by the time my function gets to the return statement, the async call hasn't completed, so my return value, stockPrice, is still the same as when I first initialized it. Unfortunately, I don't know how to fix it. I tried moving the return statement inside the http.request function, but that doesn't work either. Can anyone help please? A: You can use callback to get response from asynchronous functions. var http = require('http'); var stockPrice = 10; function GetStockPrice(ticker, callback){ var options = { host: 'dev.markitondemand.com', port: 80, path: '/MODApis/Api/v2/Quote/json?symbol=' + ticker, method: 'GET' }; http.request(options, function(res) { console.log('STATUS: ' + res.statusCode); res.setEncoding('utf8'); var stockPrice=''; res.on('data', function (chunk) { stockPrice = stockPrice + chunk; }); res.on('end', function(){ return callback(JSON.parse(stockPrice)); }); }); }; module.exports = GetStockPrice; And GetStockPrice('AMZN', function(data){ console.log(data); }); Pardon me, if there are any typos.
{ "language": "en", "url": "https://stackoverflow.com/questions/37537289", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Block all personal sites in Sharepoint (Microsoft cannot help) Is there a way to lock all personal sites. I found a script to block one site $siteUrl = "https://xxx-my.sharepoint.com/personal/adelev_xxx_onmicrosoft_com" $site = Get-SPOSite $siteUrl -Detailed Set-SPOSite $site -LockState NoAccess It works, but I have hundreds of sites to block. First I would need to list all sites and then one by one block them. Hello, Is there a way to automate it and BLOCK all sites? I want to lock sites temporarily. This lock prevent users that has a personal site to use them (new ppl are blocked by MySite setting). I contacted Microsoft directly and they provided me with some data - they told me that I should use ForEach, but I have no idea how to use it, and they won't help me any further cause it is against some policy. A: To sum up, what you need is to: * *Get all personal sites *Run Set-SPOSite for each of them using any mechanism like foreach Here's helpful article for 1: Get a list of all user OneDrive URLs in your organization. So, you need to run something like: $allSites = Get-SPOSite -IncludePersonalSite $true -Limit all -Filter "Url -like '-my.sharepoint.com/personal/'" | Select -ExpandProperty Url And for 2. you can use something similar to: foreach ($site in $allSites) { Set-SPOSite -Identity $site -LockState NoAccess } A: Here's what I came up with to get all sites that are locked. It includes all information fields. Change the export path to a destination that's appropriate for you: Get-sposite -includepersonalsite $true -Limit ALL -Filter "LockState -like 'NoAccess'" |Export-csv -Path 'C:\PowerShell\OneDriveSitesLocked.csv' -Delimiter ',' -NoTypeInformation
{ "language": "en", "url": "https://stackoverflow.com/questions/65791174", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Using structs as arguments: Error: Struct not defined I am creating a class where I defined a Struct called "Room" which I declare as private in the header file. I have several public functions that require a "Room" as an argument. When I compile (in g++) I get an error saying: Graph.h:42:17: error: "Room" has not been declared Yet here lies the declaration (whole header file now): #ifndef GRAPH_H #define GRAPH_H #include <iostream> #include <string> using namespace std; class Graph { public: // destructor ~Graph(); // copy constructor Graph(const Graph &v); // assignment operator Graph & operator = (const Graph &v); //Create an empty graph with a potential //size of num rooms. Graph( int num ); //Input the form: //int -- numRooms times //(myNumber north east south west) -- numRooms times. void input(istream & s); //outputs the graph as a visual layout void output(ostream & s) const; //Recursively searches for an exit path. void findPath( Room start ); //Moves room N E S or W void move( Room &*room , String direction ); //inputs the starting location. void inputStart( int start ); //Searches the easyDelete array for the room with the //number "roomNumber" and returns a pointer to it. const Room * findRoom( int roomNumber ); private: struct Room { bool visted; int myNumber; Room *North; Room *East; Room *South; Room *West; }; int numRooms; int _index; int _start; Room ** easyDelete; string * escapePath; Room * theWALL; Room * safety; }; #endif Are you not allowed to use structs defined inside the header file as arguments? If so, what's the workaround? Thanks. A: It compiles fine without the private: header. Why do you have this? Is the struct declared inside of a class? EDIT You have used Room before you declare it: const Room * findRoom( int roomNumber ); Also, you can't return a Room object through the public method you have declared, since outside code won't know anything about it. You need to predeclare it before using it: class Graph { public: struct Room; const Room * findRoom( int roomNumber ); struct Room { bool visted; int myNumber; Graph::Room *North; Graph::Room *East; Graph::Room *South; Graph::Room *West; }; Room room; }; int main (){ Graph x; return 0; } Or you could just move the second private up, above the public section. A: If you are using a nested struct as an argument to a mthod of the containing class, then you must use the fully-qualified name such as void outerclass::mymethod(outerclass::room); Try that. You may need to make it public too. A: * *Room cannot be private since you use it in your public member functions. *Either forward declare it like this : struct Room; // destructor ~Graph(); *Or just declare and implement it before you use it at the top of the class. *void move( Room &*room , String direction ); //this is not valid C++ A: You have to declare any type before using it. A forward declaration suffices because you are defining Graph::Room in the same scope. However, since you have to define it anyway, I would suggest moving it up to some point before first using it. Making Room private within Graph is perfectly legal (it is questionable if it is reasonable, though, if your public interface fumbles with it). On a side note: Pointers to references are no valid types (references to pointers are!). Your move function is therefore invalid.
{ "language": "en", "url": "https://stackoverflow.com/questions/8461541", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: gradle cannot compile, but final Annotation var is not syntax error Using gradle 4.10.2 @Table public class MyClass{ public static final String COL_NAME = "name"; public static final String COLTYPE_NAME = DB.DataType.VARCHAR; @Column(name = COL_NAME, columnDefinition = COLTYPE_NAME) private String name; } This should not be a syntax error, but when I run gradle clean publishtomavenlocal, I get @Column(name = COL_NAME, columnDefinition = COLTYPE_NAME) error: element value must be a constant expression ^ the above is pointing at COLTYPE_NAME. DB.DataType.VARCHAR is defined as public final class DB{ public static final class DataType{ public static final VARCHAR = "varchar"; } } How to fix this problem with gradle?
{ "language": "en", "url": "https://stackoverflow.com/questions/67235767", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: C++: Issues with manipulating a PPM file I'm working on a program that can perform various effects and manipulations on a PPM file. However for testing reasons, it uses cin rather than an input file. It is supposed to be able to perform multiple effects at once, but I am having trouble even getting one right. I'll run a removeBlue() on a line that will work, then try again with different values and it will remove red or green instead. That sort of thing. There's a lot of code, so I'll try to include only what is necessary. #include <vector> #include <stdlib.h> #include <cstdlib> #include <string> #include <vector> #include <fstream> #include <sstream> #include <iostream> using namespace std; class SimpleImageEffect { public: virtual void processImage(vector<Point> &points) = 0; }; class RemoveRed : public SimpleImageEffect { public: virtual void processImage(vector<Point> &points) { for (Point& p : points) { p.setRed(0); } } }; //Just an example of one of the effect classes. //The code in them is correct, so I won't include the others unless needed. vector<Point> parse_line(string line) { istringstream scanner{line}; vector<Point> result{}; int red = -1; int green = -1; int blue = -1; int counter = 0; while(scanner.good()) { if (counter == 0) { counter++; scanner >> red; } else if (counter == 1) { counter++; scanner >> green; } else if (counter == 2) { scanner >> blue; Point p{ red, green, blue }; result.push_back(p); counter = 0; } } return result; } void readFromCin() { string line = ""; vector<string> lines_in_file{}; int i, effect_choice; SimpleImageEffect *effect = nullptr; getline(cin, line); while (line.length() > 0) { lines_in_file.push_back(line); getline(cin, line); } for (int i = 0; i < lines_in_file.size(); i++) { if (lines_in_file[i] != "P3") { effect_choice = strToInt(lines_in_file[i]); } else if (lines_in_file[i] == "P3") { cout << lines_in_file[i] << endl; cout << lines_in_file[i+1] << endl; cout << lines_in_file[i+2] << endl; } vector<Point> points = parse_line(lines_in_file[i]); if (effect_choice == 1) effect = new RemoveRed; if (effect_choice == 2) effect = new RemoveGreen; if (effect_choice == 3) effect = new RemoveBlue; if (effect_choice == 4) effect = new NegateRed; if (effect_choice == 5) effect = new NegateGreen; if (effect_choice == 6) effect = new NegateBlue; if (effect_choice == 7) effect = new AddNoise; if (effect_choice == 8) effect = new HighContrast; if (effect_choice == 9) effect = new ConvertToGrayscale; effect->processImage(points); for (auto p : points) { cout << p; cout << endl; } } } int main(int argc, char** argv) { string menu_choice; getline(cin, menu_choice); if (menu_choice == "1") { readFromFile(); } else { readFromCin(); } return 0; } So for example, running it with an input of 2 1 P3 1 1 255 50 50 50 will return P3 1 1 255 0 50 50 but if I run it with 2 3 P3 1 2 255 50 50 50 1 2 3 it returns P3 1 2 255 0 50 50 0 2 3 I have absolutely no idea what's causing the issue, so any help at all would be greatly appreciated. Thanks. A: Your algorithm logic structure smells a lot, this is what I see: * *read all non empty lines into lines_in_file (looks good to me) *for EVERY line (problematic, requires additional logic in inner loop): * *if not "P3", try to parse [EVERY] line as integer and set effect_choice (it's not clear from your code, what happens on lines where several integers are provided, but judging from your problem description the first integer is successfully parsed by strToInt function) *if "P3", the current line and next two are copied to output *[EVERY] line is parsed as vector of triplets of numbers *effect is set by new effect for actual value of effect_choice (for EVERY line, also you don't delete the effect at end, so you are leaking memory in per-line counts. Also your current effects look like they may be implemented as static functions of "process" function type, so you don't need to allocate each of them, just store the particular memory address of requested function. And you call it processImage, while you are processing only line, not whole image. *effect is run for current line triplets *the line triplets are outputted *loop to next line (!) So for example for input: 2 3 P3 1 2 255 50 50 50 1 2 3 I believe (can't run it, as you didn't provide lot of code) this happens: lines are read, and per particular line this happens: line "2": effect_choice = 2, effect = RemoveGreen, zero triplets parsed into points, RemoveGreen::processImage() run over empty vector, empty vector printed (ie nothing). line "3": effect_choice = 3, effect = RemoveBlue, zero triplets parsed into points, RemoveBlue::processImage() run over empty vector, empty vector printed. line "P3": Lines: {"P3", "1 2", "255"} are printed, zero triplets parsed into points, RemoveGreen::processImage() run over empty vector, empty vector printed. line "1 2": effect_choice = 1, effect = RemoveRed, zero triplets parsed into points, RemoveRed::processImage() run over empty vector, empty vector printed. line "255": effect_choice = 255, zero triplets parsed into points, RemoveRed::processImage() run over empty vector, empty vector printed. line "50 50 50": effect_choice = 50, one triplet {50, 50, 50} parsed into points, RemoveRed::processImage() run over it, modified triplet outputs {0, 50, 50}. line "1 2 3": effect_choice = 1, effect = RemoveRed, one triplet {1, 2, 3} parsed into points, RemoveRed::processImage() run over it, modified triplet outputs {0, 2, 3}. All of this should be clearly visible in debugger, while stepping over the code, so you probably are not debugging it, which gets downvoting the question from me, and you will pay in tremendous pain over time, as debugging without debugger is lot more difficult. Also writing code without thinking about algorithm and code architecture makes the need of debugging lot more likely, so you wasted even more time here, by starting by writing the code. You should have first design some algorithm and code architecture (what data are processed, how, when new memory is needed, how it will be freed, where the code need to loop, where it need to skip over, or run only once, etc). Write only overview of how it will work into single-line comments, then split too generic comments into simpler steps until they can be implemented by few lines of C++ code, and move/modify them around until you feel the wanted algorithm will be implemented with minimal "cruft" added (most of the comments does, what is really requested, like "set red in point to zero", and any processing/preparations/moving/etc is minimized only to cases where you can't avoid it by smarter design). (for example in your current code you can read through the header of the file without looping, and start looping only after the pixel data pours in) Then write the code, start probably with some empty function definition so you can already "run" it in debugger and verify the emptiness works, then implement the comment (or small group of them) which you feel is clear enough to be implemented and can be tested easily (no big dependency on yet-to-implement parts). Debug + test new code. If it works, try to clean up the source to remove anything not really needed, work-in-progress variable names, etc... Then verify it works in final version. And do it again for another comment (group of), until the implementation is done. Using unit-testing makes the write-short-code, test+debug, clean-up-source rounds even easier, especially in cases like this, where I/O are pure data, so it's easy to feed specialized test input data into test, and verify the expected output data were produced.
{ "language": "en", "url": "https://stackoverflow.com/questions/42576520", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Image processing with sub pixel accuracy I'm writing a user interface program which controls industrial machinery. The machine is an automatic inline screen printer used in the electronic production industry. The exact purpose of the machine is to print solder paste onto bare PCBs. The system includes 2 cameras which form a vision system used to locate fiducials and automate the process that the machinery is involved in. The issue I have is that I need to be able to locate shapes and objects within images taken from the cameras, which is straight forward enough, but - in order to get the required accuracy I need to be able to do this with sub pixel accuracy. The two cameras form one twin vision camera, with one camera will be looking up at a stencil, and the other looking down at a PCB. The twin vision camera is on a moving carriage that moves in X and Y. The PCB is clamped onto a table than can move in X, Y and theta. The vision system is used to detect the difference between PCB position and stencil position, and the table is then adjusted to align the two together. EDIT: This is a partial screen shot taken from an existing UI program: The stencil image is the top image, the PCB is the bottom, the images here are grayscale images - in the new system I am looking at using colour but will use grayscale is required. NOTE: As you're reading this you're probably thinking "well why don't you just use whatever you use in the existing UI?" The existing UI is written in VB6, something I want to move away from, and the vision side of the program is an .ocx written by a third party company who no longer exists. I have played with AForge.NET a little bit and found it was really easy to use and I was able to use it to locate various different shapes and find the center of them which was great, but it doesn't have the sub pixel accuracy. However I could possibly use this as a starting point then apply a sub pixel algorithm to the individual center pixel or even the whole shape. EDIT: Here is a sample image taken from the test program I've written using AForge: The red outline and crosshair is what I've added as a visual aid/ experiment. This was taken with the camera that I'm likely to use, which has a resolution of 1280 x 1024, however the lens is not the actual lens I'll use, which is why the image is slightly 'fisheyed'. Also the objects of interest will be better light than this. In the actual system the lens will look at a 10mm x 8mm sqaure on both stencil and PCB, meaning each pixel will represent 7.8125um^2, however I can move the XYY table by increments of 1.25um at a time, which is essentially useless if I can't see those movements with the camera. I require 1um (sub) pixel accuracy. Does anyone know of anything I can use to do this? I have been searching for quite a while now but all I ever seem to find is information on rendering images with sub pixel accuracy. Or, better still, does anyone know how I could write something to do this myself? I wouldn't even know where to begin! Any feedback will be greatly appreciated. A: new info tells a lot... I think you should be more focused on the paste application accuracy then the carriage position precision. My bet is that the printer has far bigger dot size and error then 1 um and also the desired accuracy is dependent on the PCB usage (wiring and gaps widths). Anyway I would do this: * *linearize image geometry you need to de-fisheye image. As you camera/optics setup will be fixed (especially focus and distance to PCB) you should for each PCB thickness make an image of a chess board grid. then create mapping that will linearize the chessboard to real rectangles so you discard deviations before the next process. *normalize lighting conditions * *see Enhancing dynamic range and normalizing illumination *sub pixel accuracy each pixel of the image is integration of all the stuff in its area. So if we know the 2 colors (c0,c1) of any boundary (background/foreground) then we can estimate their sub-pixel position. Let start with axis aligned rectangles. I see it like this: Each square of the grid represents a pixel area. c0 is the gray and c1 is the green color. In the camera image you got the final color as combination of all the colors inside each pixel: * *c = s0*c0 + s1*c1 where c is the final pixel color and s0,s1 are area coresponding to c0,c1 colors in range <0,1> where s0+s1=1.0. Now we want to compute the s0,s1 to obtain sub-pixel precision. So first detect the pixel position on the boundary as one of these: * *horizontal edge *vertical edge *corner this can be done by inspecting the neighboring pixels. c0,c1 can be obtained from pixels with saturated color (all neighbors have the same color) These are in inside areas pixels. I would ignore the corner pixels as their position can be obtained from nearest H/V edge pixels (it is not possible to get both x,y coordinates from the equation above). So now for each H,V edge just solve system: I. c = s0*c0 + s1*c1 II. s0 + s1 = 1.0; compute the s0,s1 and the edge position for vertical edges is one of these: x=x0 + pixel_size*s0 // if c0 is on the left x=x0 + pixel_size*s1 // if c1 is on the left horizontal edges are like this: y=y0 + pixel_size*s0 // if c0 is on the top y=y0 + pixel_size*s1 // if c1 is on the bottom where x0,y0 is pixels top left position in pixels and the coordinate system is x+ is going to right and y+ is going down. If you got different setup just change the equations ... Now if you got non axis aligned edges then you need to compute the slope (how many pixels it takes in one axis to change in the other dy/dx. and handle the areas accordingly: So the only thing what changes is the conversion from computed s0,s1 to actual edge position. now you need to compute the left/right side or up/down. if you use the equation from the axis aligned example then you obtain the edge position in the middle of pixel. So you just shift it by the slope on both sides by x +/- 0.5*dx/dy or y +/- 0.5*dy/dx where dx,dy is the edge slope. To obtain dx,dy just search along the edge for fully saturated pixels and if found then (dx,dy) is the distance between 2 closest such pixels... [Notes] you can do this on booth grayscale and RGB. Hope this helps a bit.
{ "language": "en", "url": "https://stackoverflow.com/questions/34843193", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Keyboard from EditText destroing Layout I have EditText, when i toutch this, keyboard will show, but instead of covering the bottom part of the application, it shifts all the elements at the top and makes them smaller, everything looks distorted ... How do I display the keyboard so that it does not affect our layout? A: Please check this Link: You can add in your menifest for the activity you want to prevent such issue. Also make sure if you are having a bit more content use scrollView as a parent. And soft input mode as "adjustResize" android:windowSoftInputMode="adjustResize" or android:windowSoftInputMode="adjustPan" you can use as per your need. adjustResize to ensure that the system resizes your layout to the available space—which ensures that all of your layout content is accessible (even though it probably requires scrolling)—use this one. adjustPan The activity's main window is not resized to make room for the soft keyboard, and the contents of the window are automatically panned so that the current focus is never obscured by the keyboard and users can always see what they are typing. adjustNothing Do nothing with layouts
{ "language": "en", "url": "https://stackoverflow.com/questions/48968789", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Incrase WebView HTML5 Canvas in QT I'm porting a current HTML5 Canvas application to a QT wrapper. however its performance is quite low. This HTML5 canvas app runs at 60fps in Chrome and IE11, however it still at 10fps on QTWebView. How can I increase the render speed of this existent HTML5 canvas application inside a QT project? the question is about if there is any parameter to use some more fast renderer (like GPU) Note. this project was created using the default qt creator wizard for HTML5 applications.
{ "language": "en", "url": "https://stackoverflow.com/questions/23136398", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: SAML and Java Standalone application without browser? I am testing SSO with SP (Spring-SAML) and IDP (WSO2IS). They are working fine on browser. Now I want to bring it to a Java standalone application. Providing user credentials and SP URL, then a user can log in the application and access SP. To implement this, basically I need to use HTTPClient (for handling Cookie, POST, Redirect, Auto-POST) and follow the SAML message flow as it happens on browser. I would like to know the most efficient way to do it. Is there any library or example? Your help is highly appreciated. A: I managed to create a relatively simple solution using the HtmlUnit headless browser. In my case i had to download a PDF file from a website which required SAML authentication. import com.gargoylesoftware.htmlunit.UnexpectedPage; import com.gargoylesoftware.htmlunit.WebClient; import com.gargoylesoftware.htmlunit.html.*; import java.io.InputStream; import org.apache.commons.io.IOUtils; ... private static byte[] samlAuthenticateAndDownloadFile(String url, String username, String password) throws Exception { byte[] fileBytes; try (final WebClient webClient = new WebClient()) { final HtmlPage loginPage = webClient.getPage(url); final HtmlForm loginForm = loginPage.getForms().get(0); final HtmlSubmitInput button = loginForm.getInputByName("login"); final HtmlTextInput usernameField = loginForm.getInputByName("username"); final HtmlPasswordInput passwordField = loginForm.getInputByName("password"); usernameField.setValueAttribute(username); passwordField.setValueAttribute(password); final UnexpectedPage pdfPage = button.click(); InputStream inputStream = pdfPage.getInputStream(); fileBytes = IOUtils.toByteArray(inputStream); } return fileBytes; }
{ "language": "en", "url": "https://stackoverflow.com/questions/27123260", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Is there an edit distance algorithm that takes "chunk transposition" into account? I put "chunk transposition" in quotes because I don't know whether or what the technical term should be. Just knowing if there is a technical term for the process would be very helpful. The Wikipedia article on edit distance gives some good background on the concept. By taking "chunk transposition" into account, I mean that Turing, Alan. should match Alan Turing more closely than it matches Turing Machine I.e. the distance calculation should detect when substrings of the text have simply been moved within the text. This is not the case with the common Levenshtein distance formula. The strings will be a few hundred characters long at most -- they are author names or lists of author names which could be in a variety of formats. I'm not doing DNA sequencing (though I suspect people that do will know a bit about this subject). A: In the case of your application you should probably think about adapting some algorithms from bioinformatics. For example you could firstly unify your strings by making sure, that all separators are spaces or anything else you like, such that you would compare "Alan Turing" with "Turing Alan". And then split one of the strings and do an exact string matching algorithm ( like the Horspool-Algorithm ) with the pieces against the other string, counting the number of matching substrings. If you would like to find matches that are merely similar but not equal, something along the lines of a local alignment might be more suitable since it provides a score that describes the similarity, but the referenced Smith-Waterman-Algorithm is probably a bit overkill for your application and not even the best local alignment algorithm available. Depending on your programming environment there is a possibility that an implementation is already available. I personally have worked with SeqAn lately, which is a bioinformatics library for C++ and definitely provides the desired functionality. Well, that was a rather abstract answer, but I hope it points you in the right direction, but sadly it doesn't provide you with a simple formula to solve your problem. A: Have a look at the Jaccard distance metric (JDM). It's an oldie-but-goodie that's pretty adept at token-level discrepancies such as last name first, first name last. For two string comparands, the JDM calculation is simply the number of unique characters the two strings have in common divided by the total number of unique characters between them (in other words the intersection over the union). For example, given the two arguments "JEFFKTYZZER" and "TYZZERJEFF," the numerator is 7 and the denominator is 8, yielding a value of 0.875. My choice of characters as tokens is not the only one available, BTW--n-grams are often used as well. A: One of the easiest and most effective modern alternatives to edit distance is called the Normalized Compression Distance, or NCD. The basic idea is easy to explain. Choose a popular compressor that is implemented in your language such as zlib. Then, given string A and string B, let C(A) be the compressed size of A and C(B) be the compressed size of B. Let AB mean "A concatenated with B", so that C(AB) means "The compressed size of "A concatenated with B". Next, compute the fraction (C(AB) - min(C(A),C(B))) / max(C(A), C(B)) This value is called NCD(A,B) and measures similarity similar to edit distance but supports more forms of similarity depending on which data compressor you choose. Certainly, zlib supports the "chunk" style similarity that you are describing. If two strings are similar the compressed size of the concatenation will be near the size of each alone so the numerator will be near 0 and the result will be near 0. If two strings are very dissimilar the compressed size together will be roughly the sum of the compressed sizes added and so the result will be near 1. This formula is much easier to implement than edit distance or almost any other explicit string similarity measure if you already have access to a data compression program like zlib. It is because most of the "hard" work such as heuristics and optimization has already been done in the data compression part and this formula simply extracts the amount of similar patterns it found using generic information theory that is agnostic to language. Moreover, this technique will be much faster than most explicit similarity measures (such as edit distance) for the few hundred byte size range you describe. For more information on this and a sample implementation just search Normalized Compression Distance (NCD) or have a look at the following paper and github project: http://arxiv.org/abs/cs/0312044 "Clustering by Compression" https://github.com/rudi-cilibrasi/libcomplearn C language implementation There are many other implementations and papers on this subject in the last decade that you may use as well in other languages and with modifications. A: I think you're looking for Jaro-Winkler distance which is precisely for name matching. A: You might find compression distance useful for this. See an answer I gave for a very similar question. Or you could use a k-tuple based counting system: * *Choose a small value of k, e.g. k=4. *Extract all length-k substrings of your string into a list. *Sort the list. (O(knlog(n) time.) *Do the same for the other string you're comparing to. You now have two sorted lists. *Count the number of k-tuples shared by the two strings. If the strings are of length n and m, this can be done in O(n+m) time using a list merge, since the lists are in sorted order. *The number of k-tuples in common is your similarity score. With small alphabets (e.g. DNA) you would usually maintain a vector storing the count for every possible k-tuple instead of a sorted list, although that's not practical when the alphabet is any character at all -- for k=4, you'd need a 256^4 array. A: I'm not sure that what you really want is edit distance -- which works simply on strings of characters -- or semantic distance -- choosing the most appropriate or similar meaning. You might want to look at topics in information retrieval for ideas on how to distinguish which is the most appropriate matching term/phrase given a specific term or phrase. In a sense what you're doing is comparing very short documents rather than strings of characters.
{ "language": "en", "url": "https://stackoverflow.com/questions/878114", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "10" }
Q: How can I manipulate the data in receiving CAN frame via CAPL script and forward it into the same CAN bus? For example, I'm receiving a CAN frame from ECU with id 0x100 with some data inside in CAN channel 1. I want to change only byte 7 to 0xFF and forward this frame further in channel 1. My code is below: on message 0x100 { message 0x100 msg; msg = this; msg.byte(7) = 0xFF; output(msg); } But, in CAN trace, I see the message as it is, without byte 7 changed. What I do wrong? Maybe there is something that I do not understand.. I have one assumption to solve it, but this requires wiring changes to my hardware. If I make one channel for input and another channel for output, then I can use CAPL as a gateway and send frame from CAN1 to CAN2 inside one CAN-bus. Any ideas are welcome. Thank you.
{ "language": "en", "url": "https://stackoverflow.com/questions/66537025", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Why is it not possible to shadow a local variable in a loop? I got this situation I can't understand about shadowing. For example the following code: class Foo { int a = 5; void goFoo(int a) { // No problem naming parameter as same as instance variable for (int a = 0; a < 5; a++) { } // Now the compiler complains about the variable a on the for loop // I thought that the loop block had its own scope so I could shadow // the parameter, why the compiler didn't throw an error when i named // the parameter same as the instance variable? } } A: void goFoo(int a) { for (int a = 0; a < 5; a++) { } } it is similar to void goFoo() { int a; for (int a = 0; a < 5; a++) { } } so multiple declaration of a on the same scope, it is not acceptable. or simply it is similar to void goFoo() { int a; int a; } Also See * *java-variable-scope-shadowing A: You can make a local variable shadow an instance/static variable - but you can't make one local variable (your loop counter) shadow another local variable or parameter (your parameter). From the Java Language Specification, section 14.4.3: If a name declared as a local variable is already declared as a field name, then that outer declaration is shadowed (§6.3.1) throughout the scope of the local variable. Note the "field name" part - it's specifying that it has to be a field that is shadowed. And from section 8.4.1: The scope of a parameter of a method (§8.4.1) or constructor (§8.8.1) is the entire body of the method or constructor. These parameter names may not be redeclared as local variables of the method, or as exception parameters of catch clauses in a try statement of the method or constructor. (It goes on to talk about local classes and anonymous classes, but they're irrelevant in your case.) A: The scope of the variable depends on the hierarchy of the block as well. ie if u use like this void goFoo(int a) { // No problem naming parameter as same as instance variable for (int b = 0; b < 5; b++) { } //Now the compiler complains about the variable a on the for loop // i thought that the loop block had its own scope so i could shadow // the parameter, why the compiler didnt throw an error when i named // the parameter same as the instance variable? int b; // you can do this. } That is if a variable is declared in the outer block then you can not declare the same in the block which is inner. the other way you can do it. A: But you don't declare the second "a" in that new scope, as your code shows. It's in the scope of the goFoo() block itself. A: The problem isn't that the loop is shadowing the class field, the name is already used by the parameter. Two options: One is to change the loop: for (a = 0; a < 5; a++) { } This uses the parameter as the index variable. Not clear why you would have a parameter, but all the same... The other option is to rename the loop variable or the parameter to something else. A: It is not shadowing, it is a conflict here. Both a are in the method scope. One cannot define two variables of same name in the same scope. A: In Java (unlike, say, in c++) you cannot declare a local variable when another local variable with the same name is "in scope". You cannot do this in Java void foo() { int a; { int a; // You cannot declare 'a' here because a // from the outer block is still in scope // here. Local variables in Java cannot be // shadowed by another local variable with // the same name. Only instance variables // can be shadowed by the local variables // with the same name. } } However c++ allows you to do this void foo() { int a; a = 10; cout << a << endl; // prints 10 duh { int a; // this declaration shadows the local // variable 'a' from the outer scope. a = 20; // assigns 20 to the variable 'a' in // current inner scope, like you'd expect. cout << a << endl; // prints 20. } cout << a << endl; // prints 10 }
{ "language": "en", "url": "https://stackoverflow.com/questions/4623334", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: writing to a json file from python how do i edit/change a particular field in a json file using python code: { "EZMessage":{ "action":"account.cash", "data":{ "authToken":"123456", "account":"#ACCOUNTID#", "portfolio":"true", "historical":"true" } } } in this json code, i want to replace 123456 with 789123 string replace only works if i know what is written there. in my code, i would only know what to write, and the identifier "authToken". Is there a way to overwrite the 123456 by identifying that it is the value of "authToken" ? thanks, RS A: Use the json module to convert the string to a set of nested dict objects, make your changes, and then dump the dictionary back to a json string. import json jstr = '''{ "EZMessage":{ "action":"account.cash", "data":{ "authToken":"123456", "account":"#ACCOUNTID#", "portfolio":"true", "historical":"true" } } }''' j = json.loads(jstr) j['EZMessage']['data']['authToken'] = 654321 jstr = json.dumps(j) For how to read-from/write-to a file see the fine tutorial. A: Convert the JSON object to a Python object, then change the value just like any other Python object.
{ "language": "en", "url": "https://stackoverflow.com/questions/14595425", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Excel VBA. Matching the BackColor of a TextBox to the .Interior.Color of a cell I can't seem to find an answer for this. I have a spreadsheet with a userform, and I'm trying to match the back colour of TextBox47 with the corresponding cell on the sheet, the value of which is fetched via a Listbox. What I need is to be able to click on the list item, and the text box to fill with that colour. I have the following code to colour the cells in the sheet, according to date, and with named ranges for parameters.. and this runs on UserForm Initialise() Dim cell As Range With Range("data_table[Date Test]") For Each cell In Range("data_table[Date Test]") If cell.Value < Range("Today") Then cell.Interior.ColorIndex = 6 ElseIf cell.Value >= Range("Today") And cell.Value <= Range("Thirty_Days") Then cell.Interior.ColorIndex = 3 ElseIf cell.Value > Range("Thirty_Days") And cell.Value <= Range("Sixty_Days") Then cell.Interior.ColorIndex = 45 ElseIf cell.Value > Range("Sixty_Days") And cell.Value <= Range("Ninety_Days") Then cell.Interior.ColorIndex = 43 ElseIf cell.Value > Range("Ninety_Days") Then cell.Interior.ColorIndex = 18 End If Next cell End With This works fine, I then tried the following to colour the textbox Private Sub TextBox47_Change() Me.TextBox47.Text = Format(TextBox47.Text, "dd/mmm/yyyy") Dim cell As Range For Each cell In Range("data_table[Date Test]") With Range("data_table[Date Test]") Me.TextBox47.BackColor = .Interior.Color Next cell End With I think I need to add the following somewhere.. TextBox47.Value = Me.ListBox1.List(ListBox1.ListIndex, 65) Which is the ListBox reference for the TextBox.. but I'm starting to get very confused now. I've been looking at this for a couple of days. Edit to add Listbox code as asked. Private Sub ComboBox8_Change() Dim i As Long Me.ListBox1.Clear For i = 2 To Application.WorksheetFunction.CountA(Sheet1.Range("A:A")) If Sheet1.Cells(i, 10).Value = Me.ComboBox8.Value Then Me.ListBox1.AddItem Sheet1.Cells(i, 10).Value 'ID Number Me.ListBox1.List(ListBox1.ListCount - 1, 0) = Sheet1.Cells(i, 1).Value 'Title Me.ListBox1.List(ListBox1.ListCount - 1, 1) = Sheet1.Cells(i, 2).Value So would it be more something like this.. Private Sub TextBox47_Change() Me.TextBox47.Text = Format(TextBox47.Text, "dd/mmm/yyyy") Me.TextBox47.BackColor = .Interior.Color End Sub Which gives a Compile Error 1 Newer code I've now changed it to this.. Private Sub TextBox47_Change() Dim cell As Range Me.TextBox47.Text = Format(TextBox47.Text, "dd/mmm/yyyy") With Range("data_table[Date Test]") Me.TextBox47.BackColor = Range("data_table[Date Test]").Interior.Color End With End Sub Which at least doesn't throw up an error, but on every selection the BackColor is black. I started with .. Private Sub TextBox47_Change() Dim cell As Range Me.TextBox47.Text = Format(TextBox47.Text, "dd/mmm/yyyy") With Range("data_table[Date Test]") Me.TextBox47.BackColor = Range("cell").Interior.Color End With End Sub But that just stopped at a Run Time error 1004 Yet another edit.. please tell me if continual adding to this post is the wrong way to do it. This, when hovering over is actually picking up the correct info from the cell that I'm after (I've tried different ones to make sure), in the Listbox selection that I'm clicking on, so I guess now it's a case of telling the Interior.Colour to look at the cell that is chosen? A: I managed to get it to work.. although not sure if it's the most elegant solution. :) To save confusing it with the code above, which has gotten a bit disjointed and messy, here's all the new working code and the explanation I came up with Code to colour cells in sheet: Dim cell As Range For Each cell In Range("data_table[Date Reviewed]") If cell.Value < Range("Today") Then cell.Interior.ColorIndex = 7 'Magenta ElseIf cell.Value >= Range("Today") And cell.Value <= Range("Thirty_Days") Then cell.Interior.ColorIndex = 3 'Red ElseIf cell.Value > Range("Thirty_Days") And cell.Value <= Range("Sixty_Days") Then cell.Interior.ColorIndex = 45 'Orange ElseIf cell.Value > Range("Sixty_Days") And cell.Value <= Range("Ninety_Days") Then cell.Interior.ColorIndex = 4 'Green ElseIf cell.Value > Range("Ninety_Days") Then cell.Interior.ColorIndex = 19 'Beige End If Next cell This is in UserForm_Initialize() And then to match the cell colour with TextBox.BackColor, I've used the ListBox.ListIndex to get the date, using the following code: Private Sub TextBox47_Change() Me.TextBox47.Text = Format(TextBox47.Text, "dd/mm/yyyy") If (Me.ListBox1.List(ListBox1.ListIndex, 65)) < Range("Today") Then TextBox47.BackColor = RGB(255, 0, 255) 'Magenta ElseIf (Me.ListBox1.List(ListBox1.ListIndex, 65)) >= Range("Today") And (Me.ListBox1.List(ListBox1.ListIndex, 65)) <= Range("Thirty_Days") Then TextBox47.BackColor = RGB(255, 0, 0) 'Red ElseIf (Me.ListBox1.List(ListBox1.ListIndex, 65)) > Range("Thirty_Days") And (Me.ListBox1.List(ListBox1.ListIndex, 65)) <= Range("Sixty_Days") Then TextBox47.BackColor = RGB(255, 153, 0) 'Orange ElseIf (Me.ListBox1.List(ListBox1.ListIndex, 65)) > Range("Sixty_Days") And (Me.ListBox1.List(ListBox1.ListIndex, 65)) <= Range("Ninety_Days") Then TextBox47.BackColor = RGB(0, 255, 0) 'Green ElseIf (Me.ListBox1.List(ListBox1.ListIndex, 65)) > Range("Ninety_Days") Then TextBox47.BackColor = RGB(255, 255, 204) 'Beige End If End Sub I can now call that TextBox.BackColor to set the associated Interior.Color of any other cell I'm forwarding on that value to, such as the Report I'm generating in Sheet2: Sheet2.Range("D105").Value = Me.TextBox47.Text Sheet2.Range("D105").Interior.Color = Me.TextBox47.BackColor Thankyou for your help and patience. It was your comment "So you have a listbox which returns a date" which helped me to see where I was actually getting the date from when hovering over the line of code, rather than it seeing a particular Cell.Address, and hence how I got the above to work. Again, thankyou, and I hope I didn't break too many posting rules in the meantime. :) Apologies, but I couldn't see a thanks button anywhere. Cheers Liam
{ "language": "en", "url": "https://stackoverflow.com/questions/63898322", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Getting Started with EC2 Container Registry This is giving me a headache. Here's what I've done so far * *Created an EC2 Virtual Server Instance, and its running *Installed the AWS CLI *Installed Docker on my EC2 Virtual Server after I SSH'd into it So looking at the docs it tells you how to build an image. Now comes my confusion. Question 1: So am I right by assuming that one basically have an option to a) build an image off your host or b) pull an image created by others from Docker Hub? Question 2: If I'm right about Question #1 then what am I building an image ** off of** if I am not pulling one from docker hub? with the AWS docs here? Question 3: then I see a whole different route I can take, using Docker Compose, so I'd use that instead of all this above? This is so confusing. EC2 Container Registry – Now Generally Available So again, here, it tells you to install docker on the Host. Then immediately jumps into "create an image". Create an image off what, that host's OS? I don't get it, I guess that's what it means OR I can pull an image from Docker Hub and not go this route? Same here, it's talking about creating a docker image, what off the Host? Or..maybe I'm not understanding what "image" means but I assume going this route, instead of pulling a Docker image from Docker Hub that I'm creating an image off my EC2 virtual Instance? A: A1: No. You can't build an image off your host. You can create an new image according to your requirement like which Operating Sytem (Ubuntu, Fedora), Stack(LAMP, LEMP) and many other things. Or you can pull an image which will be pre-configured with all the packages like Wordpress Stack image, Magento stack image, Bitnami image which you can pull from docker-hub. A2: As I have mentioned earlier you can build an image of any operating system you want(Ubuntu, Fedora, Debian) but not off the host. You just need to pull image from docker-hub. e.g docker pull ubuntu will pull mininmal image of Ubuntu-14.04. And if you need specific version of Ubuntu like Ubuntu-12.04 version e.g docker pull ubuntu:12.04 will pull minimal image of Ubuntu-12.04 A3: Docker-compose is a tool for defining and running multi-container docker applications. docker-compose conatins a compose file in which you can configure your application services. And finally Amazon EC2 Container Registry is little bit different thing. The Idea is the same as docker but Amazon is providing this as a EC2 Container Service with many other functionality which docker doesn't have right now. Hope it hepls:-)
{ "language": "en", "url": "https://stackoverflow.com/questions/34504427", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: What does Qt do if an error occurs in a constructor? It is generally recommended to raise an exception if an error occurs in the constructor of a class. In Qt, none of the classes throw an exception (as far as I know). How does Qt handle errors that occur in constructors? A: As you said Qt does not use exceptions, building a QObject will not fail on the Qt side (still the C++ memory allocation could fail). What kind of error in constructor do you have in mind? Qt will create object with an invalid state if necessary, in my opinion it is not a constructor error that should cancel the object creation but more of a not-fully-initialized-yet-to-work-well object-state. Examples: QRegExp regex1; // isValid() : false QRegExp regex2("nop{"); // isValid() : false // regex2.errorString() => "bad repetition syntax" QSqlDatabase db; // isValid() : false QDate date1; // isValid() : false QDate date2(0, 0, 0); // isValid() : false QDate date3(-1, 0, 1024); // isValid() : false QString str1; // isNull() : true, isEmpty() : true QString str2(""); // isNull() : false, isEmpty() : true
{ "language": "en", "url": "https://stackoverflow.com/questions/48414296", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Is it possible to create single SQL query for dozens of UPDATE statements? Should it increase performace? How should it look like in my case? I have a problem. In code below there is a foreach loop, where is created query string for each object truck inside of trucks collection. The loop iterates 100 times (100 objects in the collection, for the example). And method with the loop is called 2000 times. I resigned from using of ORM to get better performance. But, unfortunatelly, I am still disapointed a bit with code execution speed. Please note, that for each iterated object there is created string query, that looks, for the example, like this: UPDATE dbo.Trucks SET OfficialNumber = '5124095' , Status = 'Undefined' , PerformancesUpdate = @PerformancesUpdate , PictureLink = 'http://www.somewebsite.com/photos/middle////.jpg' WHERE TruckId = 405664; and next, after parsing command.Parameters, if they exists (in this case @PerformancesUpdate), the query is sent via library method with int rows = command.ExecuteNonQuery(); //execute SQL. And so on, 100 times. Please note, that query string depends on object properties, so every case will be different a bit. Here are my questions. I am wondering, is it possible to create one query for all 100 objects in the loop and sending it at once? If yes, should it increase performance? If yes, How the sample query should look like? And here is the code that creates loop, where are created and executed SQL queries: using (SqlConnection connection = GetConnection(_connectionString)) using (SqlCommand command = connection.CreateCommand()) { connection.Open(); foreach (SomeObject truck in trucks) { Console.WriteLine("Updating " + counter++ + " of " + trucks.Count); //clean up string for basic data truck.Status = CleanUpStringCases(truck.Status); truck.Destination = CleanUpStringCases(truck.Destination); //clean up string for full AIS data if (dataType == "full") { truck.TruckType = CleanUpStringCases(truck.TruckType); } //PARSE SomeObject existing = new SomeObject(); //find existing truck to be updated if (truck.OfficialNumber > 0) existing = _context.trucks.Where(v => v.OfficialNumber == truck.OfficialNumber).FirstOrDefault(); StringBuilder querySb = new StringBuilder(); if (existing != null) { //update for basic data querySb.Append("UPDATE dbo." + _trucksTableName + " SET OfficialNumber = '" + truck.OfficialNumber + "'"); if (existing.MNCI == 0) if (truck.MNCI.HasValue) querySb.Append(" , MNCI = '" + truck.MNCI + "'"); if (truck.LatestActivity.HasValue) querySb.Append(" , LatestActivity = @LatestActivity"); if (truck.ETA.HasValue) querySb.Append(" , ETA = @ETA"); if (!string.IsNullOrEmpty(truck.Status)) querySb.Append(" , Status = '" + truck.Status + "'"); if (!string.IsNullOrEmpty(truck.Destination)) querySb.Append(" , Destination = '" + truck.Destination + "'"); if (!string.IsNullOrEmpty(truck.Area)) querySb.Append(" , Area = '" + truck.Area + "'"); if (truck.HeadingTo.HasValue) querySb.Append(" , HeadingTo = @HeadingTo"); if (truck.Lat.HasValue) querySb.Append(" , Lat = @Lat"); if (truck.Lon.HasValue) querySb.Append(" , Lon = @Lon"); if (truck.Speed.HasValue) { querySb.Append(" , Speed = @Speed"); if ((existing.SpeedMax < truck.Speed || existing.SpeedMax == null) && truck.Speed != 0) querySb.Append(" , SpeedMax = @Speed"); //update speed max } //string for full AIS data if (dataType == "full") { if (truck.PerformancesUpdate.HasValue) querySb.Append(" , PerformancesUpdate = @PerformancesUpdate"); if (!string.IsNullOrEmpty(truck.TruckType)) querySb.Append(" , TruckType = '" + truck.TruckType + "'"); if (!string.IsNullOrEmpty(truck.PictureLink)) querySb.Append(" , PictureLink = '" + truck.PictureLink + "'"); if (truck.LOA.HasValue) querySb.Append(" , LOA = '" + truck.LOA + "'"); if (truck.Height.HasValue) querySb.Append(" , Height = '" + truck.Height + "'"); } querySb.Append(" WHERE truckId = " + existing.truckId + "; "); } try { string query = querySb.ToString(); command.CommandText = query; if (query.Contains("LatestActivity =")) command.Parameters.AddWithValue("@LatestActivity", truck.LatestActivity); if (query.Contains("ETA =")) command.Parameters.AddWithValue("@ETA", truck.ETA); if (query.Contains("PerformancesUpdate =")) command.Parameters.AddWithValue("@PerformancesUpdate", truck.PerformancesUpdate); if (query.Contains("HeadingTo =")) command.Parameters.AddWithValue("@HeadingTo", truck.HeadingTo); if (query.Contains("Lat =")) command.Parameters.AddWithValue("@Lat", truck.Lat); if (query.Contains("Lon =")) command.Parameters.AddWithValue("@Lon", truck.Lon); if (query.Contains("Speed =")) command.Parameters.AddWithValue("@Speed", truck.Speed); command.CommandTimeout = 30; command.CommandType = CommandType.Text; int rows = command.ExecuteNonQuery(); //execute SQL command.Parameters.Clear(); } catch (Exception ex) { Console.WriteLine(ex.Message); } } connection.Close(); } Solution: Martin`s approach is marked as a solution. And answering question about increasing performance, after testing his approach on local DB I can tell, that DB update speed increases directly proportional on quantity of updated rows in single query. For the example, when updating 300 rows, it took me around 30s, together with API requests. When updating 1000 rows, it all takes around 80s. And, as guys mentioned, the only limitation is the number of parameters, so I am just converting doubles and DateTime to SQL format, getting rid of parameters, and voila. A: Yes, it is possible to send multiple update commands on one operation. You would need to add the commands to your string builder and number the SQL parameters. SqlCommand command = connection.CreateCommand() var querySb = new Stringbuilder(); for(int i = 0; i < trucks.Count; i++) { [...] if (truck.Speed.HasValue) { querySb.Append(" , Speed = @Speed" + i); command.Parameters.AddWithValue("@Speed" + i, truck.Speed); } querySb.AppendLine(); } command.CommandText = querySb.ToString(); command.ExecuteNonQuery(); You might create smaller batches of rows (not send all rows at once), maximum number of parameters in one command is 2,098. A: I recommend using some kind of bulk operations, since multiple separate db roundtrips produces excess overhead (as you have noticed). Bulk updates can be implemented i.e with following methods: * *By using external library which is specialized on high-speed Bulk operations *By crafting sql stored procedure which takes array of data as parameter. More information about table-valued parameters can be found in https://learn.microsoft.com/en-us/sql/relational-databases/tables/use-table-valued-parameters-database-engine *Store all the rows with a BULK INSERT operation to a temporary table and run the T-SQL MERGE operation from temp table to actual data table with a single database transaction.
{ "language": "en", "url": "https://stackoverflow.com/questions/61115981", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Nightwatch: Basic auth with access_key not working I created nightwatch.json file like below (with username and access_key properties): "test_settings": { "default": { "launch_url": "http://localhost", "selenium_port": 4444, "selenium_host": "localhost", "silent": true, "cli_args": { "webdriver.firefox.profile": "testprofile" }, "screenshots": { "enabled": false, "path": "screenshots/" }, "desiredCapabilities": { "browserName": "firefox", "javascriptEnabled": true, "acceptSslCerts": true }, "username": "examplelogin", "access_key": "password" } but basic auth don't work and I get login window to fill my password and login after running tests. I looked at packets in fiddler and no authorization header was present. Any ideas what I'm doing wrong? Nightwatch v0.9.6 A: from: https://groups.google.com/d/msg/nightwatchjs/n-B4HnnzYg8/rmaipXiTsuwJ Replying to my own post before - please don't confuse the username and access_key vars as 'basic auth' ones. They are selenium based authenticators which can optionally be used for authenticating against cloud solutions. Best solution for basic auth is the good old URL way. Try: ``` browser.url('https://' + userName + ':' + password + '@' + yourUrl) A: You can do this in globals.js. It will preserve credentials and skip basic auth prompt. beforeEach: function (browser, cb) { if (browser.globals.basic_auth_url) { browser.url(browser.globals.basic_auth_url, cb); } else { cb(); } }, basic_auth_url - add full URL with credentials. Do not add credentials to launch_url
{ "language": "en", "url": "https://stackoverflow.com/questions/39096176", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }