text
stringlengths
15
59.8k
meta
dict
Q: How in Powershell see all XML Levels I have a test xml and I want to get the value from this line ATTRIBUTE NAME="News- offers_OPT_EMAIL">F so I can check for the value F or T if I do below I can get the title but how do I get the above line value. [xml]$xml = Get-Content testFile.xml $xml $xml.CUSTOMERS.CUSTOMER.NAME.TITLE sample XML code <?xml version="1.0" encoding="UTF-8"?> <CUSTOMERS xml:lang="en"> <CUSTOMER CREATED_DATE="2018-01-01 05:18:53.0" GROUP_ID="" ID="95656565"> <NAME> <TITLE>M</TITLE> <FIRST_NAME>Joe</FIRST_NAME> <LAST_NAME>Smith</LAST_NAME> </NAME> <GENDER/> <DATE_OF_BIRTH/> <ADDRESS> <ADDRESS_LINE_1>1 White House</ADDRESS_LINE_1> <ADDRESS_LINE_2>Old Ave</ADDRESS_LINE_2> <ADDRESS_LINE_3/> <TOWNCITY>LONDON</TOWNCITY> <COUNTY/> <POSTCODE>18659</POSTCODE> <COUNTRY>France</COUNTRY> </ADDRESS> <ADDRESS> <ADDRESS_LINE_1>175 avenue de la division Leclerc</ADDRESS_LINE_1> <ADDRESS_LINE_2/> <ADDRESS_LINE_3/> <TOWNCITY>Antony</TOWNCITY> <COUNTY/> <POSTCODE>92160</POSTCODE> <COUNTRY>France</COUNTRY> </ADDRESS> <CONTACT_DETAILS> <TELEPHONE MARKETING_OPT_IN="F" TYPE="MOBILE">0123456789</TELEPHONE> <EMAIL MARKETING_OPT_IN="F">johnsmith@gmail.com</EMAIL> </CONTACT_DETAILS> <ATTRIBUTE NAME="News- offers_OPT_EMAIL">F</ATTRIBUTE> <NOTE>NA</NOTE> </CUSTOMER> A: You could use SelectSingleNode or SelectNodes with an XPath expression. There are several options to achieve what you want, depending on your intention, but this would be one way to do it: # finde the nodes $nodes = $xml.SelectNodes("//*[local-name()='ATTRIBUTE'][@NAME='News- offers_OPT_EMAIL']") # get value $nodes.InnerText Or if the value of the attribute doesn't matter, simply do: $xml.customers.customer.attribute.'#text'
{ "language": "en", "url": "https://stackoverflow.com/questions/64371411", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: String concatenation without libraries in C I am having trouble concatenating strings in C without library function. I tried the following: #include <stdio.h> struct word { char *str; int wordSize; }; void concat(struct word words[], int arraySize, int maxSize) { // word array, its size, and max size given char result[maxSize]; int resultSize = 0; struct word tmp; for (int i = 0; i < arraySize; i++) { tmp = words[i]; for (int j = 0; j < words[i].wordSize; j++, resultSize++) { result[resultSize + j] = tmp.str[j]; } } puts(result); } For example, if the struct array words contain [{"he", 2}, {"ll", 2}, {"o", 1}], the result should be hello. However, this code prints h�l�o where the second and fourth letters are questionmark. Can anyone help me debug this? A: Keep it simple and the bugs will fix themselves. Don't mix up the position in the result buffer with the loop iterators. No need for temporary variables. #include <stdio.h> typedef struct { char *str; int wordSize; } word; void concat(word words[], int arraySize, int maxSize) { char result[maxSize]; int count=0; for(int i=0; i<arraySize; i++) { for(int j=0; j<words[i].wordSize; j++) { result[count]= words[i].str[j]; count++; } } result[count] = '\0'; puts(result); } int main() { word w[3] = { {"he", 2}, {"ll", 2}, {"o", 1} }; concat(w, 3, 128); } A: In this for loop for (int j = 0; j < words[i].wordSize; j++, resultSize++) { result[resultSize + j] = tmp.str[j]; } you are incrementing resultSize and j simultaneously while you need to increase only the variable j and after the loop increase the variable resultSize by j. But in any case the function is wrong because there is no check that resultSize is less than maxSize. And moreover the built string is not appended with the terminating zero '\0'. As a result this statement puts(result); invokes undefined behavior. There is no need to create the variable length array char result[maxSize]; just to output the concatenated string. The function can be declared and defined the following way as it is shown in the demonstrative program below. #include <stdio.h> struct word { char *str; int wordSize; }; void concat( const struct word words[], size_t arraySize, size_t maxSize ) { for ( size_t i = 0, j = 0; i < maxSize && j < arraySize; j++ ) { for ( size_t k = 0; i < maxSize && k < words[j].wordSize; i++, k++ ) { putchar( words[j].str[k] ); } } putchar( '\n' ); } int main(void) { struct word words[] = { { "he", 2 }, { "ll", 2 }, { "o", 1 } }; const size_t arraySize = sizeof( words ) / sizeof( *words ); concat( words, arraySize, 5 ); return 0; } The program output is hello A: You have a couple of problems here. result[resultSize + j] means you are effectively skipping over half the characters in result. Secondly, if you copy the entire string, including the null character, puts will stop printing the result string at the end of the first word itself. So you need to skip copying the string terminator and put it in at the end of your whole concatenated string. #include <stdio.h> struct word { char *str; int wordSize; }; void concat(struct word words[], int maxSize) { // word array and max size given char result[maxSize]; int resultSize = 0; struct word tmp; for (int i = 0; i < 3; i++) { tmp = words[i]; // Keep copying the words to result, one after the other // But drop the last NULL character for (int j = 0; j < (words[i].wordSize - 1); j++, resultSize++) { result[resultSize] = tmp.str[j]; } } // Put the NULL character in after all words have been copied result[resultSize] = 0; puts(result); } struct word mywords[] = { { "TestWord", sizeof("TestWord")}, { "TestWord2", sizeof("TestWord2")} }; int main(void) { concat(mywords, 100); return 0; }
{ "language": "en", "url": "https://stackoverflow.com/questions/63953081", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Instragram - Redirect URI dose not match with registered - Objective C I am getting error while Login with oAuth for Instagram, it says the redirectURI is wrong. I have researched on it and I have checked many answers on stackoverflow but its not helpful for me. Here is the complete detail of what I did in my application. 1) I set my ClientId in pList for redirect URI : 2) I have added ig and authorize while creating the URI: 3)Now, I set ClientID in Instragram API : And Here is my RedirectURI : https://instagram.com/oauth/authorize?response_type=token&redirect_uri=igdd5fb08a33444af0b2b9c9420e69bc35%3A%2F%2Fauthorize&scope=relationships&client_id=dd5fb08a33444af0b2b9c9420e69bc35 When I fire the URl after login, it gives me the following error: Can anyone help to find out where I am going wrong ? Thanks, A: The redirect URI you're providing is not what you have defined in your client settings. 1) Go to http://instagram.com/developer/clients/manage/ 2) For your desired client/application, look for REDIRECT URI. 3) Make sure you provide the same redirect uri in your request as it is defined in your client/application settings. In your case, https://api.instagram.com/oauth/authorize/?response_type=token&redirect_uri=REDIRECT-URI&client_id=CLIENT-ID Note: You may provide an optional scope parameter to request additional permissions outside of the “basic” permissions scope. Note: You may provide an optional state parameter to carry through any server-specific state you need to, for example, protect against CSRF issues. At this point, we present the user with a login screen and then a confirmation screen where they approve your app’s access to his/her Instagram data. 4) Once a user successfully authenticates and authorizes your application, instagram will redirect the user to your redirect_uri with a code parameter that you’ll use to request the access_token like http://your-redirect-uri?code=CODE. For more information to learn about authentication process [Link] tl;dr. The Redirect URI you send to /authorized must be same as the registered URI in your app.
{ "language": "en", "url": "https://stackoverflow.com/questions/22978485", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: c++ rhel confd cdb_get returns elements in a weird order encountring a weird issue with confd. Items are indexed by uint key - when i use configuration with 9 items or lower, everything is ok - cdb_get with index 1 returns the first item, index two the seconds and so on. When i add the 10th item - the 1st item I query i get the correct one ( 1 id ) but when i query for the second item i'll get the 10th item ( like they are sorted in a "stringy" manner, and not int although they are declared as uint in yang schema ). Struggling with this for few days, does anyone have an idea how to correct the return order? Thanks
{ "language": "en", "url": "https://stackoverflow.com/questions/43963836", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to display or hide JSON data on a page based on a string value? I have a form which has an Email field. There is also an option to hide or show email address on a web page depending on which radio button was selected ("YES" or "No"). So, when exclude_email="No" the email should not be displayed. I know it is a conditional statement, but I am lost here... <script> $(function() { var people = []; $.getJSON('data2.json', function(data) { $.each(data, function(i, f) { var tblRow = "<tr>" + "<td>" + f.name + "</td>" + "<td>" + f.title + "</td>" + "<td>" + f.company + "</td>" + "<td>" + "<div style=\"text-align:center\">" + f.email + "</div>" + "</td>" + "<td>" + "<div style=\"text-align:center\">" + f.comment + "</div>" + "</td>" + "</tr>" $(tblRow).appendTo("#userdata tbody"); if (f.exclude_email == "No") this.hide(email); }); }); }); </script> A: You could do it inline when building the string. $(function() { var people = []; $.getJSON('data2.json', function(data) { $.each(data, function(i, f) { var tblRow = "" + "" + f.name + "" + "" + f.title + "" + "" + f.company + "" + "" + "" + (f.exclude_email == "No" ? '' : f.email) + "" + "" + "" + "" + f.comment + "" + "" + "" $(tblRow).appendTo("#userdata tbody"); if (f.exclude_email == "No") this.hide(email); }); }); }); A: This worked! Thank you! $(function() { var people = []; $.getJSON('data2.json', function(data) { $.each(data, function(i, f) { var tblRow = "" + "" + f.name + "" + "" + f.title + "" + "" + f.company + "" + "" + "" + (f.exclude_email == "Yes" ? '' : f.email) + "" + "" + "" + "" + f.comment + "" + "" + "" $(tblRow).appendTo("#userdata tbody"); }); }); });
{ "language": "en", "url": "https://stackoverflow.com/questions/52561400", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Building a table from Python nested dictionaries with missing values Here's the current data structure I have: {'bin1': {'A': 14545, 'B': 18579, 'C': 5880, 'D': 20771, 'E': 404396}, 'bin2': {'A': 13200, 'B': 12279, 'C': 5000, 'D': 16766, 'E': 200344}, [...] } And I'd like to write to a table, in the form: A B C D E bin1 14545 18579 5880 20771 494396 bin2 13200 12279 5000 16766 200344 ... Currently I'm using a crude print loop (where d == the dictionary described above): # print the table header labs = [i for i in d[d.keys()[0]]] print "bin" + "\t" + "\t".join(labs) # loop and print the values for j in d: print j + "\t" + "\t".join(map(str, [d[j][q] for q in d[j]])) Which appeared to work (despite obviously being unordered), however in my output I've found that some nested dictionaries don't contain all fields A-E. I guess one way to do this is to rebuild the dictionary, maybe using a more appropriate matrix-type data structure and fill in the missing values with 0, but given I have this huge nested dictionary to hand, is there a smarter way of printing the output shown above that could handle missing elements? A: Using pandas: import pandas as pd data = {'bin1': {'A': 14545, 'B': 18579, 'C': 5880, 'D': 20771, 'E': 404396}, 'bin2': {'A': 13200, 'D': 16766, 'E': 200344}, } df = pd.DataFrame(data).T df.fillna(0, inplace=True) print(df) prints A B C D E bin1 14545 18579 5880 20771 404396 bin2 13200 0 0 16766 200344 The df.fillna(0) replaces missing values with 0. A: You can use d[j].get(q, '0') instead of d[j][q] to fill in 0 for all missing entries: # print the table header labs = sorted(max(d.values(), key=len)) print "bin" + "\t" + "\t".join(labs) # loop and print the values for j in d: print j + "\t" + "\t".join(str(d[j].get(q, '0')) for q in labs) I also made some slight modifications to the other parts of the code so the columns are ordered.
{ "language": "en", "url": "https://stackoverflow.com/questions/18746278", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: Using generic class as type parameter I would like to use a generic class as a type parameter for another generic class. At first my class definition was like this: class Foo<T, R extends BaseDto> {} Then my requirements changed and I had to use a wrapper/holder class for my R type My attempt so far: (Gives compile-time error: class or interface expected on Bar<R>) class Bar<T extends BaseDto> { private T dto; public Bar(T dto) { this.dto= dto; } // getters and setters } class Foo<T, Bar<R>> { private T entity; private R dto; // getters and setters } I can not use it as Foo<T, Object> because then the clients using this class would not know that they actually need a cast from Object to Bar. How would I implement such behaviour? A: Instead of changing the class header, replace everywhere in the class where you used R with Bar<R>. So the class header stays the same: class Foo<T, R extends CustomClass> But let's say you have a field of type R. That needs to be changed to Bar<R>: Bar<R> someField; A: It looks like what you need may be: class Foo<T, R extends CustomClass, S extends Bar<R>> A: You would use class Foo<T extends CustomClass, R extends Bar<T>> {} If Bar is fixed, i.e., if the user does not need another class extending Bar, then you need to get rid of R and just use Bar<T> inside Foo
{ "language": "en", "url": "https://stackoverflow.com/questions/60090167", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How to get cumulative sum of unique IDs with group by? I am very new to python and pandas working on a pandas dataframe which looks like Date Time ID Weight Jul-1 12:00 A 10 Jul-1 12:00 B 20 Jul-1 12:00 C 100 Jul-1 12:10 C 100 Jul-1 12:10 D 30 Jul-1 12:20 C 100 Jul-1 12:20 D 30 Jul-1 12:30 A 10 Jul-1 12:40 E 40 Jul-1 12:50 F 50 Jul-1 1:00 A 40 I am trying to achieve group by date, Time and ids and apply cumulative sum such that if an id is present in the next time-slot the weight is only added once(uniquely). The resulting data frame would look like this Date Time Weight Jul-1 12:00 130 (10+20+100) Jul-1 12:10 160 (10+20+100+30) Jul-1 12:20 160 (10+20+100+30) Jul-1 12:30 160 (10+20+100+30) Jul-1 12:40 200 (10+20+100+30+40) Jul-1 12:50 250 (10+20+100+30+40+50) Jul-1 01:00 250 (10+20+100+30+40+50) This is what I tried below, however this is still counting the weights multiple times: df=df.groupby(['date','time','ID'])['Wt'].apply(lambda x: x.unique().sum()).reset_index() df['cumWt']=df['Wt'].cumsum() Any help would be really appreciated! Thanks a lot in advance!! A: The code below uses pandas.duplicate(), pandas.merge(), pandas.groupby/sum and pandas.cumsum() to come to the desired output: # creates a series of weights to be considered and rename it to merge unique_weights = df['weight'][~df.duplicated(['weight'])] unique_weights.rename('consider_cum', inplace = True) # merges the series to the original dataframe and replace the ignored values by 0 df = df.merge(unique_weights.to_frame(), how = 'left', left_index=True, right_index=True) df.consider_cum = df.consider_cum.fillna(0) # sums grouping by date and time df = df.groupby(['date', 'time']).sum().reset_index() # create the cumulative sum column and present the output df['weight_cumsum'] = df['consider_cum'].cumsum() df[['date', 'time', 'weight_cumsum']] Produces the following output:
{ "language": "en", "url": "https://stackoverflow.com/questions/55051707", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: jQuery Validate plugin is validating a field which has become "disabled" I have a field gender? which enables is Pregnant? if gender is set to FEMALE, then if is Pregnant? field is unanswered, it's flagged as invalid. If you go back and set gender? to MALE The validation still flags is Pregnant? as invalid, even though it has been disabled. jQuery says disabled fields are ignored. I even tried: jquery.validate validating disabled field ignore: ":hidden" What am I missing? A: this is a valid problem, with this markup <form> <div> Male: <input type="radio" name="gender" value="male" /> Female: <input type="radio" name="gender" value="female" /></div> <br /> <div> Pregnant: <input type="radio" name="pregnant" value="yes" /> Not Pregnant: <input type="radio" name="pregnant" value="no" /></div> <br /> <input type="submit" /> </form> and this script $('[name=gender]').click(function () { var disabled = $(this).val() === 'male'; $('[name=pregnant]').attr('disabled', disabled); // UNCOMMENT THIS TO FIX // if ($('[name=pregnant]').hasClass('error')) { // $('form').validate().form(); // } }); $('input').addClass('required'); $('form').validate({ ignore: ":disabled", errorPlacement: function (error, element) { error.appendTo(element.parent("div")); }, submitHandler: function () { alert('form is ok'); } }); to reproduce the problem: * *click female *click submit *error message shows - this is correct *click male - error message still shows *click submit - form is valid so as @ioan says you need to try and get rid of this error message as it is confusing, even though the form is valid the error message is still there * *problem - http://jsfiddle.net/YzCHJ/4/ *a possible solution - http://jsfiddle.net/YzCHJ/5/ A: The .validate() ignore: option works as follows: ignore, Default: ":hidden" Elements to ignore when validating, simply filtering them out. jQuery's not-method is used, therefore everything that is accepted by not() can be passed as this option. http://docs.jquery.com/Plugins/Validation/validate#toptions Working Demo: http://jsfiddle.net/us9aE/ HTML: <form id="myform"> <input type="text" name="field" disabled="disabled" /> <br/> </form> jQuery: $(document).ready(function() { $('#myform').validate({ ignore: ":disabled" }); }); If you'd like more specific help, please show your relevant HTML, your jQuery, and optionally create a jsFiddle demo. A: The disabled fields are ignored during the validation phase BUT if the validation phase comes into action before the field has been disabled, the error message will still be there. You can try to simply remove the validation message by cleaning the validation errors and re-validate the form.
{ "language": "en", "url": "https://stackoverflow.com/questions/14379913", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: react/prop-types and flow My .eslintrc looks like this and I am using flow: { "extends": [ "plugin:flowtype/recommended", "plugin:react/recommended", "prettier", "prettier/flowtype", "prettier/react" ], "plugins": [ "flowtype", "react", "prettier" ], "parserOptions": { "ecmaVersion": 2016, "sourceType": "module", "ecmaFeatures": { "jsx": true } }, "env": { "es6": true, "node": true }, "rules": { "prettier/prettier": ["error", { "singleQuote": true, "trailingComma": "none", "bracketSpacing": true, "jsxBracketSameLine": false, "parser": "flow" }] }, "settings": { "flowtype": { "onlyFilesWithFlowAnnotation": true } } } I am still getting react react/prop-types even though I am using flow. Is this correct and should I just turn them off? A: PropTypes are for runtime type checking, while Flow is for static type checking. Both serve their own purpose, not all type errors can be caught during compilation, so PropTypes helps you with those; Flow can catch some errors early - before you interact with your app, or even load it to the browser.
{ "language": "en", "url": "https://stackoverflow.com/questions/44872197", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Terraform breaking Azure Logic App connections I am creating an Azure Logic App (using it to unzip to a blob storage). For this I need the Logic App workflow and a connection to the blob storage. I create the empty Logic App Workflow with Terraform and the actual Logic App implementation with Visual Studio that I just then deploy to the Logic App created with tf. I use following tf code to create the empty Logic App Workflow: resource "azurerm_logic_app_workflow" "logic_unzip" { name = "ngh-${var.deployment}-unziplogic" resource_group_name = "${azurerm_resource_group.rg.name}" location = "${azurerm_resource_group.rg.location}" } As the Logic App needs connection to the Blob storage I will use following template to create it: resource "azurerm_template_deployment" "depl_connection_azureblob" { name = "azureblob" resource_group_name = "${azurerm_resource_group.rg.name}" template_body = <<DEPLOY { "$schema": "https://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#", "contentVersion": "1.0.0.0", "parameters": { "connection_name": {"type": "string"}, "storage_name": {"type": "string"}, "storage_access_key": {"type": "string"}, "location": {"type": "string"}, "api_id": {"type": "string"} }, "resources": [{ "type": "Microsoft.Web/connections", "name": "[parameters('connection_name')]", "apiVersion": "2016-06-01", "location": "[parameters('location')]", "scale": null, "properties": { "displayName": "[parameters('connection_name')]", "api": { "id": "[parameters('api_id')]" }, "parameterValues": { "accountName": "[parameters('storage_name')]", "accessKey": "[parameters('storage_access_key')]" } }, "dependsOn": [] }] } DEPLOY parameters = { "connection_name" = "azureblob" "storage_name" = "${azurerm_storage_account.sa-main.name}" "storage_access_key" = "${azurerm_storage_account.sa-main.primary_access_key}" "location" = "${azurerm_resource_group.rg.location}" "api_id" = "${data.azurerm_subscription.current.id}/providers/Microsoft.Web/locations/${azurerm_resource_group.rg.location}/managedApis/azureblob" } deployment_mode = "Incremental" } Running plan and apply, these work perfect. In Visual Studio I can then create the Logic App and use the azureblob connection to select the correct blob storage. Now, when I have deployed the Logic App Workflow from Visual Studio and run terraform plan I get following changes: An execution plan has been generated and is shown below. Resource actions are indicated with the following symbols: ~ update in-place Terraform will perform the following actions: ~ azurerm_logic_app_workflow.logic_unzip parameters.$connections: "" => "" parameters.%: "1" => "0" Plan: 0 to add, 1 to change, 0 to destroy. Running the apply command now will break the Logic App as it removes the bound connection. Clearly the Visual Studio deploy has created the binding between the Logic App and the connection. How can I tell Terraform not to remove the connections (created by the Visual Studio deploy) from the Logic App? A: Terraform is not aware of the resources deployed in the arm template, so it detects the state change and tries to "fix" that. I dont see any CF resources for logic app connections, so seeing how it detects that parameters.connections changed from 0 to 1 adding your connection directly to the workflow resource might work, but CF mentions : Any parameters specified must exist in the Schema defined in workflow_schema, but I dont see connections in the schema, which is a bit weird, but I assume I'm misreading the schema you can also use ignore_changes: lifecycle { ignore_changes = [ "parameters.$connections" ] } according to the comments and this reading: https://www.terraform.io/docs/configuration/resources.html#ignore_changes
{ "language": "en", "url": "https://stackoverflow.com/questions/55217929", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: std::transform() and toupper(), no matching function I tried the code from this question C++ std::transform() and toupper() ..why does this fail? #include <iostream> #include <algorithm> int main() { std::string s="hello"; std::string out; std::transform(s.begin(), s.end(), std::back_inserter(out), std::toupper); std::cout << "hello in upper case: " << out << std::endl; } Theoretically it should've worked as it's one of the examples in Josuttis' book, but it doesn't compile http://ideone.com/aYnfv. Why did GCC complain: no matching function for call to ‘transform( __gnu_cxx::__normal_iterator<char*, std::basic_string <char, std::char_traits<char>, std::allocator<char> > >, __gnu_cxx::__normal_iterator<char*, std::basic_string <char, std::char_traits<char>, std::allocator<char> > >, std::back_insert_iterator<std::basic_string <char, std::char_traits<char>, std::allocator<char> > >, <unresolved overloaded function type>)’ Am I missing something here? Is it GCC related problem? A: Just use ::toupper instead of std::toupper. That is, toupper defined in the global namespace, instead of the one defined in std namespace. std::transform(s.begin(), s.end(), std::back_inserter(out), ::toupper); Its working : http://ideone.com/XURh7 Reason why your code is not working : there is another overloaded function toupper in the namespace std which is causing problem when resolving the name, because compiler is unable to decide which overload you're referring to, when you simply pass std::toupper. That is why the compiler is saying unresolved overloaded function type in the error message, which indicates the presence of overload(s). So to help the compiler in resolving to the correct overload, you've to cast std::toupper as (int (*)(int))std::toupper That is, the following would work: //see the last argument, how it is casted to appropriate type std::transform(s.begin(), s.end(), std::back_inserter(out),(int (*)(int))std::toupper); Check it out yourself: http://ideone.com/8A6iV A: Problem std::transform( s.begin(), s.end(), std::back_inserter(out), std::toupper ); no matching function for call to ‘transform(__gnu_cxx::__normal_iterator<char*, std::basic_string<char, std::char_traits<char>, std::allocator<char> > >, __gnu_cxx::__normal_iterator<char*, std::basic_string<char, std::char_traits<char>, std::allocator<char> > >, std::back_insert_iterator<std::basic_string<char, std::char_traits<char>, std::allocator<char> > >, <unresolved overloaded function type>)’ This is a misleading error; the interesting part is not that there's "no matching function" for the call, but why there's no matching function. The why is that you're passing a function reference of an "<unresolved overloaded function type>" as an argument, and GCC prefers to error on the call rather than on this overload resolution failure. Explanation First, you should consider how the C library is inherited in C++. <ctype.h> has a function int toupper(int). C++ inherits this: [n3290: 21.7/1]: Tables 74, 75, 76, 77, 78, and 79 describe headers <cctype>, <cwctype>, <cstring>, <cwchar>, <cstdlib> (character conversions), and <cuchar>, respectively. [n3290: 21.7/2]: The contents of these headers shall be the same as the Standard C Library headers <ctype.h>, <wctype.h>, <string.h>, <wchar.h>, and <stdlib.h> and the C Unicode TR header <uchar.h>, respectively [..] [n3290: 17.6.1.2/6]:Names that are defined as functions in C shall be defined as functions in the C++ standard library. But using <ctype.h> is deprecated: [n3290: C.3.1/1]: For compatibility with the Standard C library, the C++ standard library provides the 18 C headers (D.5), but their use is deprecated in C++. And the way to access the C toupper is through the C++ backwards-compatibility header <cctype>. For such headers, the contents are either moved or copied (depending on your implementation) into the std namespace: [n3290: 17.6.1.2/4]: [..] In the C++ standard library, however, the declarations (except for names which are defined as macros in C) are within namespace scope (3.3.6) of the namespace std. It is unspecified whether these names are first declared within the global namespace scope and are then injected into namespace std by explicit using-declarations (7.3.3). But the C++ library also introduces a new, locale-specific function template in header <locale>, that's also called toupper (of course, in namespace std): [n3290: 22.2]: [..] template <class charT> charT toupper(charT c, const locale& loc); [..] So, when you use std::toupper, there are two overloads to choose from. Since you didn't tell GCC which function you wish to use, the overload cannot be resolved and your call to std::transform cannot be completed. Disparity Now, the OP of that original question did not run into this problem. He likely did not have the locale version of std::toupper in scope, but then again you didn't #include <locale> either! However: [n3290: 17.6.5.2]: A C++ header may include other C++ headers. So it just so happens that either your <iostream> or your <algorithm>, or headers that those headers include, or headers that those headers include (etc), lead to the inclusion of <locale> on your implementation. Solution There are two workarounds to this. * *You may provide a conversion clause to coerce the function pointer into referring to the overload that you wish to use: std::transform( s.begin(), s.end(), std::back_inserter(out), (int (*)(int))std::toupper // specific overload requested ); *You may remove the locale version from the overload set by explicitly using the global toupper: std::transform( s.begin(), s.end(), std::back_inserter(out), ::toupper // global scope ); However, recall that whether or not this function in <cctype> is available is unspecified ([17.6.1.2/4]), and using <ctype.h> is deprecated ([C.3.1/1]). Thus, this is not the option that I would recommend. (Note: I despise writing angle brackets as if they were part of header names — they are part of #include syntax, not header names — but I've done it here for consistency with the FDIS quotes; and, to be honest, it is clearer...) A: std::transform(s.begin(), s.end(), s.begin(), std::bind(&std::toupper<char>, std::placeholders::_1, std::locale())); If you use vc toolchain,please include locale
{ "language": "en", "url": "https://stackoverflow.com/questions/7131858", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "70" }
Q: String to javascript in Firefox extension (without eval(), setTimeout or new Function) I'm passing strings such as "getElementById('div1')" or "getElementsByName('div2')" from a remote server depending on the page the user opens. How can I run these as javascript in the page without using any of the above mentioned functions. A: var head = document.getElementsByTagName('head')[0], script = document.createElement('script'); script.innerHTML = 'alert("hello");'; head.appendChild(script); A: You may be able to use document.write. I don't know if you can use that for javascript, but I recommend that the server should pass codes plus an element name to the client, and then execute a certain method based off of that.
{ "language": "en", "url": "https://stackoverflow.com/questions/11218854", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Specific object selection in xcode Is there way to select object by their specific tag without the use of a loop? So instead: for (UIImageView *someObject in [self.view subviews]) { if (someObject.tag == someInteger) { [someObject removeFromSuperview]; } } Use something with a more direct approach like: [[UIImageView.whereTagEquals someInteger] removeFromSuperview]; Although I think if there was such an option it would work the same way. It would loop "behind the scene" all the UIImageViews and do something if it found the right one. Or maybe someone can help me get the same desired result with a different approach. I notice that because of too much loops my game starts to slow down at a certain point. Thank you! A: A one liner you can use is -[UIView viewWithTag:], but this will likely loop internally as well. A faster approach for lots of views is to use an NSDictionary (NSNumber instances as keys plus views as values). Dictionaries use hashes internally so they're faster in most cases. A: Try this: [[self.view viewWithTag:someInteger] removeFromSuperview];
{ "language": "en", "url": "https://stackoverflow.com/questions/8285883", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Get list of answers per city I have this db: Users-table: +----+---------+ | id | city_id | +----+---------+ city_id -> references id on city Cities-table: +----+------+ | id | city | +----+------+ Answers-table: +----+---------+ | id | user_id | +----+---------+ user_id -> references id on users Now I want a query with this result: +-----------+--------+ | City-name | amount | +-----------+--------+ | New York | 500 | +-----------+--------+ I tried several joins, count, dinstincts but no success. Think it should be quite easy but didnt manage to do it. My query: SELECT cities.name, COUNT(answers.id) FROM answers JOIN users ON users.id = answers.user_id JOIN cities on users.city_id = cities.id but gives me only 1 city.. A: You need to add GROUP BY cities.name SELECT cities.name, COUNT(answers.id) FROM answers JOIN users ON users.id = answers.user_id JOIN cities on users.city_id = cities.id GROUP BY cities.name This will tell MySQL that you want the COUNT to be grouped by cities. Without this, mysql will group everything together and count it all. A: You should be aggregating to get a count, etc. So something like: SELECT COALESCE(c.city, '<Unknown>') AS Cityname, COUNT(a.id) AS amount FROM Answers AS a LEFT JOIN Users AS u ON a.user_id = u.id LEFT JOIN Cities AS c ON u.city_id = c.id GROUP BY c.city
{ "language": "en", "url": "https://stackoverflow.com/questions/22194000", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How browsers will convert mixins to regular css In Less and Sass we make use of lots of mixins, how does the browser compile or converts those mixins to regular CSS and apply those styles? A: The browser DOES NOT convert pre-processed (LESS, SCSS, Compass) CSS rules. You need to use a build script/compiler BEFORE linking a normal CSS file to your HTML. This process converts SCSS/LESS -> CSS for your browser to render. You can use Webpack, Grunt, Gulp, or even desktop/GUI tools to do this. You can also use a javascript parser to inject the final CSS into the page onLoad but this has performance implications and IS NOT recommended.
{ "language": "en", "url": "https://stackoverflow.com/questions/57597654", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-6" }
Q: QAF Reports are not populated in dashboard.htm * *Got the latest code here: https://github.com/infostretch/qaf-report. *Extracted dashboard directory & dashboard.htm to the project root directory. *Ran QAF tests. *Opened dashboard.htm during test run & also after test run. *Tried to open dashboard.htm in Google Chrome, Firefox & Safari after giving permissions to access local files. But Dashboard.htm did not load anything. A spinning icon is displayed continously even after several minutes. Am I missing anything here? A: If you are accessing reports locally as file protocol, browser may have restriction to access local files. In such case follow the steps to allow local file access from file for the browser you are using. Firefox: go to about:config set security.fileuri.strict_origin_policy:false. Safari: Click on the Develop menu in the menu bar. Select Disable Local File Restrictions. If develop menu is not available, Click on the Edit > Preferences > Advanced tab. Check "Show Develop menu in the menu bar. chrome: Close down your Chrome browser (make sure you close all instances if you have multiple windows open) Go to Run and type the following command: chrome.exe --allow-file-access-from-file. Hit enter. Reference from local-report-access A: I just want to give more clarity by making little corrections to the existing steps mentioned here: https://github.com/infostretch/qaf-report#local-report-access When you are opening report "dashboard.htm" from local file system, your browser may have local file access restrictions. In that case, you can do following setings: * *Firefox: * *Enter "about:config" in the browser url field & click on the button "Accept the Risk & Continue". *In the "search preference name" field, enter "security.fileuri.strict_origin_policy" & click Enter & click on the toggle button towards the right to set it FALSE. *Safari: * *Click on the Develop menu in the menu bar. *Select Disable Local File Restrictions. If develop menu is not available, 1. Click on the Safari > Preferences > Advanced tab(in MAC, Safari > Preferences > Advanced tab). 2. Check "Show Develop menu in the menu bar. * *Chrome: *In Windows PC: * *Close down your Chrome browser (make sure you close all instances if you have multiple windows open) *Go to Run and type the following command: chrome.exe --allow-file-access-from-file. *In MAC * *Open your terminal anywhere, make sure Google Chrome is currently not running, copy paste this line and hit enter: open /Applications/Google\ Chrome.app --args --allow-file-access-from-files
{ "language": "en", "url": "https://stackoverflow.com/questions/62087063", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Elasticsearch: Filter Query not working I've been working to change my query to a filter in Elasticsearch using the java api. I've made sure that the fields I am running searches on are set to "not_analzed". Here is the java code for the filter: FilterBuilder andFilter = FilterBuilders.andFilter(FilterBuilders.termFilter("thread_name", keyword), FilterBuilders.termFilter("site_name", "test_site")); QueryBuilder filteredQuery = QueryBuilders.filteredQuery(QueryBuilders.matchAllQuery(), andFilter); SearchResponse threadResponse = client.prepareSearch("thread_and_messages").setQuery(filteredQuery).setSize(20).setFrom(firstRowOffset).execute().actionGet(); This then gets translated to this in JSON: "filtered" : { "query" : { "match_all" : { } }, "filter" : { "and" : { "filters" : [ { "term" : { "thread_name" : "apple" } }, { "term" : { "site_name" : "test_site" } } ] } } } When I try to do any searches it won't return the document I'm looking for which is thread_name: Apple and site_name: test_site. Also when I run this using a curl command it won't find that document either. Can anyone see what I'm doing wrong here? A: You can use must clause.That will perform and operation "query": { "bool": { "must": [ { "query_string": { "default_field": "thread_name", "query": "apple" } }, { "query_string": { "default_field": "site_name", "query": "test_site" } } ] } }
{ "language": "en", "url": "https://stackoverflow.com/questions/36059126", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Curved arrow along a circle MATPLOTLIB I need to plot some curved arrows which should lie on a circle. I tried with patches.FancyArrowPatch, but I could not find a connectionstyle able to follow a circle. Is there any connectionstyle that I can use to get the arrows of the shape I need? Thanks for any help. This is an example of code I tried: from matplotlib import pyplot as plt, patches from math import pi, sin,cos fig,ax=plt.subplots() ax.set_xlim(-1.05,1.05) ax.set_ylim(-1.05,1.05) # reference circle circ=patches.Circle((0,0),radius=1.0,fill=False,lw=1, color='C0',zorder=10) ax.add_patch(circ) style="Simple,tail_width=0.5,head_width=3,head_length=6" kw = dict(arrowstyle=style, color="C1") ang1=pi/6 ang2=pi/3 rad=0.17 arc=patches.FancyArrowPatch((cos(ang1),sin(ang1)), (cos(ang2),sin(ang2)),connectionstyle="arc3,rad={}".format(rad),shrinkA=0,shrinkB=0,**kw) ax.add_patch(arc) ang1=pi/2 ang2=pi rad=0.4 arc=patches.FancyArrowPatch((cos(ang1),sin(ang1)), (cos(ang2),sin(ang2)),connectionstyle="angle3, angleA=180, angleB=270",shrinkA=0,shrinkB=0,**kw) ax.add_patch(arc) ang1=5*pi/4 ang2=0 rad=0.7 arc=patches.FancyArrowPatch((cos(ang1),sin(ang1)), (cos(ang2),sin(ang2)),connectionstyle="arc3,rad={}".format(rad),shrinkA=0,shrinkB=0,**kw) ax.add_patch(arc) ax.axis('off') ax.set_aspect('equal') and this is the result:
{ "language": "en", "url": "https://stackoverflow.com/questions/60218316", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Drawable from String in Android How do I get a Drawable resource if I have the String (its name) as it appears in the drabale folder? int categoryPicIndex = myCursor.getColumnIndex(CookingContract.CategoryEntry.COLUMN_PIC_CATEGORY); String categoryPic = myCursor.getString(categoryPicIndex); At this point I have the string that I would use to call R.drawable.___ . How can I solve the problem? A: If "yourImageView" is the ImageView and you want to set background of it and the name of image is "imageName" yourImageView.setImageResource(context.getResources(). getIdentifier("drawable/" + imageName, null,context.getPackageName())); But i should say sorry as it doesn't really give you drawable but it gives Resource, But i hope this will help you use the string name of drawable file.
{ "language": "en", "url": "https://stackoverflow.com/questions/37354803", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: domain class field not being displayed on view page I am unable to view all of the below fields when I run my grails app the " Cost" field is not being displayed on the view page, the fields are displayed on the add page. If I remove the "name" field the "cost" field is then displayed. Is there a field limit that im not aware of ? package racetrack class Race { String name Date startDate String city String state BigDecimal distance BigDecimal cost Integer maxRunners = 100000 static constraints = { name() startDate() city() state() distance() cost() maxRunners() } } List.gsp - <%@ page import="racetrack.Race" %> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <meta name="layout" content="main" /> <g:set var="entityName" value="${message(code: 'race.label', default: 'Race')}" /> <title><g:message code="default.list.label" args="[entityName]" /></title> </head> <body> <div class="nav"> <span class="menuButton"><a class="home" href="${createLink(uri: '/')}"><g:message code="default.home.label"/></a></span> <span class="menuButton"><g:link class="create" action="create"><g:message code="default.new.label" args="[entityName]" /></g:link></span> </div> <div class="body"> <h1><g:message code="default.list.label" args="[entityName]" /></h1> <g:if test="${flash.message}"> <div class="message">${flash.message}</div> </g:if> <div class="list"> <table> <thead> <tr> <g:sortableColumn property="id" title="${message(code: 'race.id.label', default: 'Id')}" /> <g:sortableColumn property="name" title="${message(code: 'race.name.label', default: 'Name')}" /> <g:sortableColumn property="startDate" title="${message(code: 'race.startDate.label', default: 'Start Date')}" /> <g:sortableColumn property="city" title="${message(code: 'race.city.label', default: 'City')}" /> <g:sortableColumn property="state" title="${message(code: 'race.state.label', default: 'State')}" /> <g:sortableColumn property="distance" title="${message(code: 'race.distance.label', default: 'Distance')}" /> </tr> </thead> <tbody> <g:each in="${raceInstanceList}" status="i" var="raceInstance"> <tr class="${(i % 2) == 0 ? 'odd' : 'even'}"> <td><g:link action="show" id="${raceInstance.id}">${fieldValue(bean: raceInstance, field: "id")}</g:link></td> <td>${fieldValue(bean: raceInstance, field: "name")}</td> <td><g:formatDate date="${raceInstance.startDate}" /></td> <td>${fieldValue(bean: raceInstance, field: "city")}</td> <td>${fieldValue(bean: raceInstance, field: "state")}</td> <td>${fieldValue(bean: raceInstance, field: "distance")}</td> </tr> </g:each> </tbody> </table> </div> <div class="paginateButtons"> <g:paginate total="${raceInstanceTotal}" /> </div> </div> </body> </html> A: Assuming you're referring to the scaffolded list view, the scaffolding only renders six fields. The basic logic (from src/templates/scaffolding/list.gsp) is: props.eachWithIndex { p, i -> if(i == 0 { // render the field as a link to the show view } else if(i < 6) { // render the field value } } Note that the list of properties includes the id. Since you define six fields in your constraints, the last one's not being displayed (only the id + first five are). Edit To "fix" this, you have some options: * *Update the scaffolded list view code: * *First, run grails install-templates *Open up src/templates/scaffolding/list.gsp *Find the code segment above and change the condition Note that this will change the rendering for all scaffolded and generated list views. *Generate the view and update it manually. It looks like you've already generated the view, so you'll just need to update it. Note that if you generate it again, it will overwrite your changes.
{ "language": "en", "url": "https://stackoverflow.com/questions/7521755", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: XSD for soap result not working I want to check a soap response against a xsd. Here is the xml soap response: <?xml version="1.0" encoding="utf-8"?> <soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <soap:Body> <GetHTMLResponse xmlns="http://www.webserviceX.NET"> <GetHTMLResult> Test </GetHTMLResult> </GetHTMLResponse> </soap:Body> </soap:Envelope> Here is my XSD: <xs:schema attributeFormDefault="unqualified" elementFormDefault="qualified" xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:import namespace="http://schemas.xmlsoap.org/soap/envelope/" schemaLocation="http://schemas.xmlsoap.org/soap/envelope/"/> <xs:element name="GetHTMLResponse"> <xs:complexType> <xs:sequence> <xs:element name="GetHTMLResult" minOccurs="0" maxOccurs="1"> <xs:simpleType> <xs:restriction base="xs:string"> </xs:restriction> </xs:simpleType> </xs:element> </xs:sequence> </xs:complexType> I get this error: Cvc-elt.1: Cannot Find The Declaration Of Element 'soap:Envelope'. Why is this happening? A: Try checking the SOAP response against the following XSD file. I added elements for the outer <soap:Envelope> and <soap:Body> tags which are present in the SOAP response. <?xml version="1.0" encoding="UTF-8" ?> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" targetNamespace="http://www.example.org" xmlns:tns="http://www.w3.org/2003/05/soap-envelope"> <xs:element name="Envelope" type="tns:envType"> <xs:complexType name="envType"> <xs:sequence> <xs:element name="Body" type="tns:bodyType"> <xs:complexType name="bodyType"> <xs:sequence> <xs:element name="GetHTMLResponse"> <xs:complexType> <xs:sequence> <xs:element name="GetHTMLResult" minOccurs="0" maxOccurs="1" type="xs:string"> <xs:simpleType> <xs:restriction base="xs:string"> </xs:restriction> </xs:simpleType> </xs:element> </xs:sequence> </xs:complexType> </xs:element> </xs:sequence> </xs:complexType> </xs:element> </xs:sequence> </xs:complexType> </xs:element> </xs:schema>
{ "language": "en", "url": "https://stackoverflow.com/questions/30839149", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Is this the correct way of presenting the formula in code I am creating a pokemon like game, I am currently trying to add the damage calculations into my game but I am not good at maths or reading formulas, the code I have wrote: func take_damage(move,attacker): var modifier : float = rand_range(0.85,1.0) var a : float = ((2.0 * attacker.level) / 5) + 2 var b : float = a * move.power * (attacker.attack() / defence()) + 2.0 var c : float = b / 50 var damage = round(c * modifier) current_health -= damage print(damage) print(a) print(b) and here is a link to where I found pokemons damage calculation with a formula: https://bulbapedia.bulbagarden.net/wiki/Damage What I want to know is, what I have wrote in my code the same as the formula, thanks!
{ "language": "en", "url": "https://stackoverflow.com/questions/67388822", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How can I model a ordered, variable-length series of string collections in a database? I'm developing an application which has very specific/odd database requirements. I need to store collections of strings. If it helps, one string per collection is designated as "canonical", and the others are "alternatives". The list of collections needs to be ordered, so that I can easily get e.g. the 8th string collection in the list. Finally, I need to be able to insert arbitrary amounts of collections into any point in the list. Obviously a relational database with a simple incremental id column would be great for this except for the fact that you have to be able to insert collections into any point in the list. Then you'd have to update every single item after the inserted one, which isn't ideal. I'm new to databases. I barely know how to use relational databases, much less anything else. Should I use SQL for this, or should I ditch relational databases for a NoSQL approach? I'm lost. A: For structured ordering in a database, you'll want a column to store the ordering. An int is fine, but a decimal can make updates a little easier. Don't use the name "order" for the column, as it's a keyword, consider "display_order". You can create a self-referencing table. A "canonical" term has a null parent id, an "alternative" does not. create table terms ( term_id int primary key, term text not null, parent_term_id int null references terms(term_id), display_order int not null, unique (parent_term_id, term), unique (parent_term_id, display_order) ); Add a canonical term: inset into terms (term_id, term, parent_id, display_order) values (1, 'United Kingdom', null, 0); Add alternative terms, associated w the above: inset into terms (term_id, term, parent_id, display_order) values (2, 'Great Britain', 1, 0), (3, 'England', 1, 1); You can use Recursive Common Table Expressions (except in MySQL) to efficiently query this structure. See Using a sort order column in a database table regarding updating your order column. A: Another form of structuring data in an RDBMS is nested sets. I've played around with them and if they meet your need, they can be vastly superior to self-referential designs. One important consideration is that the ratio of data "movement" (inserts, deletes, updates to change the position) to queries must be low. In other words, the data should be relatively stable. With a nested set design, just one self-join is all that is needed to traverse an entire tree to any arbitrary depth. No recursion! That alone makes it a big selling point for me. :) Unfortunately, while there is information available on the Internet, it is all fairly basic. But if you don't mind playing around to get familiar with it, you just might be glad you did.
{ "language": "en", "url": "https://stackoverflow.com/questions/29585594", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Error: Cannot fit requested classes in a single dex file (# methods: 67593 > 65536) How to solve this error I'm getting in Android Studio: Error: Cannot fit requested classes in a single dex file (# methods: 67593 > 65536) cant build my project now A: Do this 4 step 1: Add this library in dependencies of the app build.gradle : implementation 'com.android.support:multidex:1.0.3' 2: Add in the defaultConfig of the app build.gradle : defaultConfig { //other configs multiDexEnabled true //add this line } 3: Create new Java class like this : public class ApplicationClass extends MultiDexApplication { @Override public void onCreate() { super.onCreate(); } } 4: Add this to your manifest (in application tag): <application android:name=".ApplicationClass" android:icon="@mipmap/ic_launcher" android:label="@string/app_name"> A: Same situation happened in my Visual Studio 2019 Xamarin project, and the way to solve this problem is just like what mentioned in the link: Error:Cannot fit requested classes in a single dex file.Try supplying a main-dex list. # methods: 72477 > 65536 multiDexEnabled true By checking the Enable multiDex checkbox in the option page of the ***.Droid project solves the problem. A: Before you take any decision, as said in Google documentation : Before configuring your app to enable use of 64K or more method references, you should take steps to reduce the total number of references called by your app code, including methods defined by your app code or included libraries. So try to remove useless importation in your app gradle and do a nice clean project or do multidex Source : https://developer.android.com/studio/build/multidex
{ "language": "en", "url": "https://stackoverflow.com/questions/52801386", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Choosing Windows Phone IsolatedStorage My web service returns some data. I want to cache it. Do I use this and serialize it to a file? IsolatedStorageFile.GetUserStoreForApplication() Or do I use this and stick it into the Dictionary? IsolatedStorageSettings.ApplicationSettings A: For caching data I would stick it in a file in IsolatedStorage. It is a little more work, but you can write a simple enough wrapper around it. It is conceivable that IsolatedStorageSettings.ApplicationSettings will one day be synced between devices using SkyDrive, this is the direction Microsoft are taking with Windows 8. So you should stick to using it for it's purpose which is application based settings.
{ "language": "en", "url": "https://stackoverflow.com/questions/7922820", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Plotting fixed plot area I have simple question, how can I plot fixed height barplots, i.e. stretching the plot area only change margins not the bararea, like the following: > A <- 4 > plot (A) > barplot(A, col = "green4") When I strech are, bar area also get increases. Edits: I want to keep the box size constant even the plot gets stretched. A: by splitting the screen into multiple parts, you can achieve that partially: split.screen(c(3,1)) A <- 4 barplot(A, col="green4") A: Are you looking to just expand the y axis. Look at ylim? A: What you might be looking for is to fix your aspect ratio. This can be achieved using asp: barplot(A, col = "green4", asp = 1) See also this post to R-help. On a more philosophical note, when the height of the bar changes, there is no change in surface area. barplot only draws a sequence of bars, where the x axis is an ordinal (ordered categorical) variable which makes it impossible to calculate a surface area. The height of the bar is the only changing variable. I would recommend drawing these kinds of timeseries using a simple line plot. So instead of: a = runif(100) b = 1:100 barplot(a) use: plot(b, a, type = "l") or switch to my favorite plotting package, ggplot2: require(ggplot2) theme_set(theme_bw()) qplot(b, a, geom = "line")
{ "language": "en", "url": "https://stackoverflow.com/questions/10406848", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: the if statement syntax in the jsp mvc, jsp and bootstrap in which i am passing 2 model attributes * *model.addAttribute("map",map) *model.addAttribute("size",SIZE) now on the jsp i want to iterate over this map and want to check if map value matches the SIZE varibale value for which i tried below syntax <div id="selector" class="btn-group"> < c:forEach items="${maps}" var="buttonName" varStatus="counter"> <div class="row"> <div class="col-sm-8"> <c:if test="${buttonName.key} == ${SIZE}"> <button type="button" id="a" >cat</button> </c:if> < /div> < /div> < br/> < /c:forEach> < /div> but this is not working , please let me know if the if syntax is correct ? A: ${} is not used to enclose a single variable but the whole statement. And you should use eq instead of ==. So the correct syntax is: ${buttonName.key eq SIZE}
{ "language": "en", "url": "https://stackoverflow.com/questions/25379444", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Element vs. Generic Type I wonder why Swift uses Element rather than Generic <T> in the following example. What is the difference between Element vs T A: From Generics: Type Parameters Type parameters specify and name a placeholder type, and are written immediately after the function’s name, between a pair of matching angle brackets (such as <T>). Naming Type Parameters In most cases, type parameters have descriptive names, such as Key and Value in Dictionary<Key, Value> and Element in Array<Element>, which tells the reader about the relationship between the type parameter and the generic type or function it’s used in. However, when there isn’t a meaningful relationship between them, it’s traditional to name them using single letters such as T, U, and V, such as T in the swapTwoValues(_:_:) function above. So func createArray<Element>(element: Element) -> [Element] { ... } func createArray<T>(element: T) -> [T] { ... } func createArray<Rumpelstilzchen>(element: Rumpelstilzchen) -> [Rumpelstilzchen] { ... } are identical functions. Here the placeholder type is the element type of the returned array, therefore Element is a suitable “descriptive name.” But it makes no difference otherwise, is it up to you to choose a name for the placeholder, balancing between readability and conciseness. A: T is not particularly traditional. In FP, Backus uses T, but ML, from around the same time, uses a. Haskell uses a, Scala uses A. There's a mix of choices. Swift, however, has strong reasons to use descriptive names. First, it's a quite descriptive language. Types are named with fully spelled-out words. Methods typically are literate in construction. Variables and properties are rarely abbreviated. There's no reason that type parameters should be uniquely obscure. It also matches well with associated types which are quite naturally verbose. What would you call Collection's index type besides Index? Why should its "element" type be specially abbreviated? And if Array implements Collection, why should it create a distinct name (T) that it would then have to associate with Collection's Element? Why would you special-case all this just to make the type name unintuitive? The deeper question would be, why wouldn't Array's element be called Element?
{ "language": "en", "url": "https://stackoverflow.com/questions/55542757", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to use TestScheduler in RxJava How should I use RxJava's TestScheduler? I come from a .NET background but the TestScheduler in RxJava does not seem to work the same way as the test scheduler in .NET rx. Here is sample code that I want to test Observable<Long> tick = Observable.interval(1, TimeUnit.SECONDS); contactsRepository.find(index) .buffer(MAX_CONTACTS_FETCH) .zipWith(tick, new Func2<List<ContactDto>, Long, List<ContactDto>>() { @Override public List<ContactDto> call(List<ContactDto> contactList, Long aLong) { return contactList; } }).subscribe() I've tried: subscribeOn(testScheduler) testScheduler.advanceTimeBy(2, TimeUnit.SECONDS); testScheduler.triggerActions(); with no luck. A: I made a little example of how to use a TestScheduler. I think it's very similar to the .NET implementation @Test public void should_test_the_test_schedulers() { TestScheduler scheduler = new TestScheduler(); final List<Long> result = new ArrayList<>(); Observable.interval(1, TimeUnit.SECONDS, scheduler) .take(5) .subscribe(result::add); assertTrue(result.isEmpty()); scheduler.advanceTimeBy(2, TimeUnit.SECONDS); assertEquals(2, result.size()); scheduler.advanceTimeBy(10, TimeUnit.SECONDS); assertEquals(5, result.size()); } https://github.com/bric3/demo-rxjava-humantalk/blob/master/src/test/java/demo/humantalk/rxjava/SchedulersTest.java EDIT According to your code : you should pass the scheduler to the Observable.interval operation, as this is what you want to control : TestScheduler scheduler = new TestScheduler(); Observable<Long> tick = Observable.interval(1, TimeUnit.SECONDS, scheduler); Subscription toBeTested = Observable.from(Arrays.asList(1, 2, 3, 4, 5)) .buffer(3) .zipWith(tick, (i, t) -> i) .subscribe(System.out::println); scheduler.advanceTimeBy(2, TimeUnit.SECONDS); A: you have some class: public class SomeClass { public void someMethod() { Observable<Long> tick = Observable.interval(1, TimeUnit.SECONDS); contactsRepository.find(index) .buffer(MAX_CONTACTS_FETCH) .zipWith(tick, new Func2<List<ContactDto>, Long, List<ContactDto>>() { @Override public List<ContactDto> call(List<ContactDto> contactList, Long aLong) { return contactList; } }).subscribe() } } Look up [Observable.interval][1] in the docs and you will see it operates on the computation scheduler, so lets override that in our test. public class SomeClassTest { private TestScheduler testScheduler; @Before public void before() { testScheduler = new TestScheduler(); // set calls to Schedulers.computation() to use our test scheduler RxJavaPlugins.setComputationSchedulerHandler(ignore -> testScheduler); } @After public void after() { // reset it RxJavaPlugins.setComputationSchedulerHandler(null); } @Test public void test() { SomeClass someInstance = new SomeClass(); someInstance.someMethod(); // advance time manually testScheduler.advanceBy(1, TimeUnit.SECONDS); } This solution is an improvement to the accepted answer as the quality, integrity and simplicity of the production code is maintained.
{ "language": "en", "url": "https://stackoverflow.com/questions/26699147", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "20" }
Q: Project with Match in aggregate not working in mongodb I am trying to fetch data based on some match condition. First I've tried this: Here ending_date is full date format Offer.aggregate([ { $match: { carer_id : req.params.carer_id, status : 3 } }, { $group : { _id : { year: { $year : "$ending_date" }, month: { $month : "$ending_date" }}, count : { $sum : 1 } } }], function (err, res) { if (err) ; // TODO handle error console.log(res); }); which gives me following output: [ { _id: { year: 2015, month: 11 }, count: 2 } ] Now I want to check year also, so I am trying this: Offer.aggregate([ { $project: { myyear: {$year: "$ending_date"} } }, { $match: { carer_id : req.params.carer_id, status : 3, $myyear : "2015" } }, { $group : { _id : { year: { $year : "$ending_date" }, month: { $month : "$ending_date" }}, count : { $sum : 1 } } }], function (err, res) { if (err) ; // TODO handle error console.log(res); }); which gives me following output: [] as you can see, _id has 2015 as a year, so when I match year it should be come in array. But I am getting null array. Why this? Is there any other way to match only year form whole datetime? Here is the sample data { "_id": { "$oid": "56348e7938b1ab3c382d3363" }, "carer_id": "55e6f647f081105c299bb45d", "user_id": "55f000a2878075c416ff9879", "starting_date": { "$date": "2015-10-15T05:41:00.000Z" }, "ending_date": { "$date": "2015-11-19T10:03:00.000Z" }, "amount": "850", "total_days": "25", "status": 3, "is_confirm": false, "__v": 0 } { "_id": { "$oid": "563b5747d6e0a50300a1059a" }, "carer_id": "55e6f647f081105c299bb45d", "user_id": "55f000a2878075c416ff9879", "starting_date": { "$date": "2015-11-06T04:40:00.000Z" }, "ending_date": { "$date": "2015-11-16T04:40:00.000Z" }, "amount": "25", "total_days": "10", "status": 3, "is_confirm": false, "__v": 0 } A: You forgot to project the fields that you're using in $match and $group later on. For a quick fix, use this query instead: Offer.aggregate([ { $project: { myyear: { $year: "$ending_date" }, carer_id: 1, status: 1, ending_date: 1 } }, { $match: { carer_id: req.params.carer_id, myyear: 2015, status: 3 } }, { $group: { _id: { year: { $year: "$ending_date" }, month: { $month: "$ending_date" } }, count: { $sum: 1 } } }], function (err, res) { if (err) {} // TODO handle error console.log(res); }); That said, Blakes Seven explained how to make a better query in her answer. I think you should try and use her approach instead. A: You are doing so many things wrong here, that it really warrants an explanation so hopefully you learn something. Its a Pipeline It's the most basic concept but the one people do not pick up on the most often ( and even after continued use ) that the aggregation "pipeline" is just exactly that, being "piped" processes that feed input into the each stage as it goes along. Think "unix pipe" |: ps -ef | grep mongo | tee out.txt You've seen something similar before no doubt, and it's the basic concept that output from the first thing goes to the next thing and then that manipulates to give input to the next thing and so on. So heres the basic problem with what you are asking: { $project: { myyear: {$year: "$ending_date"} } }, { $match: { carer_id : req.params.carer_id, status : 3, $myyear : "2015" } }, Consider what $project does here. You specify fields you want in the output and it "spits them out", and possibly with manipulation. Does it output these fields in "addition" the the fields in the document? No It does not. Only what you ask to come out actually comes out and can be used in the following pipeline stage(s). The $match here essentially asks for fields that are no longer present, because you only asked for one thing in the output. The same problem occurs further down as again you ask for fields you removed earlier and there simply is nothing to reference, but also everything was already removed by a $match that could not match anything. Also, that is not how field projections work as you have entered So just use a range for the date { "$match": { "carer_id" : req.params.carer_id, "status" : 3, "ending_date": { "$gte": new Date("2015-01-01"), "$lt": new Date("2016-01-01") } }}, { "$group": { "_id": { "year": { "$year": "$ending_date" }, "month": { "$month": "$ending_date" } }, "count": { "$sum": 1 } }} Why? Because it just makes sense. If you want to match the "year" then supply the date range for the whole year. We could play silliness with $redact to match on the extracted year value, but that is just wasted processing time. Doing this way is the fastest to process and can actually use an index to process faster. So don't otherthink the problem and just ask for the date range you want. A: If you want your aggregation to work you have to use $addFields instead of $project in order to keep status and carer_id in the object you pass to the $match { $addFields: { myyear: {$year: "$ending_date"} } }, { $match: { carer_id : req.params.carer_id, status : 3, $myyear : "2015" } },
{ "language": "en", "url": "https://stackoverflow.com/questions/33752817", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: which select sql is faster? which sql is faster ? What I am trying to do is find out all fund which have not been snapshoted today. I take snapshot daily and save it in this snapshot table. explain SELECT id from fund where id NOT IN (select id from fund_daily_snap where date_trunc('day',day) = CURRENT_DATE-1); QUERY PLAN ------------------------------------------------------------------------------------------ Seq Scan on fund (cost=76961.83..97431.81 rows=11999 width=4) Filter: (NOT (hashed SubPlan 1)) SubPlan 1 -> Seq Scan on fund_daily_snap (cost=0.00..76932.96 rows=11550 width=4) Filter: (date_trunc('day'::text, day) = (current_date - 1)) OR explain SELECT count(id) from fund where id NOT IN (select id from fund_daily_snap where day >= CURRENT_DATE-1); QUERY PLAN ------------------------------------------------------------------------------------------------------- Aggregate (cost=959232109.01..959232109.02 rows=1 width=4) -> Seq Scan on fund (cost=0.00..959232079.01 rows=11999 width=4) Filter: (NOT (SubPlan 1)) SubPlan 1 -> Materialize (cost=0.00..78015.88 rows=770033 width=4) -> Seq Scan on fund_daily_snap (cost=0.00..71157.71 rows=770033 width=4) Filter: (day >= (current_date - 1)) A: If you have indeks on "day" column, second solution will become faster by the data increase. Because built-in functions are always have more cost to evaluate.
{ "language": "en", "url": "https://stackoverflow.com/questions/32536539", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Create MultiPolygon SqlGeography from Polygon SqlGeographys I have a list of SqlGeographys that are Polygons. I want to combine them into one SqlGeography of type multipolygon. List<SqlGeography> areaPolygons = GetAreaPolygons() SqlGeography multiPoly = null; foreach (SqlGeography geog in areaPolygons) { /// Combine them somehow? } A: I found a way using SqlGeographyBuilder, there may be a more efficient way but this works: List<SqlGeography> areaPolygons = GetAreaPolygons() SqlGeography multiPoly = null; SqlGeographyBuilder sqlbuilder = new SqlGeographyBuilder(); sqlbuilder.SetSrid(4326); sqlbuilder.BeginGeography(OpenGisGeographyType.MultiPolygon); foreach (SqlGeography geog in areaPolygons) { sqlbuilder.BeginGeography(OpenGisGeographyType.Polygon); for (int i = 1; i <= geog.STNumPoints(); i++) { if (i == 1) sqlbuilder.BeginFigure((double)geog.STPointN(i).Lat, (double)geog.STPointN(i).Long); else sqlbuilder.AddLine((double)geog.STPointN(i).Lat, (double)geog.STPointN(i).Long); } sqlbuilder.EndFigure(); sqlbuilder.EndGeography(); } sqlbuilder.EndGeography(); multiPoly = sqlbuilder.ConstructedGeography;
{ "language": "en", "url": "https://stackoverflow.com/questions/24605196", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Wildfly 10 JAX-WS attachements : MTOM threshold not working as expected (?) I have JAX-WS endpoint defined with @MTOM annotation and set threshold as below. So I expect any attachments less 5MB shall be sent inline as base64binary. But the soap response is always returned as MTOM for even small files. Is this expected behavior? How can I enforce this flexibility otherwise ? @HandlerChain(file="/handler-chain.xml") @MTOM(threshold=5242880) // 5MB limit for inline soap attachements else MTOM public class WSImpl { I'm interested in this behavior. This is not the spec, but at least Metro implementation behaves like that (at least old version) in jboss 5. The Apache CXF does always sends as MTOM if enabled and does not care about threshold.
{ "language": "en", "url": "https://stackoverflow.com/questions/45105758", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: aes_ctr_128_encrypt in Android using boringSSL I am trying to implement aes_ctr128_encrypt in android using BoringSSL as defined by google. I built the application with CMAKE and Gninja by following the link https://boringssl.googlesource.com/boringssl/+/master/BUILDING.md Now I have crypto and ssl folders in the build folder but there is no AES definition in any of the files as AES.h was in the include folder in root directory. Anyhow, The binaries thus generated with CMAKE are also giving .a files and not .so files. How can I use those .a files in my project to access the aes_ctr_128_encrypt?
{ "language": "en", "url": "https://stackoverflow.com/questions/44176769", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to monitor the complete network through Python? I want to use Python to monitor the complete network, if the route or link goes up/down will get the notification. I found a few packages like lanscan, but I’m not sure that will work fine or not. Basically, I want to use python same as NMS (Network management system). Please suggest to me some good frameworks or packages. A: Pure python-based monitoring solutions are not really scalable as python at the core is pretty slow compared to something like c and multiprocessing is not native. Your best bet would be to use an opensource solution like Zabbix or cacti and use python API to interact with the data
{ "language": "en", "url": "https://stackoverflow.com/questions/66022670", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Firefox bug with position absolute inside table-cell It looks like Firefox has a bug with positon: absolute inside of a table-cell displayed parent. Is there any way to fix this? Show case It works well in Safari / Chrome but doesnt NOT work properly in Firefox (the browser treats #css-table as the parent instead of the #css-table col). I wonder if there's a method to fix this without using JS. A: Looks like: https://bugzilla.mozilla.org/show_bug.cgi?id=203225 It was logged over 10 years ago. As a workaround you could use a div within the TD and set that to position:relative instead of setting it on the TD directly.
{ "language": "en", "url": "https://stackoverflow.com/questions/19447796", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to save files to a specific folder using Plupload plugin? I'm using plupload jquery plugin to upload files to my server, how can I change the path where to save the file based on the user's input? (I also included a select dropdown input at the ui page, I need to change the path of file getting saved based on that POST result).
{ "language": "en", "url": "https://stackoverflow.com/questions/29104496", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Adding today's date to Oracle query results when using wildcard * this might be a lack of very basic knowledge, but I just can't figure it out. Searching for the answer and trial and error haven't helped much. Returning all recordsets from a table (SELECT * FROM X) --> no problem. Returning today's date (SELECT TO_CHAR(SYSDATE, 'DD-MM-YYYY') FROM DUAL) --> no problem. Returning all recordsets from the same table as well as today's date --> no luck. I have tried subselects, union, joins, with-statements, ... it's driving me nuts. When I name the columns I want returned (SELECT Columname1, Columnname2, to_char(sysdate....)) it works. This problems seems to only occur when using wildcards. How do I get Oracle to return "all columns", today's date"? Thanks! A: You have to prefix the wildcard with the table name (or alias, if you've used one): SELECT X.*, TO_CHAR(SYSDATE, 'DD-MM-YYYY') AS TODAYS_DATE FROM X Using the wildcard is generally not considered a good idea, as you have no control over the order the columns are listed (if the table was built differently in different environments) and anyone consuming this output may be thrown if the table definition changes in the future, e.g. by adding another column. It's better to list all the columns individually.
{ "language": "en", "url": "https://stackoverflow.com/questions/29075753", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Highlight cells according to mysql value I have fetched mysql results as below..I need to do is, check each $row["$date07"] value with a threshold and highlight the cell. while ($row = $result -> fetch_assoc()) { $table_rows[$rowId] .= '<tr> <td style="text-align:center"><b>'.$row['table_name'].'</td> <td style="text-align:center;">'.$row["$date07"].'</td> <td style="text-align:center;">'.$row["$date06"].'</td> <td style="text-align:center;">'.$row["$date05"].'</td> <td style="text-align:center;">'.$row["$date04"].'</td> <td style="text-align:center;">'.$row["$date03"].'</td> <td style="text-align:center;">'.$row["$date02"].'</td> <td style="text-align:center;">'.$row["$date01"].'</td> </tr>'; $table_rows[$rowId]++; } Here is my try... if($row["$date07"]<$row["threshold"]){ $table_rows[$rowId] .= '<tr> <td style="text-align:center"><b>'.$row['table_name'].'</td> <td style="text-align:center;background-color: red;">'.$row["$date07"].'</td> <td style="text-align:center;">'.$row["$date06"].'</td> <td style="text-align:center;">'.$row["$date05"].'</td> <td style="text-align:center;">'.$row["$date04"].'</td> <td style="text-align:center;">'.$row["$date03"].'</td> <td style="text-align:center;">'.$row["$date02"].'</td> <td style="text-align:center">'.$row["$date01"].'</td> </tr>'; $table_rows[$rowId]++; } As you can see I need thousands of if statements if I follow this way to achieve what I need(I need to check all 7 days and need to consider more than one day as well). So I need to find a better way to achieve what I need.. Is this possible to do? I have found some usefull threads if else statement inside echoed TD but need to use echo for that. Is there anyway to achieve what I need in some optimized method? Update: I need to consider all below cases as well when highlighting the cell. 1)Threshold breached for one day.(Ex: 2022-08-25 has breached need to highlight it) 2)Threshold breached for more than one day(Ex: 2022-08-25 and 2022-08-24 has breached. need to highlight both) 3)Threshold breached for two days but not adjacent(Ex: 2022-08-25 and 2022-08-21 breched. Still need to highlight them) 4)More than two days can be breached.. Need to highlight them all. A: You can use ternary operators within the string to check each day against the threshold, and output the extra style instructions where needed, something like this: $table_rows[$rowId] .= '<tr> <td style="text-align:center"><b>'.$row['table_name'].'</td> <td style="text-align:center;'.($row["$date07"] < $row["threshold"] ? "background-color:red;" : "").'">'.$row["$date07"].'</td> <td style="text-align:center;'.($row["$date06"] < $row["threshold"] ? "background-color:red;" : "").'">'.$row["$date06"].'</td> <td style="text-align:center;'.($row["$date05"] < $row["threshold"] ? "background-color:red;" : "").'">'.$row["$date05"].'</td> <td style="text-align:center;'.($row["$date04"] < $row["threshold"] ? "background-color:red;" : "").'">'.$row["$date04"].'</td> <td style="text-align:center;'.($row["$date03"] < $row["threshold"] ? "background-color:red;" : "").'">'.$row["$date03"].'</td> <td style="text-align:center;'.($row["$date02"] < $row["threshold"] ? "background-color:red;" : "").'">'.$row["$date02"].'</td> <td style="text-align:center;'.($row["$date01"] < $row["threshold"] ? "background-color:red;" : "").'">'.$row["$date01"].'</td> </tr>'; Demo: https://3v4l.org/NV8vF
{ "language": "en", "url": "https://stackoverflow.com/questions/73497795", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How can I effectively find a Graphics2D rendering error? Can you suggest a method of identifying the source of a rendering error from a debugger? Misko Hevery classifies bugs into three categories: * *Logical *Wiring *Rendering Its clear to me that my problem is a rendering bug. I have a Swing application with a Panel that contains multiple layers. Rendering all the layers can take a significant amount of time so the application uses a thread pool to render layers and tiles from layers into BufferedImages. When it comes time for the Event Dispatch Thread to render the panel the most-recently rendered BufferedImages are drawn to the screen. This setup has performed adequately. A new feature requires that a certain layer type support transparency. Something, somewhere isn't preserving the transparency. The error could be in a number of places, possibly in the implementation of the objects to be rendered, the error could possibly be in the offline rendering thread implementation. Its possible that the many BufferedImages aren't combined together correctly in the EDT rendering code. I'm not asking anyone to look at the code and tell me where the error is. What I want to know is what techniques people have found particularly effective in troubleshooting a Graphics2D rendering issue. I'm a big supporter of unit tests but I'd prefer to start with another technique. Is there a method or trick to visually inspect a BufferedImage or Graphics2D object from the debugger? In the Netbeans Variables and Watches windows Netbeans sometimes uses PropertyEditors to display variable values. In this example image the value of foregroundColor and backgroundColor are shown as small swatches of the Color's value. Is there an easy way to add/enable a Netbeans PropertyEditor which would display the contents of a BufferedImage? I could temporarily sprinkle the code with method calls to write the various BufferedImages encountered to the disk such that they could then be inspected offline. It might work but it would be tediious to match the file on disk to the source code. What would you do? A: You might compare your approach to the one shown here with regard to clearing the buffer: g2d.setComposite(AlphaComposite.Clear); g2d.fillRect(0, 0, w, h); In the worst case, you can break at a point in which your image is accessible and set a watch on the expression image.getRGB(0,0) with the display set to hexadecimal. The high order byte is the alpha value: FF is opaque, and 00..FE represents varying transparency.
{ "language": "en", "url": "https://stackoverflow.com/questions/25372649", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Python in Windows Store apps The Windows Store app Python 3 For Metro claims that it allows users to edit and run Python files (I can't get it to work). How is this possible from within the sandbox? Can I run a file (say test.py on the desktop) from my JavaScript app? A: How is this possible from within the sandbox? I have ported the Python interpreter to WinRT to achieve that. Instead of using Win32 API, it now uses WinRT API (in particular for reading files from the user's Documents folder). Can I run a file (say test.py on the desktop) from my JavaScript app? In principle, yes. You need to take the python33.dll from my app, wrap it as a WinRT component, and then call it. It actually is a WinRT component already, but doesn't expose any of the Python API. See http://hg.python.org/sandbox/loewis/file/ee9f8c546ddd/win8app/python33 A: Basically, what you need to do is write a C++ "shell" app according to the Metro rules, then host the Python interpreter inside that C++ app. And again, scrub the Python codebase so that it runs within the Metro sandbox. You can then go a step further, and have the C++ shell expose WinRT libraries to the Python environment. There's probably a way to get Python to expose WinRT objects, but that would be a LOT of work. You won't be able to call directly from JavaScript into Python - you'll need a WinRT component in the middle. This is a lot of work, and requires some fairly low level work in C. A: You have two options: * *add python.exe to your PATH and, from within a terminal, enter the folder that contains your test.py and run python.exe test.py, using your current installation *you can follow step1 and step2 of this post and install a brand new python from scratch If you can provide some more informations, we can help you better. Can I run a file (say test.py on the desktop) from my JavaScript app? This can be your real problem, what do you mean with this statement? generally the answer would be "no, you can't"
{ "language": "en", "url": "https://stackoverflow.com/questions/14211949", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: Is it possible to intercept all DataNucleus' JDO SQL queries? Assuming one has an operational Java application using DataNucleus's implementation of JDO to access a database, is it possible to intercept all SQL queries made to the database? The intention is to run statistics on them and keep a log/trace. A: You may easily get logs of all SQL statements from DataNucleus by turning on the category DataNucleus.Datastore.Native (see http://www.datanucleus.org/products/datanucleus/logging.html) JDO2 InstanceLifecycleListeners would allow you to intercept events, but I don't think the SQL statements would be available there... You can also look to your app server for SQL profiling tools. For example GlassFish allows you to attach SQLTraceListener implementations to your connection pools. See http://docs.oracle.com/cd/E18930_01/html/821-2418/giyck.html#giygg A: Log4j You can use java.util.logging or Log4j with DataNucleus. I'm going to tell about Log4j configuration. log4j.properties # Define the destination and format of our logging log4j.rootCategory=DEBUG, stdout log4j.appender.stdout=org.apache.log4j.ConsoleAppender log4j.appender.stdout.Target=System.out log4j.appender.stdout.layout=org.apache.log4j.PatternLayout log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %t %c{1}:%M:%L - %m%n # DataNucleus Categories log4j.category.DataNucleus=ALL The last line assigns a level threshold to INFO or ALL in order to see all DataNucleus logs. DataNucleus uses a series of categories, and logs all messages to these categories. See here for more details. You probably need * *log4j.category.DataNucleus.Query - All messages relating to queries *log4j.category.DataNucleus.Datastore - All general datastore messages or *log4j.category.DataNucleus.JDO - All messages general to JDO log4j.category.DataNucleus is a root of all DataNucleus log categories. Add log4j to your CLASSPATH. I use Gradle for dependency management, so here is my build script: build.gradle configurations { all*.exclude group: "commons-logging", module: "commons-logging" } dependencies { // Logging compile 'org.slf4j:slf4j-api:1.7.+' runtime 'org.slf4j:slf4j-jdk14:1.7.+' runtime ('log4j:log4j:1.2.17') { exclude group: "com.sun.jdmk", module: "jmxtools" exclude group: "com.sun.jmx", module: "jmxri" exclude group: "javax.mail", module: "mail" exclude group: "javax.jms", module: "jms" } } To provide a Log4J configuration file when starting up your application set a JVM parameter as -Dlog4j.configuration=file:log4j.properties This may be done for you if you are running within a JavaEE application server. Or if you are using Spring WebMVC, place log4j.properties inside WEB-INF, and add the following listener to your Deployment descriptor. web.xml <!-- The definition of the Log4j Configuration --> <listener> <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class> </listener> <context-param> <param-name>log4jConfigLocation</param-name> <param-value>/WEB-INF/log4j.properties</param-value> </context-param>
{ "language": "en", "url": "https://stackoverflow.com/questions/9635216", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: how to hover on multiple charts with the same x axis with plotly (Python)? I have figure with 2 subplots: a candlestick stock chart and the volume bar chart associated below. I would like to hover on both charts when I move my cursor on one of them. At the moment, the hover is only active on the subplot where the cursor is like in the screenshot I would like to activate the hover on volumes at the same time I think it's possible to do it with Java, but I am not sure Python
{ "language": "en", "url": "https://stackoverflow.com/questions/65007954", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Should the update for my app be compatible with iPhone 5 screen? I had some minor changes to an older app of mine. Now, I am going to update a newer version on the App Store. But it doesn't have support for iOS 6 or iPhone 5 screen. I understand, I will have to give support for iOS 6. But should I update the App for iPhone 5 screen too? I don't consider supporting iPhone 5 screen right now. A: It isn't obligatory for app to support new futures of iOS6 like so-called 'GiraffeMode' of iPhone5.
{ "language": "en", "url": "https://stackoverflow.com/questions/12596476", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Zk jmeter plugin I want to perform load tests on Zkoss with jmeter. I have installed jmeter and the zk jmeter plugin. then i placed the jar file in jmeter/lib/ext folder as specified in the Zk site http://blog.zkoss.org/2013/08/06/zk-jmeter-plugin/. Now i am facing a problem. when I place this jar in the respective folder. My jmeter application is getting crashed and showing me an error : Uncaught Exception java.lang.NoClassDefFoundError: Could not initialize class or g.apache.jmeter.gui.util.MenuFactory. See log file for details. So please help me out with this. Thanks and Regards A: If you use Jmeter 3.2, then probably it is your case: http://forum.zkoss.org/question/105222/zk-jmeter-plugin-080jar-not-working-with-jmeter-32/ (use 3.1)
{ "language": "en", "url": "https://stackoverflow.com/questions/44543265", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: OpenPyXL - find last row in existing excel file New to this and having problems findings the last row in an existing excel file with openpyxl. I tried using max_row and len(ws["A"]) but no luck. I keep getting numbers way larger than expected. It appears this is a common issue but could not find a workaround my problem. Objective is to copy data from one excel file (wb_source) and paste add it to an existing excel file (wb_target). Could you please suggest another way to find the fist available row in column A (target file) ? import openpyxl as xl #opening the source file source_file = path wb_source = xl.load_workbook(source_file) ws_source = wb_source.worksheets[0] #opening the target file target_file = path wb_target = xl.load_workbook(target_file) ws_target = wb_target.worksheets[0] #in source file max_row_source = ws_source.max_row max_column = ws_source.max_column for i in range(1, max_row_source + 1): for j in range(1, max_column + 1): c = ws_source.cell(row = i, column = j) ws_target.cell(row = (ws_target.max_row + 1), column = j).value = c.value wb_target.save(str(target_file))
{ "language": "en", "url": "https://stackoverflow.com/questions/69740763", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: expected expression before 'struct' on c I tried to make a userdata where it's declared as a struct. I tried to use scanf, but everytime i tried to compile it always says "expected expression before 'userdata'. Anyone know how to fix this? Thank you Here's my code: #include <stdio.h> typedef struct { char name[30]; char age[2]; char country[10]; char date[40]; } userdata; int main() { printf("Please input your name: \n"); scanf("%c", &userdata.name); printf("Please input your age: \n"); scanf("%c", &userdata.age); printf("Which country are you from: \n"); scanf("%c", &userdata.country); printf("Please tell me the date of your birth in number format (00 - 00 - 0000)\n"); scanf("%c", &userdata.date); printf("Here's your userdata: \n"); printf("Name : %c\n", userdata.name); printf("Age : %c\n", userdata.age); printf("Country : %c\n", userdata.country); printf("Date of birth : %c\n", userdata.date); return 0; } A: You created a type called userdata so now you need to declare an instance of the type to use it: userdata u; then you pass the address of the instance: scanf("%c", &u.name); A: By using the typedef keyword, you've declared userdata as a type alias for a struct. It's not a variable name. If you remove the typedef keyword, you'll declare a variable with that name. Also, you need to use the %s format specifier to read and write strings. The %c format specifier is used for single characters. Also, since strings are terminated by a null byte, the age member of your struct should be longer. A: You are trying to assign a value to a TYPE, not a variable. When you define typedef, you do not create a variable, you create an alias for the type. Let's say you have the int type, but you don't like it being called int. Then you can do typedef and name the type int as you want: typedef int MyType; // Create an alias for an int type You do NOT create a variable of this type. Your solution is to create a variable of userdata and set it to: userdata data; scanf("%s", &data.name); In addition, as @dbush rightly noted, you need to use the %s specifier to read strings: the %c specifier is used only for single characters.
{ "language": "en", "url": "https://stackoverflow.com/questions/71727537", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: css sprite images showing but a:link urls not showing when I hover over the images My CSS sprite images show just fine on website and sprite image changes with hover, but link URLs are not working when I hover over the images. Not sure what I am doing wrong but I'm sure it is probably something simple. The URL of the website is the following: www.roadworksmfg.com The icons in question are on the left hand side in the sidebar directly under the red catalog search button. Here is my CSS block for these sprite buttons: li.facebook-icon, li.twitter-icon{ float: left; display: block; margin: 0px 21px; width: 48px; height: 48px; background: url(/images/sprites/facebook_twiter_sprite_sheet.png) no-repeat; } li.facebook-icon{ background-position: 0 0; } li.facebook-icon:hover{ background-position: 0 -48px ; } li.twitter-icon{ background-position: 0 -96px ; } li.twitter-icon:hover{ background-position: 0 -144px ; } Here is my HTML block: <ul class="social-icons mobile-social-set"> <li class="facebook-icon"><a href="http://www.facebook.com/roadworks.manufacturing?ref=tn_tnmn"></a></li> <li class="twitter-icon"><a href="http://www.twitter.com/RoadWorksmfg"></a></li> </ul> By the way, please forgive me if I have formatted any of this question incorrectly. This is my first post and question on Stackoverflow. A: Your a element is empty. Add this to your css .social-icons a { display: block; height: 100%; }
{ "language": "en", "url": "https://stackoverflow.com/questions/27019423", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Is std::cout in a header file bad practice? This might be a duplicate question but all of my search results talk about not putting using into a header file, which is not my question. I have read up on this and understand why you should not place using inside of a header file. I am new to C++ and am trying to make sure I am learning/using best practices. I know header files are meant for defining classes, structs and the like and should never "do" anything. Does this include std::cout? Is that considered doing something? What I mean is, is it okay to print output from a header file, or should i return data to my *.cpp file and do the output from there? Or does this not really matter? A: There is nothing wrong in principle with doing things in header file. Indeed, header only libraries are quite popular in C++ nowadays. In some cases (such as templates) doing things in header file is the only way to go. The art of splitting definitions between header file and .cpp file is often a judgment call. Generally, when you define functions in header file, you might hope for better performance (since inlining would be more easily achieved), but you might end up with larger codebase (depending on linker behavior), and you are likely to increase your compilation time. Instead of asking for best practices, I wholeheartedly suggest you understand what are the mechanics at play there, and make a conscious choice yourself. A: IMHO ... Use of std::cout in any file in a library is a symptom of poor design. If you need to output something, provide the interface for the client code to pass a ostream or an ostream-like object that supports inserting data to it. Use of std::cout in an application-specific file, be it a header file or a .cpp file, is perfectly fine. A: Is std::cout in a header file bad practice? Not necessarily. For example, you might have a function which outputs character sequence into a stream. It would be useful to let the client of the function to choose which stream to use, so the function accepts the stream as an argument. It might make a lot of sense for the function to have the default behaviour of streaming to the standard output stream. Therefore you might have a function declaration in a header such as: void stream_fancy_stuffs(std::ostream& output_stream = std::cout);
{ "language": "en", "url": "https://stackoverflow.com/questions/54152460", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: How to fix my leaderboard for my Music Quiz I'm making a Music Quiz for a school project. I've made a working game however I cannot get the leaderboard (which should be text and is saved as leaderboard.txt) to show different names as it overwrites the previous name. For example, if "Sam" was to get a score of 9 and "Ben" was to get a score of 3, it would show up as "Ben-3-9" which is not what I'm after. I am trying to get my leaderboard to work like: Sam - 9 Ben - 3 ... My code looks like this right now: username = input("What is your username?") # this will ask for the persons name password = str(input("What is the password?")) # this will ask for a password which has been set already if password == "1234": print("User Authenticated") # if the password is incorrect, tell the user so and exit elif password != "1234": print("Password Denied") exit() # GAME # Creating a score variable score=0 x = 0 # Reading song names and artist from the file read = open("songnames.txt", "r") songs = read.readlines() songlist = [] # Removing the 'new line' code for i in range(len(songs)): songlist.append(songs[i].strip('\n')) while x == 0: # Randomly choosing a song and artist from the list import random choice = random.choice(songlist) artist, song = choice.split('-') # Splitting the song into the first letters of each word songs = song.split() letters = [word[0] for word in songs] # Loop for guessing the answer for x in range(0, 2): print(artist, "".join(letters)) guess = str(input("Guess the song!")) if guess == song: if x == 0: score = score + 3 break if x == 1: score = score + 1 break quit() # Printing score, Then waiting to start loop again. import time print("Your score is", score) print("Nice Work!") time.sleep(3) leaderboard = open("leaderboard.txt", "r+") leaderboard.write(username + '-' + '{}'.format(score)) leaderboard.close() leaderboard = open("leaderboard.txt", "r+") leaderboardlist = leaderboard.readlines() print(leaderboardlist) leaderboard.close() PS: this is not 100% my code I am trying to get help from different places as my school has not taught us how to code yet due to the pandemic closing down schools. A: When you do this: leaderboard = open("leaderboard.txt", "r+") leaderboard.write(username + '-' + '{}'.format(score)) you open the leaderboard in read-and-write mode, but it will start writing at the beginning of the file, overwriting whatever is there. If you just want to add new scores to the leaderboard, the simplest would be to open the file in "append" mode "a": with open("leaderboard.txt", "a") as leaderboard: leaderboard.write(username + '-' + '{}'.format(score)) Alternatively, you could open the file in "r" mode, then first read all the lines (scores) in a list or dictionary, merge / update them with the current player's new score (e.g. adding to the last score, replacing the last score, or getting the max of the new and last score of that player), and then open the file again in "w" mode and write the updated scores. (Left as an exercise to the reader.) A: The problem lies within the final few lines of code, where you are writing to the leaderboard.txt file. Using "r+" indicates that you are updating (reading and writing) the file. Opening a file this way, moves the cursor at the beginning of the file. Therefore any attempt to write to the file will override whatever is already there. The proper way to do it, is to open the file using "a" (or "a+" if you are planning to read as well). This is append mode and will move the cursor to the end of the file. Some other general notes: * *Use the with-as statement to handle closing the file automatically after you are done. *Use f-strings as opposed to string concatenation to increase readability With that in mind, here's the code: with open("leaderboards.txt", "a") as f: f.write(f"{username}-{score}") For more on files, check this question. For more on f-strings, check this quite extensive overview of them.
{ "language": "en", "url": "https://stackoverflow.com/questions/63647898", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How perform authorization with session Symfony2 in 3rd party application I have problem with following scenario: In my Symfony2 application, user which is logged in, open 3rd party application (filenamager for TinyMCE). How to authorize user with credentials from SF2 application? If user check remember_me on login page, this work: //Bootstrap of 3rd party app require_once('../../../app/bootstrap.php.cache'); require_once('../../../app/AppKernel.php'); $kernel = new AppKernel('prod', false); $request = \Symfony\Component\HttpFoundation\Request::createFromGlobals(); $container = $kernel->getContainer(); if(false == $container->get('security.context')->isGranted('ROLE_USER')) { $response = new \Symfony\Component\HttpFoundation\RedirectResponse('http://'.$request->getHost()); return $response->send(); } But if is not logged in with remember_me, this cause redirect to login page. A: On the security.yml you can set up that remember me is by default YES. Here is the reference, i don't want to copy on the whole config file. Symfony reference A: My suggestion is to place tinyMCE (any 3rd party app on your site) behind the firewall. #security.yml firewalls: tiny_mce: pattern: ^/path/to/your/tinymce/dir http_basic: # Any authentication provider here realm: "Secured Demo Area" When user will open tinymce, browser will request for http://example.com/path/to/your/tinymce/dir/tinymcefile.html. And symfony will require user for authentication, because you have mentioned this path in your security.yml Update Also this issue may appear when you was logged in on dev environment and then you try to access path from prod env or inverse! I see that for tiny mce you use dev env. Check on what env you was logged in previously.
{ "language": "en", "url": "https://stackoverflow.com/questions/19977642", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Get query url on PHP I have this url http://www.mywebsite.com/code.php?number=1234233566456766 or http://www.mywebsite.com/code.php?1234233566456766 if first example is not possible, and i try to get the code number on <input type="text" value="<?php get_textafternumber ?>"> it is possibile? A: //first, check number through GET if(isset($_GET['number'])){ $text = $_GET['number']; }else{ //second, check REQUEST_URI $urlparts = parse_url( $_SERVER['REQUEST_URI']); $text = $urlparts['query']; } echo $text; A: Take a look at the parse_url() function. It takes a URL as the input and returns an array containing all of the separate parts. A slightly altered example from the documentation: $url = 'http://username:password@example.com/path?arg=value#anchor'; print_r( parse_url( $url ) ); Outputs: Array ( [scheme] => http [host] => example.com [user] => username [pass] => password [path] => /path [query] => arg=value [fragment] => anchor ) I believe you are looking for the query part of the URL. From there you could possibly use the parse_str() function to split that string into variables.
{ "language": "en", "url": "https://stackoverflow.com/questions/17735251", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: How to split contents of column into different columns in csv files using python? I have a CSV file that has the output from my machine learning model. It should ideally have three columns ( Source, Relation type, Target). When extracting the output my outputs are being stored as a single content of the cell for n number of rows. I do not want the entities, I want the content of relations in separate columns. I have attached my output and also my expected output. Can anyone please guide me on extracting the contents of the cell into different columns using python. {'entities': [{'title': 'WarnerMedia', 'wikild': 'Q191715', 'label': 'Organization'}, {'title': 'Time (magazine)', 'wikild': 'Q43297', 'label': 'Organization'}, {'title': 'AOL', 'wikild': 'Q27585', 'label': 'Organization'}, {'title': 'Google', 'wikild': 'Q95', 'label': 'Organization'}, {'title': 'Warner Bros.', 'wikild': 'Q126399', 'label': 'Organization'}, {'title': 'U.S. Securities and Exchange Commission', 'wikild': 'Q953944', 'label': 'Organization'}], 'relations': [{'source': 'Time (magazine)', 'target': 'WarnerMedia', 'type': 'owned by'}, {'source': 'WarnerMedia', 'target': 'Time (magazine)', 'type': 'subsidiary'}, {'source': 'WarnerMedia', 'target': 'Time (magazine)', 'type': 'owned by'}, {'source': 'WarnerMedia', 'target': 'U.S. Securities and Exchange Commission', 'type': 'subsidiary'}, {'source': 'U.S. Securities and Exchange Commission', 'target': 'WarnerMedia', 'type': 'subsidiary'}, {'source': 'WarnerMedia', 'target': 'AOL', 'type': 'subsidiary'}, {'source': 'AOL', 'target': 'WarnerMedia', 'type': O 'subsidiary'}]} {'entities': [{'title': 'Europe', 'wikild': 'Q46', 'label': 'Location'}, {'title': 'London', 'wikild': 'Q84', 'label': 'Organization'}, {'title': 'Federal Reserve', 'wikild': 'Q53536', 'label': 'Organization'}, {'title': 'United States', 'wikild': 'Q30', 'label': 'Organization'}, {'title': 'Federal government of the United States', 'wikild': 'Q48525', 'label': 'Organization'}, {'title': 'Bank of America', 'wikild': 'Q487907', 'label': 'Organization'}, {'title': 'Group of Seven', 'wikild': 'Q1764511', 'label': 'Organization'}, {'title': 'United States dollar', 'wikild': 'Q4917', 'label': 'Organization'}, {'title': 'New York (state)', 'wikild': 'Q1384', 'label': 'Organization'}, {'title': 'Alan Greenspan', 'wikild': 'Q193635', 'label': 'Person'}, {'title': 'Euro', 'wikild': 'Q4916', 'label': 'Organization'}, {'title': 'Germany', 'wikild': 'Q183', 'label': 'Organization'}], 'relations': [{'source': 'Federal Reserve', 'target': 'London', 'type': 'headquarters location'}, {'source': 'Bank of America', 'target': 'New York (state)', 'type': 'headquarters location'}, {'source': 'London', 'target': 'Federal Reserve', 'type': 'headquarters location'}, {'source': 'New York (state)', 1 'target': 'Bank of America', 'type': 'headquarters location'}]} Expected Output should be like: A: Is this what you need? You have not mentioned what the second dictionary is for since the sample output only refers to the first dictionary. inp = {'entities': [{'title': 'WarnerMedia', 'wikild': 'Q191715', 'label': 'Organization'}, {'title': 'Time (magazine)', 'wikild': 'Q43297', 'label': 'Organization'}, {'title': 'AOL', 'wikild': 'Q27585', 'label': 'Organization'}, {'title': 'Google', 'wikild': 'Q95', 'label': 'Organization'}, {'title': 'Warner Bros.', 'wikild': 'Q126399', 'label': 'Organization'}, {'title': 'U.S. Securities and Exchange Commission', 'wikild': 'Q953944', 'label': 'Organization'} ], 'relations': [{'source': 'Time (magazine)', 'target': 'WarnerMedia', 'type': 'owned by'}, {'source': 'WarnerMedia', 'target': 'Time (magazine)', 'type': 'subsidiary'}, {'source': 'WarnerMedia', 'target': 'Time (magazine)', 'type': 'owned by'}, {'source': 'WarnerMedia', 'target': 'U.S. Securities and Exchange Commission', 'type': 'subsidiary'}, {'source': 'U.S. Securities and Exchange Commission', 'target': 'WarnerMedia', 'type': 'subsidiary'}, {'source': 'WarnerMedia', 'target': 'AOL', 'type': 'subsidiary'}, {'source': 'AOL', 'target': 'WarnerMedia', 'type': 'subsidiary'} ] } df = pd.DataFrame(inp['relations']) #Simply conversion to dataframe output = df[['source','type','target']] #Reordering columns output A: I suppose the data come as a string, but I'm not sure if they come as one object or as multiple objects. In my answer, I suppose each time there is only an object if not; then the only difference is having a for-loop appending the data. import json import pandas as pd JSON=""" { 'entities': [ {'title': 'WarnerMedia', 'wikild': 'Q191715', 'label': 'Organization'}, {'title': 'Time (magazine)', 'wikild': 'Q43297', 'label': 'Organization'}, {'title': 'AOL', 'wikild': 'Q27585', 'label': 'Organization'}, {'title': 'Google', 'wikild': 'Q95', 'label': 'Organization'}, {'title': 'Warner Bros.', 'wikild': 'Q126399', 'label': 'Organization'}, {'title': 'U.S. Securities and Exchange Commission', 'wikild': 'Q953944', 'label': 'Organization'} ], 'relations': [ {'source': 'Time (magazine)', 'target': 'WarnerMedia', 'type': 'owned by'}, {'source': 'WarnerMedia', 'target': 'Time (magazine)', 'type': 'subsidiary'}, {'source': 'WarnerMedia', 'target': 'Time (magazine)', 'type': 'owned by'}, {'source': 'WarnerMedia', 'target': 'U.S. Securities and Exchange Commission', 'type': 'subsidiary'}, {'source': 'U.S. Securities and Exchange Commission', 'target': 'WarnerMedia', 'type': 'subsidiary'}, {'source': 'WarnerMedia', 'target': 'AOL', 'type': 'subsidiary'}, {'source': 'AOL', 'target': 'WarnerMedia', 'type':'subsidiary'} ] } """.replace("'", '"') json_object = json.loads(JSON) df=pd.DataFrame(json_object["relations"]) df.head()
{ "language": "en", "url": "https://stackoverflow.com/questions/74298100", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Wait for Ajax to render (JSF) I have a PRIMEFACES dialog, in wich I use onCloseUpdate atribute to re-render all the content of the dialog when dialog is closed. The problem is that when I close the dialog, and (fast) click to open it again, I see that onCloseUpdate hasn't finished re-rendering the content of the dialog, and old content is displayed for a half second/second period. Here's the command link that make dialog visible: <h:commandLink id="area1" onclick="dlg.show()"> ... </h:commandLink> , and here's the dialog: <ppctu:dialog onCloseUpdate="... here is all the component ids from the dialog content ..." modal="true" widgetVar="dlg"> Is there some way to wait for onCloseUpdate rendering to complete? Thanks in advance A: Use synchronous ajax call.Synchronous AJAX (Really SJAX -- Synchronous Javascript and XML) is modal which means that javascript will stop processing your program until a result has been obtained from the server. While the request is processing, the browser is effectively frozen. function getFile(url) { if (window.XMLHttpRequest) { AJAX=new XMLHttpRequest(); } else { AJAX=new ActiveXObject("Microsoft.XMLHTTP"); } if (AJAX) { AJAX.open("GET", url, false); //notice the 'false' attribute AJAX.send(null); return AJAX.responseText; } else { return false; } } If you are using jQuery then put async:false in your ajax call var fileFromServer = getFile('http://somedomain.com/somefile.txt');
{ "language": "en", "url": "https://stackoverflow.com/questions/7119466", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Use Python logging to determine where a method was called from I'm trying to debug a Python Django app. I've got additional fields being added to a model. I've tracked this down to one method: django.db.models.options.add_field() The only place this method is called is: django.db.models.fields.init.contribute_to_class() def contribute_to_class(self, cls, name): self.set_attributes_from_name(name) cls._meta.add_field(self) if self.choices: setattr(cls, 'get_%s_display' % self.name, curry(cls._get_FIELD_display, field=self)) I'm trying to use Logging to determine where the additions to the User model are occurring. Is there anyway to that I can set a logging message that will record where this contribute_to_class() method was called from? A: Use traceback module.
{ "language": "en", "url": "https://stackoverflow.com/questions/2237355", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Flow Framework: How does @Signal behave and can be used to perform some dynamic tasks, which change the execution flow in SWF Some of my observations on researching about flow framework are: @Signal starts executing in the decider replay once the signal is received. @Signal method is executed in all the future replays of the same workflow. (Once signal is received, on each replay the decider executes @Signal). @Asynchronus methods should not be long running tasks, as decider will schedule Activity Tasks only after all @Asynch methods have completed execution. Are my observations correct ? If yes: then what if in the same workflow I want a signal, which performs some task and then stop executing for future replays. Such as a pause signal: user might pause and resume a workflow multiple times. Another problem is: How are the following types of cases handled by flow: A decider times out, and meanwhile two events come: Cancel workflow and Activity Completed. How does decider figure out that they are related and if cancellation is done, then do not responds to ActivityComplatedEvent. A: It helps to not think about workflow behavior in terms of replay. Replay is just a mechanism for recovering workflow state. But when workflow logic is written it is not really visible besides the requirement of determinism and that workflow code is asynchronous and non blocking. So never think about replay when designing your workflow logic. Write it as it is a locally executing asynchronous program. So when replay is not in a way the @Signal is just a callback method that executes once per received signal. So if you invoke some action from the @Signal method then it is going to execute once. As for second question it depends on the order in which cancellation and activity completion are received. If cancellation is first then cancellation is delivered to a workflow first which might cause the cancellation of the activity. Cancellation is actually blocking waiting for activity to cancel. Completion of activity (which is the next event) unblocks the cancellation for it. If completion is second then activity completes and whatever follows it is cancelled by the next event. In majority of cases the result is exactly the same that activity completion is received but all logic after that is cancelled.
{ "language": "en", "url": "https://stackoverflow.com/questions/43673610", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Which FK column is update by EF when there are multiple navigation properties to Users table Scenario I have tables like * *Users (ID, Email, Password) *User_Profile (ID, UserID_FK, First, Last, Created_On, Created_By_FK) This is how I create new user account Users us = new Users { Email = 'xyz@example.com', Password = 123 }; User_Profile up = new User_Profile { First = 'Kamalpreet', Last = 'Singh', Created_On = DateTime.Now }; us.User_Profile.Add(up); Context x = new Context(); x.Users.Add(us); db.Save(); Above code creates following records in database- Users Table- ID = 100 Email = xyz@example.com Password = 123 User_Profile Table- ID = 1 UserID_FK = 100 First = Kamalpreet Last = Singh Created_On = 2016-08-06 10:40:10.000 Created_By_FK = NULL Question In User_Profile table, why the Users(ID) gets copied to only User_Profile(UserID_FK) table and not get copied to User_Profile(Created_By_FK) Both UserID_FK and Created_By_FK columns are Foreign Key references to Users(ID) table. A: When you are generating a database first DbContext, you get two collections to add against (if you have two relationships setup - one for each key). For example, you should then see: * *us.User_Profile.Add() *us.User_Profile2.Add() You would then add the profile to both collections to have both foreign keys updated properly when persisting. Entity Framework keeps track of the fact you have added the same object reference to two collections, and will save it properly. Note: The other option is to save the user, and then put the ID you get back on both foreign key properties, but this may be less efficient.
{ "language": "en", "url": "https://stackoverflow.com/questions/38800784", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Json serdes override / customize base class construction I have a deep object hierarchy where the base class parameterless constructor looks like this: public class BaseClass { private Session session_; public BaseClass() { session_ = ...; } } Serialization is OK. Problem happens in deserialization when the object construction tries to establish a connection to a webservice to construct the session object which is not necessary at all as all the values obtained from the session have been serialized. So the question is how do I customize / override the constructor to skip the deserialization of session field?
{ "language": "en", "url": "https://stackoverflow.com/questions/36547727", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Python: find_all is only working for some tags the .findall function within bs4 is only working for some HTML tags. I am trying to scrape a website. from bs4 import BeautifulSoup import requests url = 'https://bitskins.com/' page_response = requests.get(url, timeout=5) page_content = BeautifulSoup(page_response.content, 'html.parser') # Gather the two lists skin_list = page_content.find_all('div', attrs={'class': 'panel-heading item-title'}) wear_box = page_content.find_all('div', attrs={'class': 'text-muted text-center'}) When I print skin_list, it works successfully, however when I try to print the wear list, it prints an empty list. I have tried one other thing: wear_box = page_content.html.search("Wear: {float}") This brought on an error stating that 'NoneType' object is not callable. I am using Sublime Text 3. A: from bs4 import BeautifulSoup import requests url = 'https://bitskins.com/' page_response = requests.get(url, timeout=5) page_content = BeautifulSoup(page_response.content, 'html.parser') skin_list = page_content.findAll('div', class_ = 'panel item-featured panel-default') for skin in skin_list: name = skin.find("div", class_ = "panel-heading item-title") price = skin.find("span", class_ = "item-price hidden") discount = skin.find("span", class_ = "badge badge-info") wear = skin.find("span", class_ = "hidden unwrappable-float-pointer") print("name:", name.text) print("Price", price.text) print("Discount:", discount.text) # Choose which one you want for w in wear.text.split(","): print("Wear:", w) You was trying to find the incorrect class. I added some other data which you can scrape for examples. Wear holds a few values which i outputted. A: In your line of code, you are searching for a tag with a class that has multiple values. wear_box = page_content.find_all('div', attrs={'class': 'text-muted text-center'}) On the page the only tag that fits is: <div class="container text-center text-muted" style="padding-top: 17px;"> In BS4, when you are searching for attributes with multiple values, you either search for a single value eg: wear_box = page_content.find_all('p', attrs={'class': 'text-muted'}) Or you have to search for the exact list of vales eg: wear_box = page_content.find_all('div', attrs={'class': 'container text-center text-muted'})
{ "language": "en", "url": "https://stackoverflow.com/questions/54505251", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Transformation inside while loop- BPEL 10g Requirement is read data from file and invoke webservice. Target webservice can handle one payload at a time but there will be multiple payload in source. So am using while loop to process payload one by one. Issue: In target service EarningTypeInclusion is optional element, so in source some payload this element will be present and in some payload this option element will not be present. <thresholdRequestInterface xmlns:xs="http://www.sample.com/ns/LMSReferrals"> <thresholdRequest> <Referral>11</Referral> <thresholdValue>100</thresholdValue> <EarningTypeInclusion> <earningType>positive</earningType> <ProvisionId>1000</ProvisionId> </EarningTypeInclusion> </thresholdRequest> <thresholdRequest> <Referral>11</Referral> <thresholdValue>100</thresholdValue> </thresholdRequest> </thresholdRequestInterface> If am using assign activity, then selection failure fault will come when optional elements are not present in source payload. We are using BPEL 10g, no option in assign activity to supress selection failure fault. So decided to use transformation inside while loop . logic used Read from file assign Loop counter=1 Count of payload(read from file) While loop counter<= Count of payload pass loop counter param value to transform transform source i.e thresholdRequest[loopcounter] to target Invoke target web service increment loop counter end loop; Problem is same data is getting trsnformed. In the below example, referral 11 data is loading 3 times. I have checked conter value, its getting incremented but inside transformation same values are getting transformed. <thresholdRequestInterface xmlns:xs="http://www.sample.com/ns/LMSReferrals"> <thresholdRequest> <Referral>11</Referral> <thresholdValue>100</thresholdValue> <EarningTypeInclusion> <earningType>positive</earningType> <ProvisionId>1000</ProvisionId> </EarningTypeInclusion> </thresholdRequest> <thresholdRequest> <Referral>12</Referral> <thresholdValue>100</thresholdValue> </thresholdRequest> <thresholdRequest> <Referral>13</Referral> <thresholdValue>100</thresholdValue> <EarningTypeInclusion> <earningType>positive</earningType> <ProvisionId>1000</ProvisionId> </EarningTypeInclusion> </thresholdRequest> </thresholdRequestInterface> Source <?xml version="1.0" encoding="utf-8" ?> <xs:schema xmlns="http://www.sample.com/ns/LMSReferrals" attributeFormDefault="qualified" elementFormDefault="qualified" targetNamespace="http://www.sample.com/ns/LMSReferrals" xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:element name="thresholdRequestInterface"> <xs:complexType> <xs:sequence> <xs:element name="thresholdRequest" minOccurs="1" maxOccurs="unbounded"> <xs:complexType> <xs:sequence> <xs:element name="Referral" type="xs:string"/> <xs:element name="thresholdValue" type="xs:int"/> <xs:element name="EarningTypeInclusion" minOccurs="0" maxOccurs="1" > <xs:complexType> <xs:sequence> <xs:element name="earningType" type="xs:stirng" /> <xs:element name="ProvisionId"> <xs:simpleType> <xs:restriction base="xs:string"> <xs:maxLength value="20" /> </xs:restriction> </xs:simpleType> </xs:element> </xs:sequence> </xs:complexType> </xs:element> </xs:sequence> </xs:complexType> </xs:element> </xs:sequence> </xs:complexType> </xs:element> </xs:schema> Please find the schema structure for source and target Target <?xml version="1.0" encoding="utf-8" ?> <xs:schema xmlns="http://www.sample.com/ns/LMSReferrals" attributeFormDefault="qualified" elementFormDefault="qualified" targetNamespace="http://www.sample.com/ns/LMSReferrals" xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:element name="thresholdRequest"> <xs:complexType> <xs:sequence> <xs:element name="Referral" type="xs:string"/> <xs:element name="thresholdValue" type="xs:int"/> <xs:element name="EarningTypeInclusion" minOccurs="0" maxOccurs="1" > <xs:complexType> <xs:sequence> <xs:element name="earningType" type="xs:stirng" /> <xs:element name="ProvisionId"> <xs:simpleType> <xs:restriction base="xs:string"> <xs:maxLength value="20" /> </xs:restriction> </xs:simpleType> </xs:element> </xs:sequence> </xs:complexType> </xs:element> </xs:sequence> </xs:complexType> </xs:element> </xs:schema> Please note schema validation is enabled at target webservice. A: Is there a specific reason that you are using Transform.Try using ora:getElement('/thresholdRequestInterface /thresholdRequest',bpws:getVariable(loopCounter))
{ "language": "en", "url": "https://stackoverflow.com/questions/44628368", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: jQuery Waypoints sticky nav when scrolling up via a click is 1px off I'm close to tearing my hair out with Waypoints. First of all, I'm far from being experienced in javascript. I'm using Waypoints to 1) fix the nav to the top of the screen at a certain point (this works fine) and 2), highlight nav items when certain sections are reached. Everything works perfectly except when you click a nav item that requires the waypoint direction up, e.g. click "Exceptional Value" and then "Destinations." You'll notice that the waypoint seems to be a pixel off and "Exceptional Value" is still highlighted. If you scroll up a pixel, "Destinations" finally highlights. This is the only way to replicate this behavior... clicking nav items that scroll down works fine. Here is my JS: http://jsfiddle.net/TreUd/. Here is the site it's implemented on: http://ifb.thepinkrobot.com/. Thanks for any help... it's greatly appreciated. <!-- waypoints --> <script type="text/javascript"> $(document).ready(function(){ $('.nav-container').waypoint(function(direction) { $('nav#main').toggleClass('sticky', direction === 'down'); }); }); </script> <script type="text/javascript"> var sections = $("section"); var navigation_links = $("nav a"); sections.waypoint({ handler: function(event, direction) { var active_section; active_section = $(this); if (direction === "down") active_section = active_section.prev(); var active_link = $('nav a[href="#' + active_section.attr("id") + '"]'); navigation_links.removeClass("selected"); active_link.addClass("selected"); }, offset: 50 }) </script> <!-- end waypoints --> A: It's definitely a strange one. There seems to be a 3px border on your header which might be causing the issue. However if you increase the offset of your waypoints from 50 to 53 seems to fix the problem. var sections = $("section"); var navigation_links = $("nav a"); sections.waypoint({ handler: function (event, direction) { var active_section; active_section = $(this); if (direction === "down") active_section = active_section.prev(); var active_link = $('nav a[href="#' + active_section.attr("id") + '"]'); navigation_links.removeClass("selected"); active_link.addClass("selected"); }, offset: 53 })
{ "language": "en", "url": "https://stackoverflow.com/questions/15824467", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How can i order queryresults by the PK of a m2m-relationtable? I have a model with a m2m relation to users: class SomeModel(models.Model): user=models.ManyToManyField(User,related_name='linked',blank=True,null=True) to which i have a query: linked_objects=SomeModel.objects.filter(user__id__contains=request.user.id) The results are the ordered by the user id. What i want to do, is to sort the results by the primary key of the relation table between User and SomeModel, which would be appname_somemodel_user. Is this possible? A: Might be wrong about this, but I think you can only refer to the intermediary table if you specify it yourself explicitly. class SomeModel(models.Model): user=models.ManyToManyField(User,related_name='linked',blank=True,null=True, through='SomeModelUser') class SomeModelUser(models.Model): user = models.ForeignKey(User) some_model = models.ForeignKey(SomeModel) linked_objects=SomeModel.objects.filter(user__id__contains=request.user.id).order_by('somemodeluser__pk')
{ "language": "en", "url": "https://stackoverflow.com/questions/5142573", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Mapping one DTO to multiple entities I have the DB model like the following. Here I describe entities I have in the EF model: public class Person { public int Id { get; set; } public int AddressId { get; set; } public int RoleId { get; set; } public string Name { get; set; } public string Email { get; set; } } public class Address { public int Id { get; set; } public int CountryId { get;set; } public string City { get; set; } } public class Role { public int Id { get; set; } public string Name { get; set; } } public class Country { public int Id { get; set; } public string Name { get; set; } } On the front end I have the management interface allowing to edit the user info. So, in each of the grid lines I show the following DTO object: public class SystemUser { public string UserName { get; set; } public string Email { get; set; } public string City { get; set; } public string Country { get; set; } public string Role { get; set; } } The main question I have - what is the best way of mapping this back to the entities after edit was performed and I get the DTO back with AutoMapper or something else? Or am I doing something completely stupid here? Edit: There is also another challenge I have: I would like to minimize round trips to the DB. A: I find AutoMapper a great choice for creating my View Models etc. When saving I find using a Service class with a method such as Save(SystemUser user) is best because then you have room for control over validation and other things that must be done. The mapping code for creating the entities you need to save is hand done, because usually there are a lot more factors involved in the save than in the read. Therefore AutoMapper isn't such a good choice here. I normally write my service class with repositories for the various entities in it's constructor. This is more to allow for unit testing which you haven't mentioned, but would be a good design anyway. If this is the sort of thing you need then I think your on the right track.
{ "language": "en", "url": "https://stackoverflow.com/questions/18446182", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: What is the interpretation of <>P -> (!P U R) What is the interpretation of <>P -> (!P U R)? This seems to be contradiction since in future P is expected and checking the absence of P until R. Model checking tool passes this via BDD as well as BMC techniques. A: I don't see any contradiction. The property is made true by any Buchi automaton s.t. * *P is always false [because the premise of the implication is false], or *At some point in the future P becomes true, yet for some time P may be false until R becomes true. i.e. In natural language, one would express that property as follows: "If, by any chance, sooner or later P becomes true, then it must be the case that the 'event' R fired first". For instance, you can imagine P be "sending answer message" and R be "received input message" and the whole property be "no unsolicited answer message is ever sent".
{ "language": "en", "url": "https://stackoverflow.com/questions/55762828", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Create MailMessage object from .msg File Path? Is there a way to create a MailMessage object from a directory path of a .msg file? Such as MailMessage x = new MailMessage("path") A: There is no direct conversion between these two entities out of the box - the Outlook message file and the MailMessage class from the .net framework. You can automate Outlook to get the instance of the MSG file instantiated using the NameSpace.OpenSharedItem method which is used to open iCalendar appointment (.ics) files, vCard (.vcf) files, and Outlook message (.msg) files. You can also use Redemption for that, look for RDOSession.GetMessageFromMsgFile. A: Thanks for the replies but I found the answer on this existing post: C# Outlook interop and OpenSharedItem for opening MSG files Like Eugene said, I used the Microsoft.Office.Interop.Outlook.Application to open the .msg file via Outlook.
{ "language": "en", "url": "https://stackoverflow.com/questions/69486646", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Shorter and more efficient way of writing this Java code What is the best way to write this code and avoid repeatedly? if (doAction() || checkNumber() || canMove() || avoidAttackersWhileHeal()) { return; } if (doCast() || doAttack()) { return; } I have a ton of methods like this, and each method that returns true means it won't continue, but coding style like this is ugly. Is there any other way to write it? A: As alternative, you can wrap your single methods in separate Predicate and then build a common predicate with required operations. This final Predicate hides all if...else. private final Predicate<Void> predicate; { Predicate<Void> doAction = in -> doAction(); Predicate<Void> checkNumber = in -> checkNumber(); Predicate<Void> canMove = in -> canMove(); Predicate<Void> avoidAttackersWhileHeal = in -> avoidAttackersWhileHeal(); Predicate<Void> doCast = in -> doCast(); Predicate<Void> doAttack = in -> doAttack(); predicate = doAction.or(checkNumber).or(canMove).or(avoidAttackersWhileHeal).or(doCast).or(doAttack); } public void doIt() { predicate.test(null); }
{ "language": "en", "url": "https://stackoverflow.com/questions/54609837", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Python Read-only file system Error With S3 and Lambda when downloading a dump file from MYSQL I'have the following code for running query from mysql dump_query=/media/+"/mysql -u"+user+" -p'"+passwd+"' -h"+host+" "+name+" -e '"+query+"' | sed 's/\t/,/g' > "+filepath+"test.csv" proc = subprocess.Popen(dump_query, shell=True) proc.wait() fs = FileSystemStorage(filepath) with fs.open('test.csv') as record: if os.path.getsize(str(record)) == 0: messages.warning(request,"No Data available to download") if nexturl is not None: return redirect(nexturl) else: return redirect('admin_reports:status_index') response = HttpResponse(record, content_type='application/csv') response['Content-Disposition'] = 'filename="'+filename+'.csv"' return response I'm getting the below error while i'm trying to do this from lambda. I gave full permisisons to the folder and csv file /bin/sh: /var/task/media/downloads/test.csv: Read-only file system A: I believe on the Lambda, you can only write files on the /tmp directory as documented here. Try adjusting your code to do that and it should work.
{ "language": "en", "url": "https://stackoverflow.com/questions/60089963", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: mock methods regardless of params with Mockito I write an interface like this: public interface IPlayer{ boolean capture(); boolean capture(String path); } I want both of the methods return true in my unit testing.For the first method, I mock like this: IPlayer iplayer = Mockito.mock(IPlayer.class); when(iplayer.capture()).thenReturn(true); when(iplayer.capture("")).thenReturn(true); This works well with the first method.But for the second method, it returns false. How can I get true regardless of the param path when I call iplayer.capture(path)? A: Use the anyString() argument matcher: when(iplayer.capture(Mockito.anyString())).thenReturn(true);
{ "language": "en", "url": "https://stackoverflow.com/questions/45958244", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Flutter use variable created inside Future builder outside of the build method, I have a future builder witch i use to fetch data, i need to use what i get from the api to a text editing controller that has to be defined outside of build and i need to give the text editing controller an initial value, in this initial value i need to put data3.firstName and data3.lastName, for now the initial values are hardcoded. Future<Response> fetchAccountData() async { SharedPreferences prefs = await SharedPreferences.getInstance(); String? authorization = prefs.getString('authorization'); var url = 'https://dev.api.wurk.skyver.co/api/v1/employees/account'; response1 = await http.get( Uri.parse(url), headers: <String, String>{ 'authorization': authorization ?? basicAuth.toString() }, ); return response1; } factory AccountData.fromJson(Map<String, dynamic> json) { return AccountData( firstName: json['firstName'], lastName: json['lastName'], phoneNumber: json['phoneNumber']); } } Future<void> putAccountData() async { SharedPreferences prefs = await SharedPreferences.getInstance(); String? authorization = prefs.getString('authorization'); var url = 'https://dev.api.wurk.skyver.co/api/v1/employees/account'; Map payload = { "firstName": editedFirstName.text, "lastName": editedLastName.text, }; try { final response = await http.put(Uri.parse(url), headers: <String, String>{ 'authorization': authorization ?? basicAuth.toString(), "Content-Type": "application/json" }, body: jsonEncode(payload)); } catch (er) {} } TextEditingController editedFirstName = TextEditingController(text: 'firstName'); << needs to be data3.firstName TextEditingController editedLastName = TextEditingController(text: 'lastName');<< needs to be data3.lastName return SafeArea( child: WillPopScope( onWillPop: () async { Navigator.pushReplacement( context, MaterialPageRoute( builder: (context) => const ProfileScreen(), ), ); return shouldPop; }, body: FutureBuilder<Response>( future: futureData, builder: (context, snapshot) { if (snapshot.hasData) { AccountData data3 = AccountData.fromJson( << data3 has data3.firstName, and data3.lastName json.decode(snapshot.data!.body), ); A: I don't fully understand the reason to have a global TextController (and I don't think its a good idea either) but using Riverpod it would look somethink like this: import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; class AccountData { final String firstName; final String lastName; final String phoneNumber; AccountData({ required this.firstName, required this.lastName, required this.phoneNumber, }); factory AccountData.fromJson(Map<String, dynamic> json) { return AccountData( firstName: json['firstName'], lastName: json['lastName'], phoneNumber: json['phoneNumber'], ); } } Future<Map<String, dynamic>> fetchAccountData() async { final response = { 'firstName': 'Name', 'lastName': 'LastName', 'phoneNumber': '98786758690', }; return Future.delayed(const Duration(seconds: 3), () => response); } final futureData = FutureProvider<AccountData>((_) async { final data = await fetchAccountData(); return AccountData.fromJson(data); }); final firstNameController = ChangeNotifierProvider<TextEditingController>((ref) { final controller = TextEditingController(); ref.listen<AsyncValue<AccountData>>(futureData, (_, curr) { curr.whenOrNull( data: (d) => controller.text = d.firstName, ); }); return controller; }); final lastNameController = ChangeNotifierProvider<TextEditingController>((ref) { final controller = TextEditingController(); ref.listen<AsyncValue<AccountData>>(futureData, (_, curr) { curr.whenOrNull( data: (d) => controller.text = d.lastName, ); }); return controller; }); void main() { runApp(const ProviderScope(child: MyApp())); } class MyApp extends StatelessWidget { const MyApp(); @override Widget build(BuildContext context) { return MaterialApp( debugShowCheckedModeBanner: false, home: Scaffold( body: Center( child: MyWidget(), ), ), ); } } class MyWidget extends ConsumerWidget { @override Widget build(BuildContext context, WidgetRef ref) { final firstController = ref.watch(firstNameController.notifier); final lastcontroller = ref.watch(lastNameController.notifier); return ref.watch(futureData).when( loading: () => const CircularProgressIndicator(), error: (e, _) => TextButton( child: Text('$e'), onPressed: () => ref.refresh(futureData), ), data: (_) { return Column( children: [ TextField( controller: firstController, ), TextField( controller: lastcontroller, ), ] ); } ); } } Now following Hazar Belge using a late initializer is a good idea, without state managament the idea would be simply use a FutureBuilder and then pass down the data to an StatefulWidget which initialize the TextEditingControllers with that data, and again using didUpdateWidget, all of it without depending of an external package (the bigger your app you would need to use more packages to help you develop fast but I would recommend try with the basic to grasp all you can do with the framework) A: You can use late initialization like this: late TextEditingController editedFirstName; late TextEditingController editedLastName; return SafeArea( child: WillPopScope( onWillPop: () async { Navigator.pushReplacement( context, MaterialPageRoute( builder: (context) => const ProfileScreen(), ), ); return shouldPop; }, body: FutureBuilder<Response>( future: futureData, builder: (context, snapshot) { if (snapshot.hasData) { AccountData data3 = AccountData.fromJson( << data3 has data3.firstName, and data3.lastName json.decode(snapshot.data!.body), ); editedFirstName = TextEditingController(text: data3.firstname) editedLastName = TextEditingController(text: data3.lastname)
{ "language": "en", "url": "https://stackoverflow.com/questions/70980002", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: WebAPI and mvc4 An error has occurred Type '.Controllers.APICategoryController' does not have a default constructor i having this error as title mention , what causes this anyone?? heres my code i just want to display the files from SQL Database but it does have error any help? thanks! namespace a.Models public interface ICatRepository { IEnumerable<Category> GetAll(); Category Get(int id); Category Add(Category item); void Remove(int id); bool Update(Category item); } another repository namespace a.Models public class CatRepository : ICatRepository { private istellarEntities db = new istellarEntities(); public CatRepository() { } public IEnumerable<Category> GetAll() { return db.Categories; } public Category Get(int id) { return db.Categories.Find(id); } public Category Add(Category category) { db.Categories.Add(category); db.SaveChanges(); return category; } public void Remove(int id) { Category category = db.Categories.Find(id); db.Categories.Remove(category); db.SaveChanges(); } public bool Update(Category category) { db.Entry(category).State = EntityState.Modified; db.SaveChanges(); return true; } } controller namespace a.Controllers public class APICategoryController : ApiController { // static readonly ICatRepository repository = new CatRepository(); private readonly ICatRepository repository; public APICategoryController(ICatRepository repository) { if (repository == null) { throw new ArgumentNullException("repository"); } this.repository = repository; } public IEnumerable<Category> GetAllCategories() { return repository.GetAll(); } Lastly my class file namespace a.Models using System; using System.Collections.Generic; public partial class Category { public Category() { this.IQuestions = new HashSet<IQuestion>(); } public int ID { get; set; } public string Name { get; set; } public string Description { get; set; } public virtual ICollection<IQuestion> IQuestions { get; set; } } A: You've got one of the more helpful error messages there - APICategoryController does not have a default constructor, ie: a parameterless constructor. You either need to use some kind of Dependency Injector for your code to know how to instantiate a concrete class for ICatRepository, or provide a default constructor. eg: //a default constructor instantiating a concrete type. Simple, but no good for testing etc. public APICategoryController() { ICatRepository repository = new ConcreteRepository; this.repository = repository; } A: you need to add default constructor. you should add this to APICategoryController (this is default constructor) public APICategoryController() { }
{ "language": "en", "url": "https://stackoverflow.com/questions/21363710", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: how to slide out content on hover - flexbox-layout i have a beautiful little landing page with big pictures and small boxes with headings in it. if you hover over the headings, the box around it should slide out (getting more width but shouldn't push the picture away, instead it should be above the picture) the picture next to it and shows some text there. this is all done in a flexbox-bootstrap layout. will position: absolute, z-index and some left or right stuff do this trick as well even in a flexbox-content? or do i have to use some jscript/jQuery stuff? here's my bootply: http://www.bootply.com/d2liwNZnCH and the code for the greater good: <main class="container"> <div class="row row-flex row-flex-wrap"> <div class="col-md-3 bgb fw"> <div class="contentbox flex-col"> <h2>example</h2> </div> </div> <div class="col-md-3"> <div class="imagecontainer"> <img src="http://placehold.it/365x365" alt="Beispielinhalt" class="img-responsive"> </div> </div> <div class="col-md-3"> <div class="imagecontainer"> <img src="http://placehold.it/365x365" alt="Beispielinhalt" class="img-responsive"> </div> </div> <div class="col-md-3 bgr fw"> <div class="contentbox flex-col"> <h2>example</h2> </div> </div> </div> <div class="row row-flex row-flex-wrap"> <div class="col-md-8"> <div class="imagecontainer"> <img src="http://placehold.it/1265x365" alt="Beispielinhalt" class="img-responsive"> </div> </div> <div class="col-md-4 bgp fw"> <div class="contentbox flex-col"> <h2>example</h2> </div> </div> </div> <div class="row row-flex row-flex-wrap"> <div class="col-md-5 bgg fw"> <div class="contentbox flex-col"> <h2>example</h2> </div> </div> <div class="col-md-7"> <div class="imagecontainer"> <img src="http://placehold.it/765x365" alt="Beispielinhalt" class="img-responsive"> </div> </div> </div> </main> <!-- Maincontent --> css: .col-xs-1, .col-sm-1, .col-md-1, .col-lg-1, .col-xs-2, .col-sm-2, .col-md-2, .col-lg-2, .col-xs-3, .col-sm-3, .col-md-3, .col-lg-3, .col-xs-4, .col-sm-4, .col-md-4, .col-lg-4, .col-xs-5, .col-sm-5, .col-md-5, .col-lg-5, .col-xs-6, .col-sm-6, .col-md-6, .col-lg-6, .col-xs-7, .col-sm-7, .col-md-7, .col-lg-7, .col-xs-8, .col-sm-8, .col-md-8, .col-lg-8, .col-xs-9, .col-sm-9, .col-md-9, .col-lg-9, .col-xs-10, .col-sm-10, .col-md-10, .col-lg-10, .col-xs-11, .col-sm-11, .col-md-11, .col-lg-11, .col-xs-12, .col-sm-12, .col-md-12, .col-lg-12 { margin: 0; padding: 0; } .row-flex, .row-flex > div[class*='col-'] { display: -webkit-box; display: -moz-box; display: -ms-flexbox; display: -webkit-flex; display: flex; flex:1 1 auto; } .row-flex-wrap { -webkit-flex-flow: row wrap; align-content: flex-start; flex:0; } .row-flex > div[class*='col-'], .container-flex > div[class*='col-'] { margin:-.2px; /* hack adjust for wrapping */ } .container-flex > div[class*='col-'] div,.row-flex > div[class*='col-'] div { width:100%; } .flex-col { display: flex !important; display: -webkit-flex !important; flex: 1 100%; flex-flow: column nowrap; align-items: center; justify-content: center; } .flex-grow { display: flex; -webkit-flex: 2; flex: 2; } h1, h2, h3, h4, h5, h6 { margin-top: 0px; word-break: break-word; } .contentbox { padding: 15px 30px 15px 30px; text-align: center; display: block; } .contentbox h2 { font-variant: small-caps; } .imagecontainer { display: block; } A: did it with a second ".contentbox"-div and some helper classes and jQuery click event and i chosed to fade the readmore-text in the contentbox itself above the centered heading. html: <div class="col-lg-3 col-sm-6 col-xs-12 fw"> <div class="contentbox readmore bgr flex-col"> <h2>example</h2> </div> <div class="contentbox expand bgr flex-col"> <span aria-hidden="true" class="pull-right closebox">&times;</span> <p>Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata.</p> <p><a href="#" class="btn btn-default">read more</a></p> </div> </div> css: .contentbox { padding: 15px 30px 15px 30px; text-align: center; display: block; height: auto; min-height: 160px; /* Only for my layout */ } .readmore { cursor: pointer; /* So your complete box seems clickable */ } .expand { position: absolute; top: 0; /* You can switch these values to whatever values wished */ left: 0; /* It will then slide from the direction you chose */ right: 0; /* but remember to put the chosen direction to 0 again on .expanded */ bottom: 0; /* for me, the fadeeffect was the most elegant way */ font-size: 15px; opacity: 0; visibility: hidden; transition: all .75s ease-in-out; } .expanded { top: 0; opacity: 1; visibility: visible; cursor: default; transition: all .75s ease-in-out; } .closebox { font-size: 24px; position: absolute; right: 10px; top: 0px; cursor: pointer; } js within document ready: $(".readmore").click(function(){ $(this).next(".expand").addClass("expanded"); }); $(".closebox").click(function(){ $(this).parent(".expanded").removeClass("expanded"); });
{ "language": "en", "url": "https://stackoverflow.com/questions/35367591", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to set a position that changes when the window size changes I'm creating a web page for my grandpa, and I'm going to have this lil biker dude, that runs across the screen and when hovered over, stops and says"wear a helmet". I got him to move back and forth and it is fixed to the navbar, but the problem is that when the screen size changes, say it's on a smaller phone or computer, then the biker dude turns around at a different spot and it runs infront of the navbar stuff. here is the html: <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous"> <title>CountrySideBycicling</title> <link rel="stylesheet" href="main.css"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-social/5.1.1/bootstrap-social.min.css"> <script src="https://kit.fontawesome.com/8333c8288f.js" crossorigin="anonymous"></script> </head> <body> <!-- lil dude --> <h6 id="message"></h6> <img src="../lil dude/riding.gif" alt="riding" id="riding"> <script> let message = document.getElementById('message'); let speed = 5; let lastspeed = 0; let counter = 0; let x = 50; let y = 25; let mX = 0; let mY = 0; //flipping and animating function move() { x += speed; document.getElementById('riding').style.left=(x + "px"); if (x + document.getElementById('riding').style.width >= window.innerWidth - 550) { speed = -5; document.getElementById('riding').style.transform="rotateY(150deg)"; } if (x <= 200) { speed = 5; document.getElementById('riding').style.transform="rotateY(0deg)"; } if (speed == 0) { document.getElementById('riding').src="../lil dude/stop.gif"; message.style.top = (y - 40 + "px"); message.style.left = (x + 50 + "px"); message.innerHTML = "Wear a Helmet!"; setTimeout(reset, 2000);console.log('hi'); } else requestAnimationFrame(move); } //mouse move collision detection window.addEventListener('mousemove', function(e) { mX = e.clientX; mY = e.clientY; if (mX >= x && mX <= x + 50 && mY >= y && mY <= y + 40) { lastspeed = speed || lastspeed; if (counter == 0) { slow(); counter = 1; } } console.log(mX + " " + mY) }); //braking it function slow() { document.getElementById('riding').src="../lil dude/brake.gif"; do { if (speed > 0){ speed -= 0.1; } else if(speed < 0) { speed += 0.1; } } while (Math.abs(speed)>0.01); speed=0; } //reset function reset() { document.getElementById('riding').src="../lil dude/riding.gif"; message.innerHTML = ""; do { if (lastspeed > 0) { speed += 0.1; } else if (lastspeed < 0) { speed -= 0.1; }console.log(lastspeed,speed); } while(5-Math.abs(speed) > 0.01); move(); counter = 0; } move(); </script> <nav class="navbar navbar-expand-lg navbar-dark bg-dark static-top"> <div class="container"> <a class="navbar-brand" href="#"> <!-- logo --> <img class = "navbar-brand" src="https://w7.pngwing.com/pngs/764/321/png-transparent-bicycle-shop-cycling-logo-fixed-gear-bicycle-cyclist-top-sport-bicycle-logo.png" alt=""> </a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarResponsive" aria-controls="navbarResponsive" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarResponsive"> <ul class="navbar-nav ml-auto"> <li class="nav-item active"> <a class="nav-link" href="index.html">Home <span class="sr-only">(current)</span> </a> </li> <li class="nav-item"> <a class="nav-link" href="about.html">About</a> </li> <li class="nav-item"> <a class="nav-link" href="gallery.html">Gallery</a> </li> <li class="nav-item"> <a class="nav-link" href="services.html">Services</a> </li> <li class="nav-item"> <a class="nav-link" href="contacts.html">Contact</a> </li> <li class="nav-item"> <a class="nav-link" href="brands.html.html">Brands</a> </li> </ul> </div> </div> </nav> <div style="height: 50;"></div> <div class="jumbotron text-center"> <div class="container"> <div style="height: 25px;"></div> <h1>CountrySideBycicling</h1> <div style="height: 25px;"></div> <p> Lorem ipsum dolor sit amet consectetur adipisicing elit. Quisquam officiis aperiam temporibus exercitationem hic provident nesciunt, quod officia neque quam sint dicta, mollitia commodi illo necessitatibus inventore blanditiis eveniet maiores. </p> <div style="height: 25px;"></div> <button class="btn btn-primary">Read More</button> </div> </div> <!-- Page Content --> <div class="container"> <!-- Heading Row --> <div class="row align-items-center my-5"> <div class="col-lg-7"> <img class="img-fluid rounded mb-4 mb-lg-0" src="http://placehold.it/900x400" alt=""> </div> <!-- /.col-lg-8 --> <div class="col-lg-5"> <h1 class="font-weight-light">Business Name or Tagline</h1> <p>This is a template that is great for small businesses. It doesn't have too much fancy flare to it, but it makes a great use of the standard Bootstrap core components. Feel free to use this template for any project you want!</p> <a class="btn btn-primary" href="#">Call to Action!</a> </div> <!-- /.col-md-4 --> </div> <!-- /.row --> <!-- Call to Action Well --> <div class="card text-white bg-secondary my-5 py-4 text-center"> <div class="card-body"> <p class="text-white m-0">This call to action card is a great place to showcase some important information or display a clever tagline!</p> </div> </div> <!-- /.col-md-4 --> </div> <!-- /.row --> </div> <!-- /.container --> <!-- Content section --> <section class="py-5"> <div class="container"> <h1>Section Heading</h1> <p class="lead">Lorem ipsum dolor sit amet, consectetur adipisicing elit.</p> <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Aliquid, suscipit, rerum quos facilis repellat architecto commodi officia atque nemo facere eum non illo voluptatem quae delectus odit vel itaque amet.</p> </div> </section> <!-- Image Section - set the background image for the header in the line below --> <section class="py-5 bg-image-full" style="background-image: url('https://unsplash.it/1900/1080?image=1081');"> <!-- Put anything you want here! There is just a spacer below for demo purposes! --> <div style="height: 200px;"></div> </section> <!-- Content section --> <section class="py-5"> <div class="container"> <h1>Section Heading</h1> <p class="lead">Lorem ipsum dolor sit amet, consectetur adipisicing elit.</p> <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Aliquid, suscipit, rerum quos facilis repellat architecto commodi officia atque nemo facere eum non illo voluptatem quae delectus odit vel itaque amet.</p> </div> </section> <!-- slider --> <div id="carouselExampleIndicators" class="carousel slide" data-ride="carousel"> <ol class="carousel-indicators"> <li data-target="#carouselExampleIndicators" data-slide-to="0" class="active"></li> <li data-target="#carouselExampleIndicators" data-slide-to="1"></li> <li data-target="#carouselExampleIndicators" data-slide-to="2"></li> </ol> <div class="carousel-inner" role="listbox"> <div class="carousel-item active"></div> <div id="target" class="carousel-item"></div> <div class="carousel-item"></div> </div> <a class="carousel-control-prev" href="#carouselExampleIndicators" role="button" data-slide="prev"> <span class="carousel-control-prev-icon" aria-hidden="true"></span> <span class="sr-only">Previous</span> </a> <a class="carousel-control-next" href="#carouselExampleIndicators" role="button" data-slide="next"> <span class="carousel-control-next-icon" aria-hidden="true"></span> <span class="sr-only">Next</span> </a> </div> <div style="height: 50px;"></div> </div> </div> <div class="container"> <!-- Content Row --> <div class="row"> <div class="col-md-4 mb-5"> <div class="card h-100"> <div class="card-body"> <h2 class="card-title">Card One</h2> <p class="card-text">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Rem magni quas ex numquam, maxime minus quam molestias corporis quod, ea minima accusamus.</p> </div> <div class="card-footer"> <a href="#" class="btn btn-primary btn-sm">More Info</a> </div> </div> </div> <!-- /.col-md-4 --> <div class="col-md-4 mb-5"> <div class="card h-100"> <div class="card-body"> <h2 class="card-title">Card Two</h2> <p class="card-text">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quod tenetur ex natus at dolorem enim! Nesciunt pariatur voluptatem sunt quam eaque, vel, non in id dolore voluptates quos eligendi labore.</p> </div> <div class="card-footer"> <a href="#" class="btn btn-primary btn-sm">More Info</a> </div> </div> </div> <!-- /.col-md-4 --> <div class="col-md-4 mb-5"> <div class="card h-100"> <div class="card-body"> <h2 class="card-title">Card Three</h2> <p class="card-text">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Rem magni quas ex numquam, maxime minus quam molestias corporis quod, ea minima accusamus.</p> </div> <div class="card-footer"> <a href="#" class="btn btn-primary btn-sm">More Info</a> </div> </div> </div> </div> </div> <!-- Footer --> <footer class="page-footer font-small mdb-color pt-4"> <!-- Footer Links --> <div class="container text-center text-md-left"> <!-- Footer links --> <div class="row text-center text-md-left mt-3 pb-3"> <!-- Grid column --> <div class="col-md-3 col-lg-3 col-xl-3 mx-auto mt-3"> <h6 class="text-uppercase mb-4 font-weight-bold">CountrySideBycicling</h6> <p>Here you can use rows and columns to organize your footer content. Lorem ipsum dolor sit amet, consectetur adipisicing elit.</p> </div> <!-- Grid column --> <hr class="w-100 clearfix d-md-none"> <!-- Grid column --> <div class="col-md-2 col-lg-2 col-xl-2 mx-auto mt-3"> <h6 class="text-uppercase mb-4 font-weight-bold">Brand Sites</h6> <p> <a href="#!">Bikesite</a> </p> <p> <a href="#!">Bikesite</a> </p> <p> <a href="#!">Bikesite</a> </p> </div> <!-- Grid column --> <hr class="w-100 clearfix d-md-none"> <!-- Grid column --> <div class="col-md-3 col-lg-2 col-xl-2 mx-auto mt-3"> <h6 class="text-uppercase mb-4 font-weight-bold">Useful links</h6> <p> <a href="gallery.html">Gallary</a> </p> <p> <a href="brands.html">Brands</a> </p> <p> <a href="about.html">About</a> </p> </div> <!-- Grid column --> <hr class="w-100 clearfix d-md-none"> <!-- Grid column --> <div class="col-md-4 col-lg-3 col-xl-3 mx-auto mt-3"> <h6 class="text-uppercase mb-4 font-weight-bold">Contact</h6> <p> <i class="fas fa-home mr-3"></i> windsor, oh, cox road</p> <p> <i class="fas fa-envelope mr-3"></i> grandpa@gmail.com</p> <p> <i class="fas fa-phone mr-3"></i> + 01 234 567 88</p> </div> <!-- Grid column --> </div> <!-- Footer links --> <hr> <!-- Grid row --> <div class="row d-flex align-items-center"> <!-- Grid column --> <div class="col-md-7 col-lg-8"> <!--Copyright--> <p class="text-center text-md-left">© 2020 Copyright: <a href="http://www.countrysidebicycling.com/"> <strong>countrysidebicycling.com</strong> </a> </p> </div> <!-- Grid column --> <!-- Grid column --> <div class="col-md-5 col-lg-4 ml-lg-0"> <!-- Social buttons --> <div class="text-center text-md-right"> <ul class="list-unstyled list-inline"> <li class="list-inline-item"> <a class="btn btn-social-icon btn-vk"> <span class="fa fa-facebook"></span> </a> </li> <li class="list-inline-item"> <a class="btn btn-social-icon btn-vk"> <span class="fa fa-instagram"></span> </a> </li> <li class="list-inline-item"> <a class="btn btn-social-icon btn-vk"> <span class="fa fa-twitter"></span> </a> </li> <li class="list-inline-item"> <a class="btn btn-social-icon btn-vk"> <span class="fa fa-pinterest"></span> </a> </li> </ul> </div> </div> <!-- Grid column --> </div> <!-- Grid row --> </div> <!-- Footer Links --> </footer> <script src="jquery.slim.min.js"></script> <script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script> </body> </html> here is the css margin: 0; padding: 0; } div{ width: 100%; height: 100%; } .navbar-default { background: none; } .navbar{ position: fixed; z-index: 10; padding: 10px 0 10px 10px; top: 0; width: 100%; } footer{ background-color:#e6e6e6; } .jumbotron{ background-image: url('download.jpeg'); color: white; background-attachment: fixed; background-repeat: no-repeat; background-size: cover; min-height: 400px; margin-top: 0px; margin-bottom: 8px; } a{ color:#2e5984; } .navbar-brand{ height: 60px; width: 100px; } #aboutusimg{ background-size: 100%; background-image: url(download.jpeg); background-repeat:no-repeat; height: 400px; } /* slider */ .carousel .carousel-item { width: 100%; height: 100vh; background-size: cover; background-position: center; } .carousel .carousel-item:first-of-type { background-image: url('download.jpeg'); } .carousel .carousel-item:nth-of-type(2) { background-image: url("download.jpeg"); } .carousel .carousel-item:last-of-type { background-image: url("download.jpeg"); } .carousel-control-prev-icon, .carousel-control-next-icon { width: 50px; height: 50px; } /* partners slider, about page */ /* carousel */ h2{ text-align:center; padding: 20px; } /* Slider */ .slick-slide { margin: 0px 20px; } .slick-slide img { width: 100%; } .slick-slider { position: relative; display: block; box-sizing: border-box; -webkit-user-select: none; -moz-user-select: none; -ms-user-select: none; user-select: none; -webkit-touch-callout: none; -khtml-user-select: none; -ms-touch-action: pan-y; touch-action: pan-y; -webkit-tap-highlight-color: transparent; } .slick-list { position: relative; display: block; overflow: hidden; margin: 0; padding: 0; } .slick-list:focus { outline: none; } .slick-list.dragging { cursor: pointer; cursor: hand; } .slick-slider .slick-track, .slick-slider .slick-list { -webkit-transform: translate3d(0, 0, 0); -moz-transform: translate3d(0, 0, 0); -ms-transform: translate3d(0, 0, 0); -o-transform: translate3d(0, 0, 0); transform: translate3d(0, 0, 0); } .slick-track { position: relative; top: 0; left: 0; display: block; } .slick-track:before, .slick-track:after { display: table; content: ''; } .slick-track:after { clear: both; } .slick-loading .slick-track { visibility: hidden; } .slick-slide { display: none; float: left; height: 100%; min-height: 1px; } [dir='rtl'] .slick-slide { float: right; } .slick-slide img { display: block; } .slick-slide.slick-loading img { display: none; } .slick-slide.dragging img { pointer-events: none; } .slick-initialized .slick-slide { display: block; } .slick-loading .slick-slide { visibility: hidden; } .slick-vertical .slick-slide { display: block; height: auto; border: 1px solid transparent; } .slick-arrow.slick-hidden { display: none; } /* lil dude */ #riding{ width: 50px; height: 40px; z-index: 30; position: fixed; top: 25px; left: 0px; transform: rotateY(0deg); } #message{ color: white; position: fixed; top: 0; left: 0; } keep in mind that there are other files, this is just the index.html, so the css has other stuff in it, but the little dude is at the bottom of the css, and before the navbar in the html. A: The hardcoded values of 200 and 550 will not work when the navbar dimensions are adjusted for diffeerent size screens. I've changed it to retrieve the offsetWidth and offsetLeft of the (.navbar-toggle button or .nav-item[0]) and .navbar-brand image to bounce back. body { margin: 0; padding: 0; } div{ width: 100%; height: 100%; } .navbar-default { background: none; } .navbar{ position: fixed; z-index: 10; padding: 10px 0 10px 10px; top: 0; width: 100%; } footer{ background-color:#e6e6e6; } .jumbotron{ background-image: url('download.jpeg'); color: white; background-attachment: fixed; background-repeat: no-repeat; background-size: cover; min-height: 400px; margin-top: 0px; margin-bottom: 8px; } a{ color:#2e5984; } .navbar-brand{ height: 60px; width: 100px; } #aboutusimg{ background-size: 100%; background-image: url(download.jpeg); background-repeat:no-repeat; height: 400px; } /* slider */ .carousel .carousel-item { width: 100%; height: 100vh; background-size: cover; background-position: center; } .carousel .carousel-item:first-of-type { background-image: url('download.jpeg'); } .carousel .carousel-item:nth-of-type(2) { background-image: url("download.jpeg"); } .carousel .carousel-item:last-of-type { background-image: url("download.jpeg"); } .carousel-control-prev-icon, .carousel-control-next-icon { width: 50px; height: 50px; } /* partners slider, about page */ /* carousel */ h2{ text-align:center; padding: 20px; } /* Slider */ .slick-slide { margin: 0px 20px; } .slick-slide img { width: 100%; } .slick-slider { position: relative; display: block; box-sizing: border-box; -webkit-user-select: none; -moz-user-select: none; -ms-user-select: none; user-select: none; -webkit-touch-callout: none; -khtml-user-select: none; -ms-touch-action: pan-y; touch-action: pan-y; -webkit-tap-highlight-color: transparent; } .slick-list { position: relative; display: block; overflow: hidden; margin: 0; padding: 0; } .slick-list:focus { outline: none; } .slick-list.dragging { cursor: pointer; cursor: hand; } .slick-slider .slick-track, .slick-slider .slick-list { -webkit-transform: translate3d(0, 0, 0); -moz-transform: translate3d(0, 0, 0); -ms-transform: translate3d(0, 0, 0); -o-transform: translate3d(0, 0, 0); transform: translate3d(0, 0, 0); } .slick-track { position: relative; top: 0; left: 0; display: block; } .slick-track:before, .slick-track:after { display: table; content: ''; } .slick-track:after { clear: both; } .slick-loading .slick-track { visibility: hidden; } .slick-slide { display: none; float: left; height: 100%; min-height: 1px; } [dir='rtl'] .slick-slide { float: right; } .slick-slide img { display: block; } .slick-slide.slick-loading img { display: none; } .slick-slide.dragging img { pointer-events: none; } .slick-initialized .slick-slide { display: block; } .slick-loading .slick-slide { visibility: hidden; } .slick-vertical .slick-slide { display: block; height: auto; border: 1px solid transparent; } .slick-arrow.slick-hidden { display: none; } /* lil dude */ #riding{ width: 50px; height: 40px; z-index: 30; position: fixed; top: 25px; left: 0px; transform: rotateY(0deg); } #message{ color: white; position: fixed; top: 0; left: 0; } <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous"> <title>CountrySideBycicling</title> <link rel="stylesheet" href="main.css"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-social/5.1.1/bootstrap-social.min.css"> <script src="https://kit.fontawesome.com/8333c8288f.js" crossorigin="anonymous"></script> </head> <body> <!-- lil dude --> <h6 id="message"></h6> <img src="../lil dude/riding.gif" alt="riding" id="riding"> <script> let message = document.getElementById('message'); let speed = 5; let lastspeed = 0; let counter = 0; let x = 50; let y = 25; let mX = 0; let mY = 0; //flipping and animating function move() { x += speed; document.getElementById('riding').style.left=(x + "px"); var v=document.getElementsByClassName('navbar-toggler')[0]; if(v&&v.offsetLeft===0) v=document.getElementsByClassName('nav-item')[0]; var w=document.getElementsByClassName('navbar-brand')[0]; if (speed > 0 && x + document.getElementById('riding').style.width >= (v&&(v.offsetLeft-v.offsetWidth))) { speed = -5; document.getElementById('riding').style.transform="rotateY(150deg)"; } if (speed < 0 && x <= (!w||(w.offsetLeft+w.offsetWidth))) { speed = 5; document.getElementById('riding').style.transform="rotateY(0deg)"; } if (speed == 0) { document.getElementById('riding').src="../lil dude/stop.gif"; message.style.top = (y - 40 + "px"); message.style.left = (x + 50 + "px"); message.innerHTML = "Wear a Helmet!"; setTimeout(reset, 2000);console.log('hi'); } else requestAnimationFrame(move); } //mouse move collision detection window.addEventListener('mousemove', function(e) { mX = e.clientX; mY = e.clientY; if (mX >= x && mX <= x + 50 && mY >= y && mY <= y + 40) { lastspeed = speed || lastspeed; if (counter == 0) { slow(); counter = 1; } } console.log(mX + " " + mY) }); //braking it function slow() { document.getElementById('riding').src="../lil dude/brake.gif"; do { if (speed > 0){ speed -= 0.1; } else if(speed < 0) { speed += 0.1; } } while (Math.abs(speed)>0.01); speed=0; } //reset function reset() { document.getElementById('riding').src="../lil dude/riding.gif"; message.innerHTML = ""; do { if (lastspeed > 0) { speed += 0.1; } else if (lastspeed < 0) { speed -= 0.1; }console.log(lastspeed,speed); } while(5-Math.abs(speed) > 0.01); move(); counter = 0; } move(); </script> <nav class="navbar navbar-expand-lg navbar-dark bg-dark static-top"> <div class="container"> <a class="navbar-brand" href="#"> <!-- logo --> <img class = "navbar-brand" src="https://w7.pngwing.com/pngs/764/321/png-transparent-bicycle-shop-cycling-logo-fixed-gear-bicycle-cyclist-top-sport-bicycle-logo.png" alt=""> </a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarResponsive" aria-controls="navbarResponsive" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarResponsive"> <ul class="navbar-nav ml-auto"> <li class="nav-item active"> <a class="nav-link" href="index.html">Home <span class="sr-only">(current)</span> </a> </li> <li class="nav-item"> <a class="nav-link" href="about.html">About</a> </li> <li class="nav-item"> <a class="nav-link" href="gallery.html">Gallery</a> </li> <li class="nav-item"> <a class="nav-link" href="services.html">Services</a> </li> <li class="nav-item"> <a class="nav-link" href="contacts.html">Contact</a> </li> <li class="nav-item"> <a class="nav-link" href="brands.html.html">Brands</a> </li> </ul> </div> </div> </nav> <div style="height: 50;"></div> <div class="jumbotron text-center"> <div class="container"> <div style="height: 25px;"></div> <h1>CountrySideBycicling</h1> <div style="height: 25px;"></div> <p> Lorem ipsum dolor sit amet consectetur adipisicing elit. Quisquam officiis aperiam temporibus exercitationem hic provident nesciunt, quod officia neque quam sint dicta, mollitia commodi illo necessitatibus inventore blanditiis eveniet maiores. </p> <div style="height: 25px;"></div> <button class="btn btn-primary">Read More</button> </div> </div> <!-- Page Content --> <div class="container"> <!-- Heading Row --> <div class="row align-items-center my-5"> <div class="col-lg-7"> <img class="img-fluid rounded mb-4 mb-lg-0" src="http://placehold.it/900x400" alt=""> </div> <!-- /.col-lg-8 --> <div class="col-lg-5"> <h1 class="font-weight-light">Business Name or Tagline</h1> <p>This is a template that is great for small businesses. It doesn't have too much fancy flare to it, but it makes a great use of the standard Bootstrap core components. Feel free to use this template for any project you want!</p> <a class="btn btn-primary" href="#">Call to Action!</a> </div> <!-- /.col-md-4 --> </div> <!-- /.row --> <!-- Call to Action Well --> <div class="card text-white bg-secondary my-5 py-4 text-center"> <div class="card-body"> <p class="text-white m-0">This call to action card is a great place to showcase some important information or display a clever tagline!</p> </div> </div> <!-- /.col-md-4 --> </div> <!-- /.row --> </div> <!-- /.container --> <!-- Content section --> <section class="py-5"> <div class="container"> <h1>Section Heading</h1> <p class="lead">Lorem ipsum dolor sit amet, consectetur adipisicing elit.</p> <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Aliquid, suscipit, rerum quos facilis repellat architecto commodi officia atque nemo facere eum non illo voluptatem quae delectus odit vel itaque amet.</p> </div> </section> <!-- Image Section - set the background image for the header in the line below --> <section class="py-5 bg-image-full" style="background-image: url('https://unsplash.it/1900/1080?image=1081');"> <!-- Put anything you want here! There is just a spacer below for demo purposes! --> <div style="height: 200px;"></div> </section> <!-- Content section --> <section class="py-5"> <div class="container"> <h1>Section Heading</h1> <p class="lead">Lorem ipsum dolor sit amet, consectetur adipisicing elit.</p> <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Aliquid, suscipit, rerum quos facilis repellat architecto commodi officia atque nemo facere eum non illo voluptatem quae delectus odit vel itaque amet.</p> </div> </section> <!-- slider --> <div id="carouselExampleIndicators" class="carousel slide" data-ride="carousel"> <ol class="carousel-indicators"> <li data-target="#carouselExampleIndicators" data-slide-to="0" class="active"></li> <li data-target="#carouselExampleIndicators" data-slide-to="1"></li> <li data-target="#carouselExampleIndicators" data-slide-to="2"></li> </ol> <div class="carousel-inner" role="listbox"> <div class="carousel-item active"></div> <div id="target" class="carousel-item"></div> <div class="carousel-item"></div> </div> <a class="carousel-control-prev" href="#carouselExampleIndicators" role="button" data-slide="prev"> <span class="carousel-control-prev-icon" aria-hidden="true"></span> <span class="sr-only">Previous</span> </a> <a class="carousel-control-next" href="#carouselExampleIndicators" role="button" data-slide="next"> <span class="carousel-control-next-icon" aria-hidden="true"></span> <span class="sr-only">Next</span> </a> </div> <div style="height: 50px;"></div> </div> </div> <div class="container"> <!-- Content Row --> <div class="row"> <div class="col-md-4 mb-5"> <div class="card h-100"> <div class="card-body"> <h2 class="card-title">Card One</h2> <p class="card-text">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Rem magni quas ex numquam, maxime minus quam molestias corporis quod, ea minima accusamus.</p> </div> <div class="card-footer"> <a href="#" class="btn btn-primary btn-sm">More Info</a> </div> </div> </div> <!-- /.col-md-4 --> <div class="col-md-4 mb-5"> <div class="card h-100"> <div class="card-body"> <h2 class="card-title">Card Two</h2> <p class="card-text">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quod tenetur ex natus at dolorem enim! Nesciunt pariatur voluptatem sunt quam eaque, vel, non in id dolore voluptates quos eligendi labore.</p> </div> <div class="card-footer"> <a href="#" class="btn btn-primary btn-sm">More Info</a> </div> </div> </div> <!-- /.col-md-4 --> <div class="col-md-4 mb-5"> <div class="card h-100"> <div class="card-body"> <h2 class="card-title">Card Three</h2> <p class="card-text">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Rem magni quas ex numquam, maxime minus quam molestias corporis quod, ea minima accusamus.</p> </div> <div class="card-footer"> <a href="#" class="btn btn-primary btn-sm">More Info</a> </div> </div> </div> </div> </div> <!-- Footer --> <footer class="page-footer font-small mdb-color pt-4"> <!-- Footer Links --> <div class="container text-center text-md-left"> <!-- Footer links --> <div class="row text-center text-md-left mt-3 pb-3"> <!-- Grid column --> <div class="col-md-3 col-lg-3 col-xl-3 mx-auto mt-3"> <h6 class="text-uppercase mb-4 font-weight-bold">CountrySideBycicling</h6> <p>Here you can use rows and columns to organize your footer content. Lorem ipsum dolor sit amet, consectetur adipisicing elit.</p> </div> <!-- Grid column --> <hr class="w-100 clearfix d-md-none"> <!-- Grid column --> <div class="col-md-2 col-lg-2 col-xl-2 mx-auto mt-3"> <h6 class="text-uppercase mb-4 font-weight-bold">Brand Sites</h6> <p> <a href="#!">Bikesite</a> </p> <p> <a href="#!">Bikesite</a> </p> <p> <a href="#!">Bikesite</a> </p> </div> <!-- Grid column --> <hr class="w-100 clearfix d-md-none"> <!-- Grid column --> <div class="col-md-3 col-lg-2 col-xl-2 mx-auto mt-3"> <h6 class="text-uppercase mb-4 font-weight-bold">Useful links</h6> <p> <a href="gallery.html">Gallary</a> </p> <p> <a href="brands.html">Brands</a> </p> <p> <a href="about.html">About</a> </p> </div> <!-- Grid column --> <hr class="w-100 clearfix d-md-none"> <!-- Grid column --> <div class="col-md-4 col-lg-3 col-xl-3 mx-auto mt-3"> <h6 class="text-uppercase mb-4 font-weight-bold">Contact</h6> <p> <i class="fas fa-home mr-3"></i> windsor, oh, cox road</p> <p> <i class="fas fa-envelope mr-3"></i> grandpa@gmail.com</p> <p> <i class="fas fa-phone mr-3"></i> + 01 234 567 88</p> </div> <!-- Grid column --> </div> <!-- Footer links --> <hr> <!-- Grid row --> <div class="row d-flex align-items-center"> <!-- Grid column --> <div class="col-md-7 col-lg-8"> <!--Copyright--> <p class="text-center text-md-left">© 2020 Copyright: <a href="http://www.countrysidebicycling.com/"> <strong>countrysidebicycling.com</strong> </a> </p> </div> <!-- Grid column --> <!-- Grid column --> <div class="col-md-5 col-lg-4 ml-lg-0"> <!-- Social buttons --> <div class="text-center text-md-right"> <ul class="list-unstyled list-inline"> <li class="list-inline-item"> <a class="btn btn-social-icon btn-vk"> <span class="fa fa-facebook"></span> </a> </li> <li class="list-inline-item"> <a class="btn btn-social-icon btn-vk"> <span class="fa fa-instagram"></span> </a> </li> <li class="list-inline-item"> <a class="btn btn-social-icon btn-vk"> <span class="fa fa-twitter"></span> </a> </li> <li class="list-inline-item"> <a class="btn btn-social-icon btn-vk"> <span class="fa fa-pinterest"></span> </a> </li> </ul> </div> </div> <!-- Grid column --> </div> <!-- Grid row --> </div> <!-- Footer Links --> </footer> <script src="jquery.slim.min.js"></script> <script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script> </body> </html> here is the css
{ "language": "en", "url": "https://stackoverflow.com/questions/61622962", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Curl Not Sending I have this curls on my localhost and these just works fine doing its task. These curls are: [1] - GCM ; [2] - my own api. However, when uploaded these files to my online server, curl [2] is not working but curl [1] is just doing fine. // curl [1] - my own api public function send($recipient, $message) { // $client = new GuzzleHttp\Client(); // $r = $client->post('http://link.to.api', [ // 'body' => [ // 'recipient' => $recipient, // 'message' => $message['message'] // ] ]); // $response = $client->send($r); // $postData = 'recipient='.$recipient. // '&message='.$message['message']; // shell_exec('curl -i -X POST "http://link.to.api" -d "'. $postData.'"'); $url = 'http://link.to.api'; $ch = curl_init(); curl_setopt($ch,CURLOPT_URL,$url); curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch,CURLOPT_HEADER, false); curl_setopt($ch,CURLOPT_RETURNTRANSFER,true); // curl_setopt($ch, CURLOPT_POST, count($postData)); // Disabling SSL Certificate support temporarly curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_POSTFIELDS, array('recipient'=>'123123', 'message'=>'assss')); $output=curl_exec($ch); curl_close($ch); return $output; } // curl [2] - GCM public function send($reg_ids, $message) { // Set POST variables $url = 'https://android.googleapis.com/gcm/send'; $GOOGLE_API_KEY = '11111111111111111111111111111111'; $fields = array( 'registration_ids' => $reg_ids, 'data' => $message, ); $headers = array( 'Authorization: key=' . $GOOGLE_API_KEY, 'Content-Type: application/json' ); // Open connection $ch = curl_init(); // Set the url, number of POST vars, POST data curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // Disabling SSL Certificate support temporarly curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields)); // Execute post $result = curl_exec($ch); if ($result === FALSE) { die('Curl failed: ' . curl_error($ch)); } // Close connection curl_close($ch); return $result; } As you can see, I have tried different options for send my curl[2]. Any tips and help? My website that do these things and my [link.to.api] are stored in the same server. A: curl_setopt($ch, CURLOPT_POSTFIELDS, array('recipient'=>'123123', 'message'=>'assss')); I just change the above code to this: curl_setopt($ch, CURLOPT_POSTFIELDS, $postData); where $postData is: $postData = 'recipient='.$recipient.'&message='.$message['message'] Alas!
{ "language": "en", "url": "https://stackoverflow.com/questions/29794548", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to tell Mathematica to replace 0 to power 0 by 1? Experts; Given f = (#1^#2) & Is there a way to define 'f' above such that if #1 and #2 are both zero, then the value of the pure function 'f' should be 1 ? so that when I write f[0,0] it will return 1 and not Indeterminate? btw, I know I can write f = (If[#1 == 0 && #2 == 0, 1, #1^#2]) & But I wanted a general rule or pattern, so I do not have to write these checks, as the pure function can be more complicated (many # in it ) and I do not want to do many of these 'if then else' checks for each possible 0^0 that might show up. thanks Update: May be I should clarify more why I am doing this. I have a user selects a function from a menu. The function is a x^n0 + b y^n1 + c x^n2 y^n3 Where in the above, the parameters 'n0', 'n1', 'n2' and 'n3' also can be selected from sliders, and these can be zero. Now, 'x' and 'y' are coordinates, and these can be zero also. Therefore, it is possible that 0^0 can be encountered when evaluating the above function. There are many cases to check for, when doing it myself. For example 'y^n3' can be 0^0 and not the other, y^n1 can be 0^0 and not the other, x^n2 y^n3 can be both 0^0 and not the others, etc.., and so I have to define many different cases. (16 possible cases I think). And I am trying to avoid this. If I can tell Mathematica to replace 0^0 by 1 at a lower level, then life will be simpler. Update 12/7/11 Thanks for everyone's answers and comments, all are very useful and solve my problem and I learned from them. I selected Leonid answer as it allowed me to solve my problem with least amount of additional coding. Here is an small example Manipulate[Row[{format[x, n], "=", eval[x, n]}], {{x, 0.0, "x="}, 0, 1, .1, Appearance -> "Labeled"}, {{n, 0.0, "n="}, 0, 1, .1, Appearance -> "Labeled"}, Initialization :> ( format[x_, n_] := HoldForm["(" x ")"^n]; eval = Unevaluated[#1^#2] /. HoldPattern[0.0^0.0] :> 0.0 & ) ] I use real numbers everywhere in my code (it is a numerical pde solver), so that is why I used 0.0 in the above and not 0^0 to fit with what I am doing. A: You may try writing it like f = Quiet[Check[#1^#2,1]] &. Quiet will suppress the "Power::indet: "Indeterminate expression 0^0 encountered." message and Check will replace the result with 1 if it is indeterminate. It is probably better to use some function like s = Quiet[Check[#1, 1]] and wrap your expressions in it. A: I'm slightly surprised the trivial (albeit slightly dangerous) fix did not get mentioned earlier. If you really don't expect the expression 0^0 to come up in any context where you'd (a) be worried that it did, or (b) would like it to evaluate it to something other than 1, you can simply try Unprotect[Power]; Power[0, 0] = 1; Protect[Power]; 0^0 I needed this fix in a situation where a complicated function had a number of calls to expressions of the form x^n where x is real and n is an integer, in which case 0^0 should be seen as the limit of x^0=1 as x goes to 0. It's important to note, though, that doing this will 'contaminate' Power for the current kernel session, and may therefore break other notebooks which run concurrently and for which conditions (a) and (b) may not hold. Since Power is located in the System՝ context instead of Global՝, it may be difficult to separate the contexts of different notebooks to avoid clashes produced by this fix. A: Of course there are many ways to do things in Mathematica, but a design idiom I often use is to write the "function" (actually, a pattern) with decreasing specificity. Mathematica has the property that it will apply more specific patterns before less specific. So, for your case I'd just write: Clear[f]; f[0, 0] = 1; f[a_, b_] := a^b; I assume you expect to work with integer values since that's the usual context for this type of situation, e.g. when evaluating Bernstein basis functions. A: I agree with the answer of @Deep Yellow, but if you insist on a pure function, here is one way: f = Unevaluated[#1^#2] /. HoldPattern[0^0] :> 1 & EDIT Staying within the realm of pure functions, the situation you described in your edit can be addressed in the same way as my solution to your specific original example. You can automate this with a tiny bit of metaprogramming, defining the following function transformer: z2zProtect[Function[body_]] := Function[Unevaluated[body] /. HoldPattern[0^0] :> 1] Then, my previous code can be rewritten as: f = z2zProtect[#1^#2 &] But you can is this more generally, for example: ff = z2zProtect[#1^#2 + 2 #2^#3 + 3 #3^#4 &] In[26]:= ff[0,0,0,0] Out[26]= 6
{ "language": "en", "url": "https://stackoverflow.com/questions/8403626", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "10" }
Q: handling "No results" with Jquery Autocomplete Hey I'm trying to return a message when there are no results for the users current query! I have looked all over the net and there are similar scenarios, but I can't seem to get it working with my code below! Can anyone help me figure this out please, as I am pulling my hair out trying to fix it! I need to maintain the ability to use the keyboard to scroll down through the results. Thanks in advance. HTML <div id="search_box"> <form id="search_form" autocomplete="off" action="" onSubmit="return false;"> <input type="text" id="suggestSearchBox" value="Search by City or Hotel Name" onClick="this.value='';" /> </form> </div> Javascript NOTE: The remote data source is called "dataLocCodes", which is a javascript array // JavaScript Document $(function() { $("#suggestSearchBox").focus().autocomplete(dataLocCodes, { max: 15, selectFirst: true, matchContains: true, formatItem: function(row, i, max){ if (row.hotelId) { return row.accomName + ' - ' + row.city + ' - ' + row.country; } else { return row.city + ' - ' + row.country; } } }).result( function(event, row, formatted) { $("input#suggestSearchBox").val(row.city + ' - ' + row.country); var param = row.locparam; var encoded_url = param.replace(/ /gi,"+"); encoded_url = encoded_url.replace(/&/gi,"amp"); window.location.href = "hotels.html?location=" + encoded_url; }); }); A: There are a couple of ways to handle this. You can either create a source method so that if the results from the filter are empty, you add "no results" as a value, or you handle the response event to display a message that no results where returned in your ui. If using the source method, then add a select handler to prevent No Result from being a value. var availableTags = ['Abc', 'Def', 'ghi']; $('#noresults').autocomplete({ source: function (request, response) { var responses = $.ui.autocomplete.filter(availableTags, request.term); if (responses.length == 0) responses.push('No Result'); response(responses); }, response: function (event, ui) { if (ui.content.length == 0) { console.log('No results'); } }, select: function (event, ui) { // don't let no result get selected return (ui.item.value != 'No Result'); } });
{ "language": "en", "url": "https://stackoverflow.com/questions/13181557", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to keep a round imageView round using auto layout? How do I turn a rectangular image view into a circular image view that can hold shape in auto layout without setting width and height restraints? Thereby allowing the imageView to define it’s size, and size bigger and smaller relative to objects around it with leading, trailing, top, and bottom constraints. I asked a similar question the other day, but I think this might be posed in a more concise way. Thanks so much! EDIT Ok, I started over to make this as simple as possible. I have a view named "Cell" and a UIImageView named "dog" within the cell, and that's it. I don't have "unable to simultaneously satisfy constraints" in the console anymore, just two simple views using auto layout. I'm still trying to use this code to round the UIImageView: profileImageView.layer.cornerRadius = profileImageView.frame.size.width / 2 profileImageView.clipsToBounds = true Here is the cell constraint setup: Here is the profile pic constraint setup: Here is the result without the code, no rounding, but nice and square: Here is the result with the code to round: This makes no sense to me, because without the rounding code the image is square, and with the code it's diamond shaped. If it's square shouldn't it be a circle with no issues? EDIT 2 Here's what happens when I remove the bottom constraint and add a multiplier of .637 for equal height to superview. A: Unfortunately you cannot do this using cornerRadius and autolayout — the CGLayer is not affected by autolayout, so any change in the size of the view will not change the radius which has been set once causing, as you have noticed, the circle to lose its shape. You can create a custom subclass of UIImageView and override layoutSubviews in order to set the cornerRadius each time the bounds of the imageview change. EDIT An example might look something like this: class Foo: UIImageView { override func layoutSubviews() { super.layoutSubviews() let radius: CGFloat = self.bounds.size.width / 2.0 self.layer.cornerRadius = radius } } And obviously you would have to constrain the Foobar instance's width to be the same as the height (to maintain a circle). You would probably also want to set the Foobar instance's contentMode to UIViewContentMode.ScaleAspectFill so that it knows how to draw the image (this means that the image is likely to be cropped). A: First of all, I should mention that u can get a circle shape for your UIView/UIImageView only if the width and height will be equal. It's important to understand. In all other cases (when width != height), you won't get a circle shape because the initial shape of your UI instance was a rectangle. OK, with this so UIKit SDK provides for developers a mechanism to manipulate the UIview's layer instance to change somehow any of layer's parameters, including setting up a mask to replace the initial shape of UIView element with the custom one. Those instruments are IBDesignable/IBInspectable. The goal is to preview our custom views directly through Interface Builder. So using those keywords we can write our custom class, which will deal only with the single condition whether we need to round corners for our UI element or not. For example, let's create the class extended from the UIImageView. @IBDesignable class UIRoundedImageView: UIImageView { @IBInspectable var isRoundedCorners: Bool = false { didSet { setNeedsLayout() } } override func layoutSubviews() { super.layoutSubviews() if isRoundedCorners { let shapeLayer = CAShapeLayer() shapeLayer.path = UIBezierPath(ovalIn: CGRect(x: bounds.origin.x, y: bounds.origin.y, width: bounds.width, height: bounds.height )).cgPath layer.mask = shapeLayer } else { layer.mask = nil } } } After setting the class name for your UIImageView element (where the dog picture is), in your storyboard, you will get a new option, appeared in the Attributes Inspector menu (details at the screenshot). The final result should be like this one. A: Setting radius in viewWillLayoutSubviews will solve the problem override func viewWillLayoutSubviews() { super.viewWillLayoutSubviews() profileImageView.layer.cornerRadius = profileImageView.frame.height / 2.0 } A: It seems when you add one view as a subview of another that netted view will not necessarily have the same height as its superview. That's what the problem seems like. The solution is to not add your imageView as a subview, but have it on top of your backgroundView. In the image below I'm using a UILabel as my backgroundView. Also in your case, when you're setting the cornerRadius use this: let radius: CGFloat = self.bounds.size.height / 2.0. A: create new interface in your .h file like @interface CornerClip : UIImageView @end and implementation in .m file like @implementation cornerClip -(void)layoutSubviews { [super layoutSubviews]; CGFloat radius = self.bounds.size.width / 2.0; self.layer.cornerRadius = radius; } @end now just give class as "CornerClip" to your imageview. 100% working... Enjoy A: With my hacky solution you'll get smooth corner radius animation alongside frame size change. Let's say you have ViewSubclass : UIView. It should contain the following code: class ViewSubclass: UIView { var animationDuration : TimeInterval? let imageView = UIImageView() //some imageView setup code override func layoutSubviews() { super.layoutSubviews() if let duration = animationDuration { let anim = CABasicAnimation(keyPath: "cornerRadius") anim.fromValue = self.imageView.cornerRadius let radius = self.imageView.frame.size.width / 2 anim.toValue = radius anim.duration = duration self.imageView.layer.cornerRadius = radius self.imageView.layer.add(anim, forKey: "cornerRadius") } else { imageView.cornerRadius = imageView.frame.size.width / 2 } animationDuration = nil } } An then you'll have to do this: let duration = 0.4 //For example instanceOfViewSubclass.animationDuration = duration UIView.animate(withDuration: duration, animations: { //Your animation instanceOfViewSubclass.layoutIfNeeded() }) It's not beautiful, and might not work for complex multi-animations, but does answer the question. A: Swift 4+ clean solution based on omaralbeik's answer import UIKit extension UIImageView { func setRounded(borderWidth: CGFloat = 0.0, borderColor: UIColor = UIColor.clear) { layer.cornerRadius = frame.width / 2 layer.masksToBounds = true layer.borderWidth = borderWidth layer.borderColor = borderColor.cgColor } } Sample usage in UIViewController 1.Simply rounded UIImageView override func viewWillLayoutSubviews() { super.viewWillLayoutSubviews() imageView.setRounded() } 2.Rounded UIImageView with border width and color override func viewWillLayoutSubviews() { super.viewWillLayoutSubviews() imageView.setRounded(borderWidth: 1.0, borderColor: UIColor.red) } A: write this code override viewDidLayoutSubViews() { profileImageView.layer.cornerRadius = profileImageView.frame.size.width / 2 profileImageView.clipsToBounds = true } in this case it will called after calculating the autolayout calculations in the first code you called the cornerradius code before calculating the actual size of the view cuz it's dynamically calculated using aspect ratio , the actual corner radius is calculated before equaling the width and the height of the view A: I have same problem, and Now I get what happened here, hope some ideas can help you: there are something different between the tows: * *your profileImageView in storyboard *your profileImageView in viewDidLoad the size of bound and frame is different when viewDidLoad and in storyboard,just because view is resize for different device size. You can try it print(profileImageView.bounds.size) in viewDidLoad and viewDidAppear you will find the size in viewDidLoad you set cornerRadius is not the real "running" size. a tips for you: you can use a subClass of ImageView to avoid it, or do not use it in storyboard, A: If you have subclassed the UIImageView. Then just add this piece of magical code in it. Written in : Swift 3 override func layoutSubviews() { super.layoutSubviews() if self.isCircular! { self.layer.cornerRadius = self.bounds.size.width * 0.50 } } A: I am quite new to iOS native development, but I had the same problem and found a solution. So the green background has this constraints: backgroundView.translatesAutoresizingMaskIntoConstraints = false backgroundView.topAnchor.constraint(equalTo: superview!.safeAreaLayoutGuide.topAnchor).isActive = true backgroundView.leftAnchor.constraint(equalTo: superview!.leftAnchor).isActive = true backgroundView.widthAnchor.constraint(equalTo: superview!.widthAnchor).isActive = true backgroundView.heightAnchor.constraint(equalTo: superview!.heightAnchor, multiplier: 0.2).isActive = true The image constraints: avatar.translatesAutoresizingMaskIntoConstraints = false avatar.heightAnchor.constraint(equalTo: backgroundView.heightAnchor, multiplier: 0.8).isActive = true avatar.widthAnchor.constraint(equalTo: backgroundView.heightAnchor, multiplier: 0.8).isActive = true avatar.centerYAnchor.constraint(equalTo: backgroundView.centerYAnchor, constant: 0).isActive = true avatar.leadingAnchor.constraint(equalTo: backgroundView.leadingAnchor, constant: 20).isActive = true on viewWillLayoutSubviews() method I set the corner radius to avatar.layer.cornerRadius = (self.frame.height * 0.2 * 0.8) / 2 Basically, I am simply calculating the height of the image and then divide it by 2. 0.2 is the backgroungView height constraint multiplier and 0.8 the image width/height constraint multiplier. A: Solution: Crop the image [imageView setImage:[[imageView image] imageWithRoundedCorners:imageView.image.size.width/2]]; imageView.contentMode = UIViewContentModeScaleAspectFill; I was looking for the same solution for profile pictures. After some hit and try and going through available functions, I came across something which works and is a nice way to ensure its safe. You can use the following function to crop out a round image from the original image and then you need not worry about the corner radius. Post this even if your view size changes the image remains round and looks good. A: Can be easily done by creating an IBOutlet for the constraint which needs to be changed at runtime. Below is the code: * *Create a IBOutlet for the constraint that needs to be changed at run time. @IBOutlet var widthConstraint: NSLayoutConstraint! *Add below code in viewDidLoad(): self.widthConstraint.constant = imageWidthConstraintConstant() Below function determines for device types change the width constraint accordingly. func imageWidthConstraintConstant() -> CGFloat { switch(self.screenWidth()) { case 375: return 100 case 414: return 120 case 320: return 77 default: return 77 } } A: Add a 1:1 aspect ratio constraint to the imageView for it to remain circular, despite any height or width changes. A: I added custom IBInspectable cornerRadiusPercent, so you can do it without any code. class RoundButton: UIButton { override var bounds: CGRect { didSet { updateCornerRadius() } } //private var cornerRadiusWatcher : CornerRadiusPercent? @IBInspectable var cornerRadiusPercent: CGFloat = 0 { didSet { updateCornerRadius() } } func updateCornerRadius() { layer.cornerRadius = bounds.height * cornerRadiusPercent } }
{ "language": "en", "url": "https://stackoverflow.com/questions/32362934", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "49" }
Q: Using Array(Tuple(LowCardinality(String), Int32)) in ClickHouse I have a table CREATE TABLE table ( id Int32, values Array(Tuple(LowCardinality(String), Int32)), date Date ) ENGINE MergeTree() PARTITION BY toYYYYMM(date) ORDER BY (id, date) but when executing the request SELECT count(*) FROM table WHERE (arrayExists(x -> ((x.1) = toLowCardinality('pattern')), values) = 1) I get an error Code: 49. DB::Exception: Received from clickhouse:9000. DB::Exception: Cannot capture column 3 because it has incompatible type: got String, but LowCardinality(String) is expected.. If I replace the column 'values' values Array(Tuple(String, Int32)) then the request is executed without errors. What could be the problem when using Array(Tuple(LowCardinality(String), Int32))? A: Until it will be fixed (see bug 7815), can be used this workaround: SELECT uniqExact((id, date)) AS count FROM table ARRAY JOIN values WHERE values.1 = 'pattern' For the case when there are more than one Array-columns can be used this way: SELECT uniqExact((id, date)) AS count FROM ( SELECT id, date, arrayJoin(values) AS v, arrayJoin(values2) AS v2 FROM table WHERE v.1 = 'pattern' AND v2.1 = 'pattern2' ) A: values Array(Tuple(LowCardinality(String), Int32)), Do not use Tuple. It brings only cons. It's still *2 files on the disk. It gives twice slowdown then you extract only one tuple element https://gist.github.com/den-crane/f20a2dce94a2926a1e7cfec7cdd12f6d valuesS Array(LowCardinality(String)), valuesI Array(Int32)
{ "language": "en", "url": "https://stackoverflow.com/questions/60768819", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: I want the view to remain static but the content to re-orient within the view I am making a view with several subviews for iPad. I want all the positioning and sizing of the subviews to stay the same when rotating the iPad, but the content inside the subviews to re-orient. Does anyone know how to do this? A: It sounds like you still need to layout the views depending on the orientation. However, you're portrait and landscape frames would have different proportions on the screen. An Example of how you might layout a view: int h = 300; int w = 100; int space = 50; CGRect frame; if( interfaceOrientation == UIInterfaceOrientationPortrait ) { frame = CGRectMake( space, space, w, h ); } else if( interfaceOrientation == UIInterfaceOrientationPortraitUpsideDown ) { frame = CGRectMake( self.view.bounds.size.width - w - space, self.view.bounds.size.height- h - space, w, h ); } else if( interfaceOrientation == UIInterfaceOrientationLandscapeRight ) { frame = CGRectMake( space, self.view.bounds.size.height- w - space, h , w ); } else if( interfaceOrientation == UIInterfaceOrientationLandscapeLeft ) { frame = CGRectMake( self.view.bounds.size.width - h - space, space, h, w ); } self.label.frame = frame;
{ "language": "en", "url": "https://stackoverflow.com/questions/6024399", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Performance Issues in Celery I already read other posts about that but none of them solve my problem. I have function to scan all ports for a given ip. It takes 5-10 seconds to complete without celery but if I use the celery to run this function, it takes approximately 15 minutes. I observed that function without celery, consuming approximately %90 cpu power but with celery this value is %2-%3 so task takes 15 minutes to finish. This causes a serious performance problem for me. How to increase a cpu power for a specific task or any idea to solve this problem? @app.task def port_scan(ip): ##requires nmap 7.70 if (regex(ip)==True): ##If ip is valid try: nm = nmap.PortScanner() result_1 = nm.scan(ip,arguments="-p 1-65535 -T5") #Just for test output = ({"Name":result_1["scan"][ip]["tcp"]}) # print(output) return output #It will return with the output that needed except KeyError: return None
{ "language": "en", "url": "https://stackoverflow.com/questions/57902529", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Input validation using PHP and Jquery Ajax I want to validate an user input with ajax. It is the first time I use Ajax and I got stuck. If the input is correct I still get an error message and I don't know why. I get as an error 'Subtax error in the jquery file'. What do I do wrong? Thank you in advance. HTML: <form method="POST" action="<?php echo $_SERVER['PHP_SELF']; ?>"> <div class="form-group"> <label for="inputName">Your name</label> <input type="text" name="inputName" class="form-control" id="inputName" placeholder="Name"> </div> <div class="form-group"> <label for="inputEmail">Your e-mail</label> <input type="text" name="inputEmail" class="form-control" id="inputEmail" placeholder="E-mail"> </div> <div class="form-group"> <label for="inputMess">Your message for us</label> <textarea name="inputMess" class="form-control" id="inputMess"></textarea> </div> <button type="submit" name="send" class="btn btn-default">Send</button> </form> <div id='mess'></div> PHP: <?php sleep(1); $mail_reg = '/^(?i)(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9] {1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/'; $return = array(); $mesaj = ''; if ($_SERVER['REQUEST_METHOD'] === 'POST') { if (empty($_POST['inputName']) || is_numeric($_POST['inputName'])) { $mesaj = "Please enter your name!"; $return['error'] = true; $return['msg'] = 'oops'.$mesaj; echo json_encode($return); exit(); } elseif (empty($_POST['inputEmail']) || !preg_match($mail_reg, $_POST['inputEmail'])) { $mesaj = "Please enter your e-mail!"; $return['error'] = true; $return['msg'] = 'oops'.$mesaj; echo json_encode($return); exit(); } elseif (empty($_POST['inputMess'])) { $mesaj = "Please tell us something"; $return['error'] = true; $return['msg'] = 'oops'.$mesaj; echo json_encode($return); exit(); } else { $return['error'] = false; $return['msg'] = 'Thank you for getting in touch. We will contact you!'; echo json_encode($return); exit(); } } ?> JavaScript: $(document).ready(function() { var email_reg = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/i; $('form').submit(function(event) { event.preventDefault(); if ($('#inputName').val() == '' || $('#inputName').val().length < 2 || !isNaN($('#inputName').val())) { alert('Please enter your name'); } else if (!email_reg.test($('#inputEmail').val())) { alert('Please enter a valid e-mail adress'); } else if ($('#inputMess').val() == '' || !isNaN($('#inputMess').val())) { alert('Please tell us something'); } else { var formData = $('form').serialize(); submitForm(formData); } }) function submitForm(formData) { $.ajax({ type: 'POST', url: $('form').action, data: formData, dataType: 'json', cache: false, timeout: 7000, success: function(data) { $('#mess').text(data.msg); }, error: function(XMLHttpRequest, textStatus, errorThrown) { $('#mess').text('A communication error occured'); }, complete: function(XMLHttpRequest, status) { //$('form')[0].reset(); } }) } }) A: There might be some problem with your jquery file inclusion. Your code is working absolutely fine with me. I tried your code by saving it in a new php file as follows. <?php sleep(1); $mail_reg = '/^(?i)(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9] {1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/'; $return = array(); $mesaj = ''; if ($_SERVER['REQUEST_METHOD'] === 'POST') { if (empty($_POST['inputName']) || is_numeric($_POST['inputName'])) { $mesaj = "Please enter your name!"; $return['error'] = true; $return['msg'] = 'oops'.$mesaj; echo json_encode($return); exit(); } elseif (empty($_POST['inputEmail']) || !preg_match($mail_reg, $_POST['inputEmail'])) { $mesaj = "Please enter your e-mail!"; $return['error'] = true; $return['msg'] = 'oops'.$mesaj; echo json_encode($return); exit(); } elseif (empty($_POST['inputMess'])) { $mesaj = "Please tell us something"; $return['error'] = true; $return['msg'] = 'oops'.$mesaj; echo json_encode($return); exit(); } else { $return['error'] = false; $return['msg'] = 'Thank you for getting in touch. We will contact you!'; echo json_encode($return); exit(); } } ?> <html> <head> <script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> </head> <body> <form method="POST" action="<?php echo $_SERVER['PHP_SELF']; ?>"> <div class="form-group"> <label for="inputName">Your name</label> <input type="text" name="inputName" class="form-control" id="inputName" placeholder="Name"> </div> <div class="form-group"> <label for="inputEmail">Your e-mail</label> <input type="text" name="inputEmail" class="form-control" id="inputEmail" placeholder="E-mail"> </div> <div class="form-group"> <label for="inputMess">Your message for us</label> <textarea name="inputMess" class="form-control" id="inputMess"></textarea> </div> <button type="submit" name="send" class="btn btn-default">Send</button> </form> <div id='mess'></div> <script> $(document).ready(function() { var email_reg = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/i; $('form').submit(function(event) { event.preventDefault(); if ($('#inputName').val() == '' || $('#inputName').val().length < 2 || !isNaN($('#inputName').val())) { alert('Please enter your name'); } else if (!email_reg.test($('#inputEmail').val())) { alert('Please enter a valid e-mail adress'); } else if ($('#inputMess').val() == '' || !isNaN($('#inputMess').val())) { alert('Please tell us something'); } else { var formData = $('form').serialize(); submitForm(formData); } }) function submitForm(formData) { $.ajax({ type: 'POST', url: $('form').action, data: formData, dataType: 'json', cache: false, timeout: 7000, success: function(data) { $('#mess').text(data.msg); }, error: function(XMLHttpRequest, textStatus, errorThrown) { $('#mess').text('A communication error occured'); }, complete: function(XMLHttpRequest, status) { //$('form')[0].reset(); } }) } }) </script> </body> </html> Output: A: Try add header('Content-Type: application/x-javascript'); in php before outputing the json string.
{ "language": "en", "url": "https://stackoverflow.com/questions/25885685", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: ORA-22992 / ORA-06502+ORA-06512 errors I'm using this part of code in large one : SELECT DISTINCT P.SKU, SUBSTR(X.ATTRIBUTENAME, 14, 3) ATTRIBUTECODE, X.ATTRIBUTEVALUE FROM PRODUCT@ISPSTAG2 P, XMLTABLE('/attrs/attr' PASSING XMLTYPE(REGEXP_REPLACE(P.ATTRIBUTES_DE_AT, '<attr name="longDescription">.*?<\/attr>')) COLUMNS ATTRIBUTENAME VARCHAR2(50) PATH '@name', ATTRIBUTEVALUE VARCHAR2(4000) PATH '/string' ) X WHERE X.ATTRIBUTENAME LIKE 'Z_CA%' AND DN(DOMAINID) = 'AT' AND SKU NOT LIKE 'OFF_%' AND SKU NOT LIKE 'PDT%' AND ATTRIBUTES_DE_AT IS NOT NULL; And it throws an ORA-22992 error. I've made some research and a tip can to use the dual SELECT DISTINCT P.SKU, SUBSTR(X.ATTRIBUTENAME, 14, 3) ATTRIBUTECODE, X.ATTRIBUTEVALUE FROM PRODUCT@ISPSTAG2 P, XMLTABLE('/attrs/attr' PASSING XMLTYPE(REGEXP_REPLACE(P.ATTRIBUTES_DE_AT, '<attr name="longDescription">.*?<\/attr>')) COLUMNS ATTRIBUTENAME VARCHAR2(50) PATH '@name', ATTRIBUTEVALUE VARCHAR2(4000) PATH '/string' ) X WHERE X.ATTRIBUTENAME LIKE 'Z_CA%' AND DN(DOMAINID) = 'AT' AND SKU NOT LIKE 'OFF_%' AND SKU NOT LIKE 'PDT%' AND (SELECT ATTRIBUTES_DE_AT FROM DUAL) IS NOT NULL; But now I get ORA-06502/ORA-06512 errors : ORA-06502: PL/SQL : erreur numérique ou erreur sur une valeur ORA-06512: à "SYS.XMLTYPE", ligne 272 ORA-06512: à ligne 1 06502. 00000 - "PL/SQL: numeric or value error%s" *Cause: An arithmetic, numeric, string, conversion, or constraint error occurred. For example, this error occurs if an attempt is made to assign the value NULL to a variable declared NOT NULL, or if an attempt is made to assign an integer larger than 99 to a variable declared NUMBER(2). *Action: Change the data, how it is manipulated, or how it is declared so that values do not violate constraints. But, I executed the first one on ISPSTAG2 and it works, but the second one on ISPSTAG2 returns me the same ORA-06502/ORA-06512 errors so the issue is with the dual subquery. I also tried to create a view on ISPSTAG2 using DBMS_LOB.SUBSTR with 4000 characters but same error. Any ideas ? Thank you. A: If forgot to use the (SELECT ATTRIBUTES_DE_AT FROM DUAL) subquery inside the XMLTYPE... SELECT DISTINCT P.SKU, SUBSTR(X.ATTRIBUTENAME, 14, 3) ATTRIBUTECODE, X.ATTRIBUTEVALUE FROM PRODUCT@ISPSTAG2 P, XMLTABLE('/attrs/attr' PASSING XMLTYPE(REGEXP_REPLACE(**(SELECT ATTRIBUTES_DE_AT FROM DUAL)**, '<attr name="longDescription">.*?<\/attr>')) COLUMNS ATTRIBUTENAME VARCHAR2(50) PATH '@name', ATTRIBUTEVALUE VARCHAR2(4000) PATH '/string' ) X WHERE X.ATTRIBUTENAME LIKE 'Z_CA%' AND DN(DOMAINID) = 'AT' AND SKU NOT LIKE 'OFF_%' AND SKU NOT LIKE 'PDT%' AND (SELECT ATTRIBUTES_DE_AT FROM DUAL) IS NOT NULL; The thing I don't understand is that when don't use the subquery in the IS NOT NULL filter I have the the ORA-22992 error (using distant LOB), so why I have a different error not using the dual subquery, which is the same distant LOB ? Anyway for you for your time/help :)
{ "language": "en", "url": "https://stackoverflow.com/questions/58862055", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Why Azure app service restarts when swapping slots? After having this issue in production for a long time, and having read anything i can find about (such as this or this or that), i made a simple test. * *Create an empty asp.net website *in Application_Start, send an email or message (i've used PushBullet) to you so you know when the app starts *Create a new app service plan and resource group *Create the website on Azure and publish it *Create a staging deployment slot *Swap staging/production *Publish the website again so both slots have the same version of the website So i have an empty website, no connectionstring, no slot setting : When i click swap, I will get notifications that slots restart (at least once each). Why is this happening ? UPDATE: After studying Mohit's answer, i need some more clarifications. * *We send the notification in the Application_Start method, which is triggered by the AppInit event if i understand correctly. *I do not understand the behavior you explain. The order seems very important to ensure no downtime, yet you say it's not necessarily in that order. Why is it required to restart the app domain for the production slot ? Why would users get annoyed that the site is down (it should not) ? *What is the "new swap" feature ? What's the difference with the "old swap" ? For my tests, i just swapped using the portal. *You mention the "new swap" pauses before swap. I suppose it just means it waits for the applicationInitialization to complete (eg HTTP 200 on /) ? *I've done some more testing since yesterday. In the Application_Start method, i've added some Thread.Sleep to make app startups longer. However, when i swap i see no downtime on either staging or production. Shouldn't i experience downtimes on staging, at least for the duration of my app startup ? Does this mean the slot that is warmed up then swapped with production is in fact another temporary slot that is neither staging nor prod ? A: I have very similar problem, app is restarted after swapping to production slot and that causes unwanted downtime. After a lot of searching I found the following: In some cases after the swap the web app in the production slot may restart later without any action taken by the app owner. This usually happens when the underlying storage infrastructure of Azure App Service undergoes some changes. When that happens the application will restart on all VMs at the same time which may result in a cold start and a high latency of the HTTP requests. While you cannot control the underlying storage events you can minimize the effect they have on your app in the production slot. Set this app setting on every slot of the app: WEBSITE_ADD_SITENAME_BINDINGS_IN_APPHOST_CONFIG: setting this to “1” will prevent web app’s worker process and app domain from recycling when the App Service’s storage infrastructure gets reconfigured. You can find the whole Ruslany post, that I found very helpful here
{ "language": "en", "url": "https://stackoverflow.com/questions/55479062", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: inquirer package, present questions based on previous answers I'm using NPM 'inquirer' package in order to present the user various questions. One of them is a 'choices' selection. Is there a way to present follow up questions based on the 'choices' selection? Here's my code: const { prompt } = require('inquirer'); require('colors'); const questions = [ { type: 'input', name: 'appName', message: 'Enter application name:' }, { type: 'input', name: 'appDescription', message: 'Enter app description:' }, { type: 'input', name: 'appAuthor', message: 'Enter app author:' }, { type: 'checkbox', name: 'plugins', message: 'Select plugins to install:', choices: [ { name: 'Cassandra' } ] } ]; module.exports.performQuestions = async () => { console.log('\nWelcome to Chef!\n'.underline.italic.cyan); const answers = await prompt(questions); if (!answers.appName) { console.error('\nPlease provide app name!\n'.red); process.exit(1); } answers.appType = 'service'; return answers; }; Here I want to present a few more questions if the user selects 'Cassandra' is that possible? Thanks. A: You can use "when" and like in the example bellow, the second question will popup only if "Cassandra" is selected: const QUESTIONS = [ { name: 'your-name', type: 'list', message: 'Your name:', choices: ['Batman', 'Superman', 'Ultron', 'Cassandra'], }, { name: 'hello-cassandra', type: 'confirm', message: 'Oh, hello Cassandra!', when: (answers) => answers['your-name'] === 'Cassandra', }, ]; inquirer.prompt(QUESTIONS) .then(answers => { console.log(answers); });
{ "language": "en", "url": "https://stackoverflow.com/questions/54909019", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to access an application using different host and port with JBoss 5 I have deployed my application in Jboss and I want to give users access to my application with different host and ports per user. To explain clearly: http://192.168.11.21/MBeanProject/servcount for user1 and http://192.168.11.22/MBeanProject/servcount for user2 so on... How could I do this? I am using JBoss5 as my AS. Based on the user request I need to count the number of times that user1 accessed the first url and the number of times the user2 accessed the second one ...and so on... Can you guide me how could I procced? Currently I am working with the Snmp traps using JBoss5 A: You will need a separate IP address for every user, right? Which doesn't sound like a very scalable solution, but if you do decide to do this you will then need as many IP addresses as you have users, and tell JBoss to listen to all interfaces using a startup argument like bin/run.sh -b 0.0.0.0. Then, your Servlets will be able to tell the full IP address by checking (eg) HttpServletRequest#getRequestUrl(). Or, you could have a separate instance of JBoss running for each user, binding each one to a different IP. However, this is a very unusual design. It offers poor scalability, difficult maintenance, difficult network config and sysadmin tasks, and confusion for any new devs on the project. Appservers are designed to be able to serve multiple users on the same instance. I can't really see any positives to a design like this. Unless you have very good reasons for doing so (in which case please share!) you should probably use different URLs for different users, like: http://192.168.11.21/MBeanProject/user1/servcount http://192.168.11.21/MBeanProject/user2/servcount or http://192.168.11.21/MBeanProject/servcount?user=user1 http://192.168.11.21/MBeanProject/servcount?user=user2
{ "language": "en", "url": "https://stackoverflow.com/questions/5167427", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Python 2.7 : UnicodeDecodeError when I use character point with import socket connect I work with python under windows. I have this error "UnicodeDecodeError: 'utf8' codec can't decode byte 0x92" when I excecute this simple code : import socket s=socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((controlAddr, 9051)) controlAddr is "127.0.0.1" and I know that it is the character '.' which cause the problem so I tried different conversion but each time, I have the same error. I tried these different ways: * *controlAddr = u'127.0.0.1' *controlAddr = unicode('127.0.0.1') *controlAddr.encode('utf-8') *controlAddr = u'127'+unichr(ord('\x2e'))+u'0'+unichr(ord('\x2e'))+'0'+unichr(ord('\x2e'))+u'1' I added # -*- coding: utf-8 -*- at the begining of the main file and socket.py file. ... I still have the same error A: The error message says you have a byte 0x92 in your file somewhere, which is not valid in utf-8, but in other encodings it may be, for example: >>> b'\x92'.decode('windows-1252') '`' That means that your file encoding is not utf-8, but probably windows-1252, and problematic character is the backtick, not the dot, even if that character is found only in a comment. So either change your file encoding to utf-8 in your editor, or the encoding line to # -*- coding: windows-1252 -*- The error message doesn't mention the file the interpreter choked on, but it may be your "main" file, not socket.py. Also, don't name your file socket.py, that will shadow the builtin socket module and lead to further errors. Setting an encoding line only affects that one file, you need to do this for every file, only setting it in your "main" file would not be enough. A: Your error says 'utf8' codec can't decode byte 0x92". In the Windows codepage 1252, this character maps to U+2019 the right quotation mark ’. It is likely that the editor you use for your Python script is configured to replace the single quote ('\x27' or ') by the right quotation mark. It may be nicer for text, but is terrible in source code. You must fix it in your editor, or use another editor. A: Thank you ! Indeed, this character doesn't exist in utf-8. However, I didn't send the character "`", corresponding to 0x92 with windows-1252 and to nothing in utf-8. Futhermore this error appears when a character "." is in controlAddr and it is the same hexadecimal code for both encoding, i.e, 0x2e. The complete error message is given above : Traceback (most recent call last): File "C:\Python27\Lib\site-packages\spyderlib\widgets\externalshell\pythonshell.py", line 566, in write_error self.shell.write_error(self.get_stderr()) File "C:\Python27\Lib\site-packages\spyderlib\widgets\externalshell\baseshell.py", line 272, in get_stderr return self.transcode(qba) File "C:\Python27\Lib\site-packages\spyderlib\widgets\externalshell\baseshell.py", line 258, in transcode return to_text_string(qba.data(), 'utf8') File "C:\Python27\Lib\site-packages\spyderlib\py3compat.py", line 134, in to_text_string return unicode(obj, encoding) File "C:\Python27\Lib\encodings\utf_8.py", line 16, in decode return codecs.utf_8_decode(input, errors, True) UnicodeDecodeError: 'utf8' codec can't decode byte 0x92 in position 736: invalid start byte For this code : controlPort = 9051 controlAddr = unicode("127.0.0.1") import socket s=socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((controlAddr, controlPort))
{ "language": "en", "url": "https://stackoverflow.com/questions/41856598", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Set the selected value of two dropdownlists simultaneously using jQuery How to set the selected value of a dropdownlist to the selected value of another? The below code shows how to accomplish this correctly. ASPX <asp:DropDownList ID="ddl1" RunAt="Server" DataValueField="ID" DataTextField="ID" AppendDataBoundItems="true"/> <asp:DropDownList ID="ddl2" RunAt="Server" DataValueField="ID" DataTextField="TEXT" AppendDataBoundItems="true"/> JQUERY $("#<%= ddl1.ClientID %>").change(function() { var Code = $(this).val(); $("#<%= ddl2.ClientID %>").val(Code); }); When using jQuery Mobile, however the DataTextField is rendered as a span tag which the above code does not update. QUESTION How to amend the above code to accommodate for this? http://jsfiddle.net/E28WW/ A: Store the value from first selectmenu, then look for it in the second one. Select it using .prop('selected', true); and then call .selectmenu('refresh'). Demo $(document).on('pageinit', function () { $(document).on('change', '#ddl1', function () { var selected = $(this).val(); $('#ddl2 option[value="' + selected + '"]').prop('selected', true); $('#ddl2').selectmenu('refresh'); }); }); I used pageinit which is equivalent to .ready(). It is a special event for jQM. A: Have you checked that the change function is actually being called. Is the script you provide the entire contents of the script tag? The function will not be bound to the event until it is loaded, using the $(document).ready(); will bind the event to the control. $(document).ready(function() { $("#<%= ddl1.ClientID %>").change(function() { var Code = $(this).val(); $("#<%= ddl2.ClientID %>").val(Code); }); });
{ "language": "en", "url": "https://stackoverflow.com/questions/19177852", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Postman Response download is NOT pretty in Atom and other editors While using Postman and Sending and Downloading a Request, I have saved the JSON locally and when opening in Atom, Notepad++ and other editors, the Postman JSON is not parsed. I've tried changing LF in Atom and it doesn't seem to do anything. See below which shows (on the right pane) a pretty pane that parses nicely from a different project. I don't see any settings in Postman to change nor is there an option to change when downloading. Any ideas?
{ "language": "en", "url": "https://stackoverflow.com/questions/53128857", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Display a delivery day range based on shipping country in Woocommerce In Woocommerce, I'm trying to add an estimated delivery day range on cart and checkout pages. I have set 2 shipping Zones: Germany and other European countries (outside Germany) called "DHL Europe". I need to display a different delivery day range for Germany shipping country than other European shipping countries: * *Germany shipping country will display "Lieferzeit 3-5 Werktage" (and when there is no shipping costs). *Other European shipping countries will display "Lieferzeit 5-7 Werktage" My code attempt: function sv_shipping_method_estimate_label( $label, $method ) { $label .= '<br /><small class="subtotal-tax">'; switch ( $method->method_id ) { case 'flat_rate': $label .= 'Lieferzeit 3-5 Werktage'; break; case 'free_shipping': $label .= 'Lieferzeit 3-5 Werktage'; break; case 'international_delivery': $label .= 'Lieferzeit 5-7 Werktage'; } $label .= '</small>'; return $label; } add_filter( 'woocommerce_cart_shipping_method_full_label', 'sv_shipping_method_estimate_label', 10, 2 ); It works with the free_shipping and flat_rate shipping methods, but not for European deliveries (outside Germany). What am I doing wrong? How to display the correct date range for European countries (outside Germany)? A: You don't really need to target your shipping methods, but instead customer shipping country: add_filter( 'woocommerce_cart_shipping_method_full_label', 'cart_shipping_method_full_label_filter', 10, 2 ); function cart_shipping_method_full_label_filter( $label, $method ) { // The targeted country code $targeted_country_code = 'DE'; if( WC()->customer->get_shipping_country() !== $targeted_country_code ){ $days_range = '5-7'; // International } else { $days_range = '3-5'; // Germany } return $label . '<br /><small class="subtotal-tax">' . sprintf( __("Lieferzeit %s Werktage"), $days_range ) . '</small>'; } Code goes on function.php file of your active child theme (or active theme). Tested and works.
{ "language": "en", "url": "https://stackoverflow.com/questions/55287041", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Display notifications on a particular time I would like to display notification on a particular time and daily routine (i.e at 8'o clock morning). I am using broadcast receiver, alarmmanager to display notifications. But the problem is, I am not getting the notifications displayed on mobile. I've added wake lock permissions in manifest file also. Help me please Thank you MainActivity.java public class MainActivity extends ActionBarActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Calendar calendar = Calendar.getInstance(); calendar.set(Calendar.HOUR_OF_DAY, 8); calendar.set(Calendar.MINUTE, 00); calendar.set(Calendar.SECOND, 0); Intent notificationmassage = new Intent(getApplicationContext(),NotificationClass.class); //This is alarm manager PendingIntent pi = PendingIntent.getService(this, 0 , notificationmassage, PendingIntent.FLAG_UPDATE_CURRENT); AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE); am.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pi); Toast.makeText(this, "Start Alarm", Toast.LENGTH_LONG).show(); } NotificationClass.java public class NotificationClass extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { // TODO Auto-generated method stub PendingIntent contentIntent = PendingIntent.getActivity(context, 0, new Intent(context, MainActivity.class), 0); NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context) .setSmallIcon(R.drawable.ic_launcher) .setContentTitle("Text1") .setContentText("Text2 "); mBuilder.setContentIntent(contentIntent); mBuilder.setDefaults(Notification.DEFAULT_SOUND); mBuilder.setAutoCancel(true); NotificationManager mNotificationManager ; mNotificationManager= (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE); mNotificationManager.notify(1,mBuilder.build()); } } manifest: <uses-sdk android:minSdkVersion="8" android:targetSdkVersion="21" /> <uses-permission android:name="android.permission.WAKE_LOCK"/> <application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity android:name=".MainActivity" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <receiver android:name=".NotificationClass"> </receiver> </application> UPDATE: - now the issues was when ever I open the Application notification arises. For Ex: Alarm Set to 8.AM, whenever I open the app after 8 AM,the notification arises..even though the current time is > 8 AM. How to solve that? A: In your activity Replace following PendingIntent pi = PendingIntent.getService(this, 0, notificationmassage, PendingIntent.FLAG_UPDATE_CURRENT); with PendingIntent pi = PendingIntent.getBroadcast(this, 0, notificationmassage, PendingIntent.FLAG_UPDATE_CURRENT); A: public void getNotification(Context context,String Message){ int icon = R.drawable.appicon; int when =(int) System.currentTimeMillis(); NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); Notification notification = new Notification(icon, Message, when); String title = context.getString(R.string.app_name); Intent notificationIntent = new Intent(context, MainActivity.class); // set intent so it does not start a new activity notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP |Intent.FLAG_ACTIVITY_CLEAR_TASK); PendingIntent intent =PendingIntent.getActivity(context, 0, notificationIntent, 0); notification.setLatestEventInfo(context, title,Message, intent); notification.flags |= Notification.FLAG_AUTO_CANCEL; // Play default notification sound notification.defaults |= Notification.DEFAULT_SOUND; // Vibrate if vibrate is enabled notification.defaults |= Notification.DEFAULT_VIBRATE; notificationManager.notify(0, notification); }
{ "language": "en", "url": "https://stackoverflow.com/questions/31555310", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Show records of a particular year in one page <?php $hostname = "localhost"; $user = "root"; $password = ""; $dbname = "abcd"; $conn = new mysqli($hostname, $user, $password, $dbname); $sql="SELECT YEAR(date) as year from events GROUP BY year"; $row2 = mysqli_fetch_array(mysqli_query($conn,$sql)); $result2 = $conn->query($sql); $eyear=$row2['year']; $year="2017"; for ($counter = 1; $counter <=5; $counter++){ echo'<p><a href="'.$eyear.'">'.$year.'</a></p>'; $year--; } ?> I want to retrieve records of separate years and display results for a particular year in one page
{ "language": "en", "url": "https://stackoverflow.com/questions/50771734", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Failing data insert in php mysql I need to add records into the table 'writings'. As you can see in the code below, the failure leds to the message data insert failed. I've already tried to change everything that online forums adviced but it didnt help. All the program outputs is data insert failed and thats all. When I tried to add mysql_errno, it gave error code 0, which,as I remember, means that operation was successful. The main code: <?php include 'dbcon.php'; $Title=$_GET['Title']; $TaskID=$_GET['TaskID']; $uid=$_GET['uid']; $Text=$_GET['Text']; $Date=$_GET['Date']; $result=mysqli_query($MySQLiconn,"insert into 'writings'(uid,TaskID,Date,Text,Title, comment) values('$uid','$TaskID','$Date','$Text','$Title','')"); if ($result) { echo "Successfully added.<br>"; } else { echo "Data insert failed <br><br>"; } The file DBcon <?php $DB_host = "localhost"; $DB_user = "root"; $DB_pass = ""; $DB_name = "web"; $MySQLiconn = new MySQLi($DB_host,$DB_user,$DB_pass,$DB_name); if($MySQLiconn->connect_errno) { die("ERROR : -> ".$MySQLiconn->connect_error); } A: Try this: $sql = "INSERT INTO writings (uid, TaskID, Date, Text, Title, comment) VALUES ('$uid','$TaskID','$Date','$Text','$Title','')"; $result = mysql_query( $sql, $MySQLiconn ); if(! $result ) { die('Could not enter data: ' . mysql_error()); } echo "Entered data successfully\n";
{ "language": "en", "url": "https://stackoverflow.com/questions/43773309", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Tracker.autorun not working inside componentDidMount of react Tracker.autorun not working inside componentDidMount of react when I specify the projection (fields) for output. But the same works when I dont have any projection on mongo query. This works: Meteor.subscribe('quotes'); this.quotesTracker = Tracker.autorun(() => { const quotes = Quotes.find( {instrument_token: 12374274}, { sort: {timestamp: 1}, limit: 5000 } ).fetch(); This doesnt work Meteor.subscribe('quotes'); this.quotesTracker =Tracker.autorun(() => { const quotes = Quotes.find( {instrument_token: 12374274}, { fields: { last_price: 1, timestamp: 1, }, sort: {timestamp: 1}, limit: 5000 } ).fetch(); What am I missing here? A: I don't think Meteor's tracker works well with ReactJS, as their mechanism of re-render is different. You might want to use this package. https://github.com/meteor/react-packages/tree/devel/packages/react-meteor-data You can use it like so. import { Meteor } from 'meteor/meteor'; import { mount } from 'react-mounter'; import { withTracker } from 'meteor/react-meteor-data'; import { IndexPage } from "./index-page"; FlowRouter.route('/', { action: () => { mount(IndexPageContainer, {}); } }); export const IndexPageContainer = withTracker(() => { Meteor.subscribe('whatever'); return { Meteor: { collection: { whatever: Whatever.find().fetch() }, user: Meteor.user(), userId: Meteor.userId(), status: Meteor.status(), loggingIn: Meteor.loggingIn() } }; })(IndexPage); Where IndexPage is your actual component. You can then access the db by this.props.Meteor.collection.whatever.find()
{ "language": "en", "url": "https://stackoverflow.com/questions/50933897", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Running PHP - when using a node instance and port I'm running an application using nodejs and it's listening on port 8000, so my web url bar is ip:8000. I have an ajax call to a php file: $.ajax({ url: './chat/store.php', type: 'post', data: {message: message}, error: function () { console.log('Store not working...'); } but the php won't run because were running inside the node instance, so is there anything I can do to so that php runs while accessing the ip:8000 url? A: Simple way: You could call the CMD version of php from inside node and return the value via node. Hard way
{ "language": "en", "url": "https://stackoverflow.com/questions/34003082", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Accessing MJPEG Stream .net core I am trying to access a mjpeg stream through my .net core app. It seems AForge.Video is not compatible with .net core. Is there any lib / coding example available how to access a video stream and get single images out of it? Is there any possibility to get Aforge running with .NET core? private MJPEGStream stream = null; public void initRecorder(RecorderUnit unit) { stream = new MJPEGStream(unit.getAdress()); stream.NewFrame += stream_newFrame; stream.VideoSourceError += stream_error; } private void stream_newFrame(object sender, NewFrameEventArgs eventArgs) { Bitmap bmp = (Bitmap)eventArgs.Frame.Clone(); } private void stream_error(object sender, VideoSourceErrorEventArgs eventArgs) { } A: I've had good success using FFmpeg wrappers in C# in times gone by. Here is one that I've used: https://github.com/Ruslan-B/FFmpeg.AutoGen . It takes some work to master the FFmpeg compilation process, which is typically done via cross-compile from Linux, and is typically a necessary part of this. It also takes some work to understand the FFmpeg API. There are a lot of options and steps to extracting frames, and some difficulties in making it performant, especially the display of the extract frames. This project won't be as easy as you were hoping; however, you will have the full FFmpeg power at your fingertips when done.
{ "language": "en", "url": "https://stackoverflow.com/questions/61139263", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Using python loop to change part of variable name within function (e.g. inserting different number at end) Updated question in Edit II I am running a regression model. For that model, I want to test a large set of values in one specific part of the function and then run the model and all following functions. E.g. alpha = ['1', '2', '3'] for a in alpha: oddsvar = 'odds_all' + a result = 'result_all' + a norm_odds = 'norm_odds' + a pos_norm_odds = 'pos_norm_odds' + a oddsvar = mba263.odds_ratios(result)['Odds ratios'] norm_odds = numpy.power(oddsvar, std_all) pos_norm_odds = norm_odds pos_norm_odds[pos_norm_odds<1]=1/pos_norm_odds[pos_norm_odds<1] pos_norm_odds.sort_values(ascending=False) print(pos_norm_odds) When I first define oddsvar (and the other variables) they just contain a string. I want that string to be used in the rest of the function to either be a variable name or pull data from a different part of my code. For alpha = 1 the handwritten code would look like this: odds_all1 = mba263.odds_ratios(result_all1)['Odds ratios'] norm_odds_all1 = numpy.power(odds_all1, std_all) pos_norm_odds_all1=norm_odds_all1 pos_norm_odds_all1[pos_norm_odds_all1<1]=1/pos_norm_odds_all1[pos_norm_odds_all1<1] pos_norm_odds_all1.sort_values(ascending=False) I have been trying (and searching) but so far couldn't find a solution that works for me. Edit: Rewording my question: I am trying to define a name in the first half by making oddsvar = 'odds_all' + a -->> result should be e.g. odds_all1 Then I want to use the new name "odds_all1" and have it be the result of the equation on the right. What I can't figure out in the code is, how to have oddsvar = mba263.odds_ratios(result)['Odds ratios'] ... translated to ... odds_all1 = mba263.odds_ratios(result_all1)['Odds ratios'] So that after the function has run, I can call the variable "odds_all1" and it gives me the whole list of odds for my logistic regression with alpha = 1. I see that I can solve the first half with a dictionary (thanks @Teh), however, that approach doesn't seem to work for the argument within the function. Edit II: alpha= ['1', '2', '3'] for a in alpha: d = {} #odds_all dict e = {a: 'result_all' + a} #result_all dict f = {} #norm_odds dict g = {} #pos_norm_odds dict d['odds_all' + a] = mba263.odds_ratios(e[a])['Odds ratios'] f['norm_odds' + a] = numpy.power(d['odds_all' + a], std_all) g['pos_norm_odds' + a] = e['norm_odds' + a] g['pos_norm_odds' + a][g['pos_norm_odds' + a]<1]=1/g['pos_norm_odds' + a][g['pos_norm_odds' + a]<1] g['pos_norm_odds' + a].sort_values(ascending=False) print(g) Thank you for the help so far. With the dict approach I was able to solve the left side of the equation. However, the "mba263.odds_ratios(e[a])" still yields an error (AttributeError: 'str' object has no attribute 'params'). I have "result_all1" defined as a variable name elsewhere, but combining result_all and the alpha can only be done as a string. Can I switch it back from being a string to being a name within the dict? A: This is just a guess on my part, but I found the exec() to run a command, and you might look that up. You could probably build a string with "global {}" or set it to a throw away value and fill in your built name, and then run the string with exec([stringname]). Here's just a test I ran from the command prompt in python. myval = "test1" mystr = "global " + myval exec(mystr) print(mystr) global test1 print(type("test1")) <class 'str'> Hope this helps you. Good luck with your program! Did you try something like this after your first setting lines? temp_str = "global " + oddsvar exec(temp_str) Again, I'm just guessing. I hope you can get this to work like you need. For the other set of values, you might try building a string, and then using the exec on that. Something like this temp_str = oddsvar + "mba263.odds_ratios(result)['Odds ratios']" exec(temp_str)
{ "language": "en", "url": "https://stackoverflow.com/questions/67030801", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: OpenCV Assertion Failed with SolvePnP I'm trying to use solvePnP in a C++ program that detects a chessboard in a video stream. Every time the calibration finishes, I try to run solvePnP, but I keep getting errors that I think are related to the translation and rotation vectors. This is the error: The error This is my code: #include <cstdio> #include <cstdlib> #include <string> #include <iostream> #include <fstream> #include <opencv2/core/core.hpp> #include <opencv2/imgproc/imgproc.hpp> #include <opencv2/calib3d/calib3d.hpp> #include <opencv2/highgui/highgui.hpp> using namespace cv; using namespace std; //Global variables vector<vector<Point2f> > corner_list; vector<vector<Point3f> > point_list; vector<Mat> rotation_vecs, translation_vecs; int i = 0; bool calibMode = true, drawMode = false, drawMode2 = false, camMatrixInit = false, calibrated = false; Mat originalCameraMatrix, cameraMatrix, distCoefficients, frame, gray, rvec, tvec; //Function declarations vector<Point3f> genWorldPoints(int cols, int rows); void printCameraMatrix(); void printDistCoeff(); void printRotVecs(); /*Generates the world points (0, 0, 0), (1, 0, 0), etc. for the camera calibration.*/ vector<Point3f> genWorldPoints(int cols, int rows){ vector<Point3f> ret; for (int i=0; i<rows; i++) { for (int j=0; j<cols; j++) { int tempi = i*(-1); ret.push_back(Point3f((float)j, (float)tempi, 0.0)); } } return ret; } /*Print the camera matrix*/ void printCameraMatrix(){ cout << "Original Camera Matrix" << endl << originalCameraMatrix << endl; cout << "Current Camera Matrix" << endl << cameraMatrix << endl; } /*Prints the distortion coefficients*/ void printDistCoeff(){ cout << "Distortion Coefficients:"<< endl << distCoefficients << endl; } int main(int argc, char *argv[]){ VideoCapture *capdev; cameraMatrix = Mat::eye(3, 3, CV_64F); distCoefficients = Mat::zeros(8, 1, CV_64F); // open the video device capdev = new VideoCapture(0); if (!capdev->isOpened()) { printf("Unable to open video device\n"); return(-1); } namedWindow("Video", 1); bool found; *capdev >> frame; rvec = Mat::zeros(3, 1, CV_64F); tvec = Mat::zeros(3, 1, CV_64F); //Initialize camera matrix cameraMatrix.at<double>(0,2) = (frame.size().width)/2; cameraMatrix.at<double>(1,2) = (frame.size().height)/2; cameraMatrix.copyTo(originalCameraMatrix); printCameraMatrix(); for(;;){ *capdev >> frame; if (!found) { imshow("Video", frame); } Size patternsize(9,6); vector<Point2f> corner_set; vector<Point3f> point_set; int code = waitKey(10); cvtColor(frame, gray, CV_BGR2GRAY); found = findChessboardCorners(gray, patternsize, corner_set, CV_CALIB_CB_ADAPTIVE_THRESH | CV_CALIB_CB_FILTER_QUADS); //Code to add a calibration frame if (found && calibMode) { cornerSubPix(gray, corner_set, Size(11, 11), Size(-1, -1), TermCriteria(CV_TERMCRIT_EPS + CV_TERMCRIT_ITER, 30, 0.1)); drawChessboardCorners(frame, patternsize, Mat(corner_set), found); //s key press if (code == 115){ printf("Adding calibration frame\n"); printf("Number of corners found: %lu\n", corner_set.size()); printf("Point 0 x: %f\ty: %f\n", corner_set[0].x, corner_set[1].y); //Add the corner set corner_list.push_back(corner_set); //Generate point set vector<Point3f> point_set = genWorldPoints(9,6); //Add point set to point set list point_list.push_back(point_set); //Save the image string filename = "../data/images/p4_calib_image_"+to_string(i)+".jpeg"; imwrite(filename, frame); //if there are more than 5 saved calibration images, run calibration procedure if (i>4) { //Calculate the reprojection error by running calibrateCamera double rpe = calibrateCamera(point_list, corner_list, frame.size(), cameraMatrix, distCoefficients, rotation_vecs, translation_vecs, CV_CALIB_FIX_ASPECT_RATIO | CV_CALIB_FIX_K4); //Print the camera matrix printCameraMatrix(); printDistCoeff(); //Print the reprojection error cout << "Reprojection error: " << rpe << endl; calibrated = true; } //Increment i i++; } imshow("Video", frame); } else if (found && drawMode){ cout << "Draw mode" << endl; bool solved = solvePnP(point_list, corner_list, cameraMatrix, distCoefficients, rvec, tvec); //rotation_vecs.front(), translation_vecs.front()); } else if (found && drawMode2){ cout << "Draw mode 2" << endl; bool solved = solvePnP(point_list, corner_list, cameraMatrix, distCoefficients, rvec, tvec); //rotation_vecs.front(), translation_vecs.front()); } //Switching between drawing modes if (calibrated && code == 49) { calibMode = false; drawMode2 = false; drawMode = true; } else if (calibrated && code == 50){ calibMode = false; drawMode = false; drawMode2 = true; } //Switch back to calibration mode else if (calibrated && code == 51){ drawMode = false; drawMode2 = false; calibMode = true; } if (code == 27) { printf("Terminating\n"); delete capdev; return(0); } } capdev = new VideoCapture(0); printf("Terminating\n"); delete capdev; return(0); } Please excuse the indentation... A: The problem is that sovlePnP requires vector<Point2/3f> as input, instead of vector<vector<Point2/3f> >. In your code, "point_list" is vector<vector<Point3f> >, and "corner_list" is vector<vector<Point2f> >. The documentation of solvePnP can be found here: http://docs.opencv.org/3.0-beta/modules/calib3d/doc/camera_calibration_and_3d_reconstruction.html
{ "language": "en", "url": "https://stackoverflow.com/questions/36815605", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Convert React Components into web Components Want to convert existing react components into isolated web components in which we share data using props and custom events and also theme(styling) was set according to the props we share . Like if we share theme=light , web Component theme should be default and same is done for dark theme. I tried many way but not find the correct one.
{ "language": "en", "url": "https://stackoverflow.com/questions/74570843", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Looking for any way to transfer file from PPC to PC i looking for any way to transfer file from PPC to PC - and from PC to PPC , i dont want to use WebService, and if i use RAPI i need that in the PC will be any program - and i dont want (i dont want that in the PC will be any of my program) how i can do it ? thank's in advance A: You're going to need to be more specific -- the way the question is now it's basically impossible to determine what you're after. Do you need to transfer a file from a Windows Mobile handheld to a Windows PC? Over what type of connection (are they on the same 802.11 network) ? You need more details or no one will be able to even attempt to help you. A: So, if what I gather is correct, you want to plug a device with your app on it into a PC and then be able to push files to the PC from the device without having to install anything over on the PC. Is that correct? If so, the next question is are you insane? It's not possible, and for very good reason. You don't see any potential security problems with being able to just plug a device into a PC and push files up to the PC without the user having to explicitly have installed something to receive that data? I could write a simple attack app that would fill up the PC's hard drive in about 5 minutes. A: A vanilla version of this is to just use the Active Sync synchronization folders. If you on the device save a file to the device synch folder, then Active Sync will move it over to the PC synch folder automatically.
{ "language": "en", "url": "https://stackoverflow.com/questions/1821318", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Pass local variable to create.js.erb for an iteration in an iteration I have a Post and a Comment model, while a post can have multiple comments and a comment belongs to a post (and a user). I am iterating through all Posts by doing @posts.each do |d|, which is not a big deal. Also i am iterating through all the comments of a Post by d.comments.each do |comment|. No big deal too. Ive setted up a create.js.erb to make my app a bit more dynamic and to instantly display the comment you created under a post. While my form is working fine, i have troubles setting up the create.js.erb which is giving me a NameError - undefined local variable or method 'comment' for #<Class:> Did you mean? @comment: when submitting the forms content. After reloading the page the comment is added up, but i would like to have an instant update like a single page app would behave. i have never worked with ajax before. I would be able to solve the whole situation if i would just display the comments on a separate posts#show view but since i am iterating through every post on the index page and want to display every comment of every post and also update the comments async i just cant figure out how to do that. How do I create the desired behavior? Sorry if my question is asked kinda wonky. comments_controller.rb def create @user = current_user @comment = Comment.new(comment_params) @comment.user_id = @user.id respond_to do |format| if @comment.save format.js {} format.html { redirect_to root_path, notice: 'Comment added' } format.json { render :show, status: :created, location: @comment } else format.html { redirect_to root_path } format.json { render json: @comment.errors, status: :unprocessable_entity } end end end posts/index.html.erb <% @posts.each do |d| %> <%= d.content %> <div class="comment-list"> <%= render partial: "comments/comment", collection: d.comments %> </div> <% end %> comments/_comment.html.erb <%# d.comments.reverse.each do |comment| %> <%= comment.content %> <%# end %> create.js.erb $(".comment-list").append("<%= j render partial: "comments/comment" %>"); A: $(".comment-list").append("<%= j render partial: "comments/comment" %>"); Replace above code with $(".comment-list").append("<%= j render partial: "comments/comment", locals: {comment: @comment} %>");
{ "language": "en", "url": "https://stackoverflow.com/questions/66907452", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }