text
stringlengths
70
452k
dataset
stringclasses
2 values
python crypto.sign not found, though it's in the module I'm trying to use some google api sample code, and it's not working. Admittedly, I'm green at python, but I've boiled it down to this simple test program: #!/usr/bin/python from OpenSSL import crypto print crypto.sign('key', 'xyzzy', 'sha256') which results in: Traceback (most recent call last): File "./ot", line 5, in <module> print crypto.sign('key', 'xyzzy', 'sha256') AttributeError: 'module' object has no attribute 'sign' When I look at the openssl crypto module (/usr/lib/python2.6/site-packages/OpenSSL/crypto.py), it does, in fact, have "sign" defined: def sign(self, pkey, digest): """ Sign the certificate request using the supplied key and digest so I'm very puzzled. As near as I can tell, there are no other versions laying around pip show pyopenssl --- Name: pyOpenSSL Version: 0.14 Location: /usr/lib/python2.6/site-packages Requires: cryptography, six Expanded output based on comments: openssl file: /usr/lib64/python2.6/site-packages/OpenSSL/__init__.pyc dir(crypto): ['Error', 'FILETYPE_ASN1', 'FILETYPE_PEM', 'FILETYPE_TEXT', 'NetscapeSPKI', 'NetscapeSPKIType', 'PKCS12', 'PKCS12Type', 'PKCS7Type', 'PKey', 'PKeyType', 'TYPE_DSA', 'TYPE_RSA', 'X509', 'X509Extension', 'X509ExtensionType', 'X509Name', 'X509NameType', 'X509Req', 'X509ReqType', 'X509StoreType', 'X509Type', 'X509_verify_cert_error_string', '_C_API', '__doc__', '__file__', '__name__', '__package__', '_exception_from_error_queue', 'dump_certificate', 'dump_certificate_request', 'dump_privatekey', 'load_certificate', 'load_certificate_request', 'load_pkcs12', 'load_pkcs7_data', 'load_privatekey'] crypto file /usr/lib64/python2.6/site-packages/OpenSSL/crypto.so crypto.sign: Traceback (most recent call last): File "./ot", line 16, in <module> print crypto.sign('key', 'xyzzy', 'sha256') AttributeError: 'module' object has no attribute 'sign' You may want to verify that the OpenSSL package you're importing from is the one you expect. Try import OpenSSL, then print OpenSSL.__file__ to find its location. According to the docs, the sign method was added in OpenSSL 0.11, so if you are getting an older version when you import, it may not have the function. What does print dir(crypto) output? I've added output showing openssl.file, dir(crypto) and crypto.file. If I read it right, somehow the crypto.so lib really is missing sign() and I should try rebuilding pyopenssl... For people not using openssl who have this problem (missing sign method) there is another solution. Check the import section on the top of your code, you need to have this import : from Crypto.Signature import PKCS1_v1_5 and not the Crypto.Cipher implementation: from Crypto.Cipher import PKCS1_v1_5 This class doesn't have the sign method: https://www.dlitz.net/software/pycrypto/api/2.6/Crypto.Cipher.PKCS1_v1_5.PKCS115_Cipher-class.html The Crypto.Signature PKCS1_v1_5 class has the sign method :https://www.dlitz.net/software/pycrypto/api/2.6/Crypto.Signature.PKCS1_v1_5.PKCS115_SigScheme-class.html I apparently had some conflicting installations - I removed a couple of yum python-crypto packages, then pip uninstalled openssl and there was still stuff in /usr/lib64/python2.6/site-packages/OpenSSL/ (including crypto.so), so I manually removed that directory and then pip installed pyopenssl and that solved the problem. Thanks for the pointers...
common-pile/stackexchange_filtered
Generate a dictionnary in a list So here's my problem, I have a list of characters generated randomly by a program. I would like for each of those characters to have feelings towards each others. Here is my code so far: import random # create characters class CHARACTER: def __init__(self, name, surname, age, sexe, pragmatism, courage, intelligence, shyness, happiness, fear, hunger, comfort, feeling): self.name = name self.surname = surname self.age = age self.sexe = sexe self.pragmatism = pragmatism self.courage = courage self.intelligence = intelligence self.shyness = shyness self.happiness = happiness self.fear = fear self.hunger = hunger self.comfort = comfort self.feeling = feeling characters = [] # list that will contain all the characters feelingslist = [] sexe = ["Male", "Female"] mname = ["John", "Mike", "Albert", "Henry", "Patrick", "Francis", "Robert", "Simon", "Charles", "Charlie", "Connor", "Adam", "Blake", "Steven", "Edward", "Andrew", "Joe", "Gregory", "Brian", "Anthony", "Frank", "Billy", "Boris", "Edgar", "Elliott", "Erik", "Liam", "Kyron", "Ned", "Neil", "Ricky", "Ross", "Rich", "Roy", "Preston", "William", "Vladimir", "Zach", "Wyatt", "Tylor", "Thomas", "Spike"] fname = ["Alessia", "Ally", "Bridgette", "Callie", "Jessica", "Debora", "Diana", "Elizabeth", "Clair", "Fran", "Hannah", "Helene", "Marie", "Laura", "Leslie", "Leyla", "Kiley", "Margaret", "Lola", "Maryjane", "Megan", "Rose", "Sofia", "Samantha", "Teresa", "Yolanda", "Teri", "Vicky", "Tricia", "Rose", "Rita", "Nita", "Paola", "Penelope", "Polly", "Nathalie", "Melody", "Morgane"] lname = ["Smith", "Johnson", "Williams", "Jones", "Brown", "Miller", "Moore", "Taylor", "Thomas", "White", "Harris", "Thompson", "Garcia", "Allen", "Lewis", "Hall", "Young", "Clark", "Hill", "Lopez", "Carter", "Turner", "Collins", "Evans", "Campbell", "Nelson", "Parker", "Green", "Black", "Green", "Lee", "Martin"] # the code below create 10 male and 10 female characters # and puts them in the characters list. for i in range(20): character = CHARACTER(random.choice(mname), random.choice(lname), random.randint(1,10), random.choice(sexe), random.randint(1,10), random.randint(1,10), random.randint(1,10), random.randint(1,10), random.randint(1,10), random.randint(1,10), random.randint(1,10), random.randint(1,10), {}) characters.append(character) i += 1 # assigning sexe to characters for character in characters: if character.sexe == "Female": character.name = random.choice(fname) # feelings for character in characters: for character in characters: character.feeling[id(character)] = 5 # for each character in characters: # add one feeling for each character # printing characters for character in characters: print character.name print character.surname print character.sexe print id(character) print character.feeling print " " Now my problem with this is that the program only adds one entry for each characters like this: Morgane Garcia Female 44880880 {44880880: 5} So each character has an entry in their "feeling dictionnary" for themselves but not for the other ones. I would like for each dictionnary to have one entry for every single other character in the program (so every character has an opinion about all the other ones) In your loop for setting feelings, you are using the same variable (character) to control both loops; they need to be different variables. For example: for char1 in characters: for char2 in characters: char1.feeling[id(char2)] = 5 Alright I finally solved this, just in case someone with the same problem reads that topic here is my solution: characters_len = len(characters) for character in characters: for i in range(characters_len): character.feeling[id(characters[i])] = 5 Thank you for your answers and putting me on the right path So I should do something like this: characters_len = len(characters) for character in characters: for i in range(characters_len): character.feeling[id(character)] = 5 i+=1 ? No: you are still using character to identify both who's feeling is being set and who that feeling is about. And don't change i explicitly; for is already taking care of that. Ok, I see what the problem is but I'm not sure how to fixe it...how would you code it so that the program understands that it has to loop through all the characters for each character?
common-pile/stackexchange_filtered
Multiplication of cardinal numbers Let $a_i$ be a cardinal number for every $i \in\ I$. Let $\{A_i\}$ and $\{A'_i\}$ be families of sets and let $A_i$, $A'_i$ and $a_i$ be equipotent for every $i \in I$. Then show that $\prod_i\ A_i $ is equipotent with $\prod_i\ A'_i $. This seems obviously true but I don't know how to actually show the bijection between them.. Hint: Since you are given that $A_i$ and $A_i!'$ are equipotent for each $i$, you can assume that you have a collection of bijections $f_i$, where $f_i$ is a bijection between $A_i$ and $A_i!'$. These are your raw materials. Your job is to figure out how to build the bijection for the product out of these raw materials. It really feels that you are afraid to try things on your own. You should know that without chewing a lot on problems and trying hard you will not learn how to do this on your own. I say that because you ask questions which often appear in a rather similar form on this site before, and you often accept the answer in minutes. This signals me that you haven't really tried to tackle the problem on your own before asking. Note that this is basically a reformulation of this question For each $i\in I$ you have a bijection $\varphi_i:A_i\to A'_i$. Define $$\varphi:\prod_{i\in I}A_i\to\prod_{i\in I}A'_i:\langle a_i:i\in I\rangle\mapsto\Big\langle\varphi_i(a_i):i\in I\Big\rangle$$ and prove that it’s a bijection. This is what I call a follow-your-nose proof: there really is only one reasonable thing to try. All you’re given is the equipotence of $A_i$ and $A'_i$ for $i\in I$. All that gives you is the existence of the bijections $\varphi_i$, so either the result is very hard (unlikely) or somehow it must be possible to use those bijections to get the one that you want. Since a typical element of $\prod_iA_i$ is just a function $\langle a_i:i\in I\rangle$ from $I$ to $\bigcup_iA_i$, about the only thing to try is to apply the bijections $\varphi_i$ to the components of $\langle a_i:i\in I\rangle$.
common-pile/stackexchange_filtered
React Native - Positioned absolute view is behind other components of the screen guys. So, I'm trying to make a simple Select Dropdown Menu with React Native. I've another code that works as well, but the problem is within the Position absolute. I've tried a lot of times but no success. The problem: The absolute View is behind others components of screen. Expected behavior: The absolute view above all components Can someone help me? This is my snack representation of this problem. https://snack.expo.dev/@ellyssonmiike/shallow-croissant Thank you all You can use react-native-portalize library for this problem. Portalize basically renders the content of Portal in Host component. Here is the snack with the Portalize implementation: https://snack.expo.dev/@truetiem/shallow-croissant First you need to install react-native-portalize: yarn add react-native-portalize Then wrap your app with Host component: import {Host} from 'react-native-portalize'; <Host> // your app content </Host> And wrap your dropdown list with Portal component: import {Portal} from 'react-native-portalize'; <Portal> <View style={[styles.dropdownMenu, { top: height }]}> // your dropdown content </View> </Portal> Thank you, works perfectly! you need just a little re-arrangement for your stylesheet as follows: const styles = StyleSheet.create({ container: { flex: 1, zIndex: 10 }, dropdownContainer: { position: 'absolute', top: Constants.statusBarHeight, zIndex:10, backgroundColor: '#ccc', width: '100%', elevation: 10, }, dropdownMenu: { flex:1 } }); You can also remove {{top: height}} for Item style. I don't see any need for it.
common-pile/stackexchange_filtered
mongodb: when using $all, the query execution time depends on the order of the input parameters I have a toy mongodb collection with the following structure { "operation" : { "type" : "STACK" }, "constraints" : [{ "partNumbers" : ["part", "part_1"] }] } I want to query the documents with the specified type and partNumbers, so I wrote this query db.getCollection('toy').find({ "operation.type" : "STACK", "constraints.partNumbers": {"$all": ["part_1", "part"]} }) and the index db.toy.ensureIndex( { "operation.type": 1, "constraints.partNumbers": 1, }) I created a dataset with some millions documents, with almost all of them having "part" in the partNumbers array The query is very fast (it takes 1 ms), but if I swap "part" and "part1", it takes forever (more than 2 seconds on my dataset). It looks like mongodb uses the index only on the first element that I pass in the "$all" function of the query. this is the result of explain() for the query that executes fast { "queryPlanner" : { "plannerVersion" : 1, "namespace" : "factorysim.robofacturingservice", "indexFilterSet" : false, "parsedQuery" : { "$and" : [ { "constraints" : { "$elemMatch" : { "$and" : [ { "partNumbers" : { "$size" : 2 } }, { "constraintType" : { "$eq" : "PART_NUMBER_CONSTRAINT" } }, { "partNumbers" : { "$eq" : "part_1" } }, { "partNumbers" : { "$eq" : "part" } } ] } } }, { "operation.type" : { "$eq" : "STACK" } } ] }, "winningPlan" : { "stage" : "FETCH", "filter" : { "constraints" : { "$elemMatch" : { "$and" : [ { "partNumbers" : { "$eq" : "part_1" } }, { "partNumbers" : { "$size" : 2 } }, { "constraintType" : { "$eq" : "PART_NUMBER_CONSTRAINT" } }, { "partNumbers" : { "$eq" : "part" } } ] } } }, "inputStage" : { "stage" : "IXSCAN", "keyPattern" : { "operation.type" : 1.0, "constraints.partNumbers" : 1.0 }, "indexName" : "operation.type_1_constraints.partNumbers_1", "isMultiKey" : true, "multiKeyPaths" : { "operation.type" : [], "constraints.partNumbers" : [ "constraints", "constraints.partNumbers" ] }, "isUnique" : false, "isSparse" : false, "isPartial" : false, "indexVersion" : 2, "direction" : "forward", "indexBounds" : { "operation.type" : [ "[\"STACK\", \"STACK\"]" ], "constraints.partNumbers" : [ "[\"part_1\", \"part_1\"]" ] } } }, "rejectedPlans" : [] }, "serverInfo" : { "host" : "p1", "port" : 27017, "version" : "3.6.8", "gitVersion" : "8e540c0b6db93ce994cc548f000900bdc740f80a" }, "ok" : 1.0 } and for the one that executes slow { "queryPlanner" : { "plannerVersion" : 1, "namespace" : "factorysim.robofacturingservice", "indexFilterSet" : false, "parsedQuery" : { "$and" : [ { "constraints" : { "$elemMatch" : { "$and" : [ { "partNumbers" : { "$size" : 2 } }, { "constraintType" : { "$eq" : "PART_NUMBER_CONSTRAINT" } }, { "partNumbers" : { "$eq" : "part" } }, { "partNumbers" : { "$eq" : "part_1" } } ] } } }, { "operation.type" : { "$eq" : "STACK" } } ] }, "winningPlan" : { "stage" : "FETCH", "filter" : { "constraints" : { "$elemMatch" : { "$and" : [ { "partNumbers" : { "$eq" : "part" } }, { "partNumbers" : { "$size" : 2 } }, { "constraintType" : { "$eq" : "PART_NUMBER_CONSTRAINT" } }, { "partNumbers" : { "$eq" : "part_1" } } ] } } }, "inputStage" : { "stage" : "IXSCAN", "keyPattern" : { "operation.type" : 1.0, "constraints.partNumbers" : 1.0 }, "indexName" : "operation.type_1_constraints.partNumbers_1", "isMultiKey" : true, "multiKeyPaths" : { "operation.type" : [], "constraints.partNumbers" : [ "constraints", "constraints.partNumbers" ] }, "isUnique" : false, "isSparse" : false, "isPartial" : false, "indexVersion" : 2, "direction" : "forward", "indexBounds" : { "operation.type" : [ "[\"STACK\", \"STACK\"]" ], "constraints.partNumbers" : [ "[\"part\", \"part\"]" ] } } }, "rejectedPlans" : [] }, "serverInfo" : { "host" : "p1", "port" : 27017, "version" : "3.6.8", "gitVersion" : "8e540c0b6db93ce994cc548f000900bdc740f80a" }, "ok" : 1.0 } Is there a way of writing a query/index combination that works independently from the order of the input parameters? Add explained query plans for both queries to the question. I've edited my question @D.SM Both query plans appear to be identical, therefore the assertion that the index usage depends on the order of the input array appears to be unsupported by evidence. Actually, if you look carefully there is a difference. The first plan says "constraints.partNumbers" : [ "["part_1", "part_1"]" ] and the second "constraints.partNumbers" : [ "["part", "part"]" ]. The query using the index to filter documents having "part_1" is faster because "part_1" is less frequent than "part" The same index is used in the same way. The fact that you are querying with different values doesn't affect index choice. OK, if your question is about your specific execution you also should provide sample data that reproduces the behavior you are seeing. And I don't see execution stats in your question, research what those are and add them.
common-pile/stackexchange_filtered
JavaFX How to have the program continue doing something until a button is clicked In my code I want to begin doing something when the user hits "start" and pause if the user hits "pause" and start up again once the user hits "play" The pause button changes text to read play. I'm having issues with stopping the program once it starts. The following is an extremely simplified version of my code, assuming all imports have been done: boolean play = true; Button pausebtn = new Button("Pause"); pausebtn.setOnAction( e -> { if(play == true) { pausebtn.setText("Play"); play = false; //pause the printing that the "Start" button began } else { pausebtn.setText("Pause"); play = true; } }); Button startbtn = new Button("Start"); startbtn.setOnAction( e -> { //start printing from 1 to integer max }); I know that the order of this code may need to be changed. But before I do that I want to just know exactly how I should go about doing this. My actual code of course is much more complicated but this is basically what I want to happen: have the program start one execution when the start button is pressed, and pause it once the pause button is pressed, and start again once the play button is pressed. Any help would be appreciated. It's not clear what the actual problem is. There seems to be nothing fundamentally wrong with the code you posted. Are you asking how to wait for play flag to become true ?
common-pile/stackexchange_filtered
How to create Botton that run clickevent on Another Botton in java? I have this code public class NewClass { private void btn_NumberONEMouseClicked(java.awt.event.MouseEvent evt) { } private void btn_NumberTOWMouseClicked(java.awt.event.MouseEvent evt) { } I have 2 Bottons ( Btn number One & Btn Number Tow ) I Want The First Botton will do click Event on the secound Botton How can I do it ?? Do not forget to validate my answer if it helped you Abdullah You have to use the doClick() method of the JButton class Here is the code : JButton but = new JButton(); JButton but2 = new JButton(); but.addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent e) { but2.doClick(); } }); but2.addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent e) { System.out.println("It works !"); } }); I did not use your variables because I didn't understand your methods. But this works perfectly.
common-pile/stackexchange_filtered
Automatic Oracle partitioning by month in the tablespace corresponding to the month I need to partition my table by month automatically and that each partition is in the tablespace corresponding to the month. I don't need the round robin way. I want each partition to be in its tablespace. Thanks I think because you have to use the round Robin way, because Oracle can automatically create partitions but Oracle cannot create automatically tablespaces. Thanks. I created the tablespaces for every month and I use store in, but I don't want the way round robin. I would like other way to match each tablespace with exact month partition As I already stated, you have to use round robin, because the tablespaces have to exist at desing time. Otherwise Oracle cannot create partitions automatically. Would be this: CREATE TABLE MY_TABLE ( START_TIME TIMESTAMP(0) NOT NULL, more columns ) PARTITION BY RANGE (START_TIME) INTERVAL (INTERVAL '1' MONTH) STORE IN ( TS_JAN, TS_FEB, TS_MAR, TS_APR, TS_MAY, TS_JUN, TS_JUL, TS_AUG, TS_SEP, TS_OKT, TS_NOV, TS_DEC ) ( PARTITION P_INITIAL VALUES LESS THAN (TIMESTAMP '2021-01-01 00:00:00') TABLESPACE TS_JAN ); Just ensure timestamp of the inital partition (e.g. 1st of January) matches the correct tablespace. Otherwise you have to create all partitions and tablespaces manually in advance. Yes, that example is the same I have in my DB, but I have the little problem that I wrote before. Thank you very much for your help.
common-pile/stackexchange_filtered
Set subdomain as environemt variable in htaccess I want to get the subdomain-string and set an environment variable in the htaccess file to that value: SetEnvIf Host TEST\.mywebsite\.lvh\.me MAGE_RUN_CODE=TEST This is working, but I would need to add such a line for every subdomain. I want this working for every subdomain. So if I visit test.mywebsite.lvh.me, MAGE_RUN_CODE should be set to test. If I visit subdomain2.mywebsite.lvh.me, MAGE_RUN_CODE should be set to subdomain2. Any help appreciated. http://www.visiospark.com/mod-rewrite-rule-generator/ Managed to solve it: SetEnvIf Host ^([^\.]*)\.mywebsite\.lvh\.me$ MAGE_RUN_CODE=$1 Here a little explaination: ^ starts the expression $ end the expression () This defines a group and is the tricky part. It stores the value in $1, more groups would store it in $2, $3...
common-pile/stackexchange_filtered
Should I use both HtmlEncode and JavaScriptStringEncode if inside HTML <script> tag to create HtmlString from string? My question is very similar to this one, but without the <% %> details. Let's say I have the following code: public static IHtmlString AddSomethingToWindow(string value) { var output = new StringBuilder(); output.AppendLine("<script type='text/javascript'>"); output.Append("window.something=\"" + value + "\";"); output.Append("</script>"); return new HtmlString(output.ToString()); } Let's say value is coming from an untrusted source & could be anything. To make RenderSomething method safe, do I need HttpUtility.HtmlEncode(HttpUtility.JavaScriptStringEncode(value)) or is just HttpUtility.JavaScriptStringEncode(value) sufficient? Or are both wrong? Simplest thing would be a JSON encoder, because valid JSON is valid JavaScript (and it's safe). encoding does not change anything in regards to some script security - script is script, and by encoding it, you do not change the security aspect here at all, just that funny characters such as spaces etc. can be correctly encoded. So, if you encode un-safe script, well, then you have some unsafe script. So, encoding really has little to do with security issues, only that of having some encoded script that will work. @AlbertD.Kallal I've updated the question to make it clearer. Please, take a look at edit history. The purpose here is to include value as part of a JS string, not include it as any JS code. @Pointy I upvoted the comment, but after thinking I think this is not correct. If the JSON has a string that has "", it'll cause issues, I think. "Let's say value is coming from an untrusted source & could be anything." <- then you shouldn't be injecting this as a script. @ControlAltDel I don't want to inject it as a script. I want to inject it as part of a JS string. E.g., window.something="really-dangerous-value";. Whatever really-dangerous-value is, I want my code to work correctly. @HossamEl-Deen re: "I don't want to..." then why in this string you are creating are you injecting this inside a script tag? @ControlAltDel The end-goal is to pass data from the view model in ASP.NET to JavaScript code. @HossamEl-Deen not correct: a proper JSON serializer always renders "/" as "/" @HossamEl-Deen Whatever your end goal, this introduces a huge vulnerability. In the business world you'd either need to find another (safer) way to achieve what you are doing or get rid of this functionality all together. Have you considered using a Wiki flavor? @Pointy I stand corrected. I hereby confirm what you've said, negating what I've said before, for future readers. In the spec, it's seemingly not a must, but spec possibly says it's optional & as you've said typical JSON serializers do it. So, for future readers: try out your serialization library & see. @ControlAltDel I'm not sure what you mean by Wiki flavor, but I generally agree with you that this is not ideal. However, there are other constraints in play, and according to my answer below it's possible to make it safe -- even if it's generally not recommended. I strongly believe, although I'm not 100% sure, that JavaScriptStringEncode is enough. (1) From HTML spec: The easiest and safest way to avoid the rather strange restrictions described in this section is to always escape an ASCII case-insensitive match for "<!--" as "\x3C!--", "<script" as "\x3Cscript", and "</script" as "\x3C/script"... (2) The core idea of this is supported by answers from other people 1 & 2, even though they may not be fully accurate or up to date with the spec comment above (from which the second linked answer is actually derived). (3) Looking at JavaScriptStringEncode, it seemingly replaces <, among other characters, which should satisfy (1). From these 3 points, I think one can conclude that calling JavaScriptStringEncode is enough, since the code inside script doesn't need to be HTML encoded, it just needs to escape <!--, <script, and </script (case-insensitively), which JavaScriptStringEncode by escaping < (replacing it with its Unicode sequence). This is true. The HTML parser will pay absolutely no attention to the content of the <script> tag other than to scan for "". Thus, HTML encoding is not necessary is there is no HTML parsing involved.
common-pile/stackexchange_filtered
How to get tooltip text from database from spring jdbc? How can I use JSP, JavaScript/jQuery and spring-jdbc to display tooltip text from database-mysql on mouseover. What did you try? You are going to want to preload the tooltip texts on page load so you don't have to send a request right when the user hovers over the element. first things first you are going to want to create a db table that contains the tooltip strings. next you are going to want to get the values from the DB using spring/jdbc. Here is a link describing how to do that. next you are going to want to set up a gateway that serves up the information found above, so that your front end can grab the tooltip strings. To make this happen you are most likely going to need a java class "tooltip," which you use to wrap the tooltip strings and send back when the tooltips endpoint has been hit next, in the front end you are going to want to process the tooltip string data you got back. If you are going to be reusing the same tooltip text for many elements then I would recommend giving each tooltip a name. You will want to use that name to store the tooltip text on the FE in a global location so that every page/component of your app will be able to access the tooltips. Now you have the tooltip text in the front end and you can add a html element help you display your tooltip. Here is a link for reference - How do I add a tool tip to a span element? Good luck!!
common-pile/stackexchange_filtered
Error: unexpected '}' in " in my code.Tried suggestions but I am still stuck I am new to R and trying to run some reports but keep getting the following error for this command. Command as follows: for (id in (df$ID)){ subgroup <- df[df$ID == id,] render("Feedback.rmd", output_dir = filepath, output_file = paste0(id, "_CMA1_22-23", ".doc"))} Error as follows: Error: unexpected '}' in " render("Feedback.rmd", output_dir = filepath, output_file = paste0(id, "_CMA1_22-23", ".doc"))}" I have tried substituting '.doc' for ".doc" having read answers to other similar posts. Other posts also mentioned the else command but since i haven't got that, it's moot. Are you maybe running only the line starting with render instead of the for loop? In RStudio (if that is what you are using) you could use source to run the code rather than run. Thanks, @tavdp - definitely running the full loop. Thanks, @John Coleman. Tried running source and it seemed to help. Identified a missing package which once installed seems to be running the output file. New error now but a step in the right direction!
common-pile/stackexchange_filtered
What is a time complexity for sets and maps created with a factory methods Set.of() and Map.of()? In Java, when I create a set with Set.of() or a map with Map.of() what is the time complexity of the contains and get operations? Is it O(1)? They are unmodifiable, you cannot add to a Set.of() returned Set. Source ok, what about get? using forEach() method. I ask about time complexity. If there is 10000 items in the Map, depending on the implementation, it can be O(1) or O(logN) The Set.of and Map.of APIs return instances of JDK-private implementations. The performance of these implementations is not guaranteed by the specification. However, the APIs do return specific implementations about which performance statements can be made. Thus, the question is reasonable and is distinct from a (hypothetical) question such as "What is the performance of Map.get?" which is a poor question because there are many different Map implementations. In any case, the implementations behind Set.of (for size greater than two) and Map.of (for size greater than one) use a simple open addressed hashing scheme with linear probing for collision resolution. The Set.contains and Map.get operations are O(1) if the elements' (keys') hashes are reasonably well distributed.
common-pile/stackexchange_filtered
Browser history in react-router Why I use browserHistory in my React app, it still serves up a page at localhost:3000, but when it gets deployed, I get an empty page with nothing in the console. When I switch to hashHistory, however, it runs fine on both localhost:3000 and on my site. Why is this happening? The below code doesn't work when I deploy it (uses browserHistory): import React from 'react'; import { Router, Route, IndexRoute, browserHistory } from 'react-router'; import App from './components/App'; import Home from './components/Home'; import Company from './components/Company'; const router = ( <MuiThemeProvider> <StyleRoot> <Router history={browserHistory}> <Route path="/" component={App}> <IndexRoute component={Home} /> <Route path="/company" component={Company} /> </Route> </Router> </StyleRoot> </MuiThemeProvider> ) ReactDOM.render( router, document.getElementById('root') ); I'm using v3.0 for react-router. Please specify which version of react-router you are using. First, which version of React Router are you using? In version 4, you need to create an instance of BrowserHistory instead of just passing the class. You are probably getting the blank page as the fall back page for a routing error. Check you browser's console for an error message. You should be getting a default route for http://localhost:3000/badurl, <Home> for http://localhost:3000 and <App> with <Company> as a this.props.children for http://localhost:3000/company. You can replace the blank page with a 404 page using <Route path="*" component={NotFoundPage} />. Please update the question with more information if none of these help. I'm using react-router version 3. I'm actually getting an error in the console now saying that resource can't be found. Something's up with my routing.
common-pile/stackexchange_filtered
Copy directory structure only at year end Happy New Year. I have a solution to this, but I can't make it work unless I am in the directory I want to copy. At the end of 2018, I want to copy the directory structure only of various folders named 2018/ into 2019/. cd 2018/ find . -type d -exec mkdir -p ../2019/{} \; And this works. How do I do it from the base directory? find 2018 -type d -exec basename {} \; gives me the folder names, but find 2018 -type d -exec mkdir 2019/`basename {}` \; still copies the 2018 folder into the 2019 folder, and you loose the directory tree. I can't find a simple answer after multiple searches. Any ideas? Edit Thanks for all the help and suggestions. This one ultimately worked best for me: find 2018/* -type d | sed 's/^2018//g' | xargs -I {} mkdir -p 2019"/{}" Take a look if this helps https://stackoverflow.com/questions/4073969/copy-folder-structure-sans-files-from-one-location-to-another Thanks @Paulo: that has the one line answer I'm looking for. https://stackoverflow.com/a/30646398/2709804 This like should do the trick: for FOLDER in `ls -l 2018/|grep '^d'|awk '{print $9}'`; do mkdir -p 2019/$FOLDER; done OR for FOLDER in `find 2018 -type d -exec basename {} \;|grep -v 2018`; do mkdir -p 2019/$FOLDER; done I hope this helps. The first version works; thanks. The second does not, as it collapses the tree structure, and puts all the subdirectories into 2019/. It's weird the second option didn't work as it works for me. Anyways I'm glad it worked for you. Please mask the answer as correct so it can help others. Why you shouldn't parse the output of ls. If you have mtree, you can do this: $ mkdir 2019 $ mtree -cdp 2018 | mtree -Up 2019 If you don't have mtree, here's how to install Archie Cobbs' mtree port from GitHub on Ubuntu 16.04.5 LTS: $ mkdir work; cd work $ # adjust this URL to match the desired version from the GitHub page $ wget https://s3.amazonaws.com/archie-public/mtree-port/mtree-1.0.4.tar.gz $ tar xf mtree-1.0.4.tar.gz $ cd mtree-1.0.4 $ cat README mtree - Utility for creating and verifying file hierarchies This is a port of the BSD mtree(1) utility. See INSTALL for installation instructions. See COPYING for license. See CHANGES for change history. Enjoy! $ cat INSTALL Simplified instructions: 1. Ensure you have the following software packages installed: libopenssl-devel 2. ./configure && make && sudo make install Please see https://github.com/archiecobbs/mtree-port for more information. $ # I already had openssl installed in my Ubuntu VM, so I forged ahead: $ ./configure ... $ make ... $ sudo make install $ man mtree ... $ which mtree /usr/bin/mtree I think the OpenSSL package name mentioned by the author may have changed since the instructions were created. On my system, libssl-dev was the package I needed to build mtree with SHA256 etc. support. HTH, Jim I can't see how to install mtree on ubuntu. @smilingfrog I located Archie Cobbs' GitHub project to port mtree to Linux, and updated my answer with instructions for installation on Ubuntu 16. Just: cd 2018/ find * -type d -exec mkdir -p ../2019/{} \; using the '*' instead of '.' will avoid selecting the 2018 directory itself. Without cd-ing to directory, I would get the directories list into an array and substitute the year in mkdir command. For example: # get list into an array, names can have spaces. IFS=$'\r\n' dirs=($(find /some/path/2018/* -type d)) let i=0 while [ $i -lt ${#dirs[*]} ]; do mkdir -p "${dirs[$i]/2018/2019}" let i=i+1 done +1 for find *; I didn't know that was an option. However, this does the same as my working script, and I am trying to figure out how to do it without changing into the directory. just added a way to achieve this.
common-pile/stackexchange_filtered
basic algebra inequalities it's been a while since I worked with inequalities. Im trying to figure out the steps taken to go from $p > n^{1/3}$ to $p/n < n^{2/3}$ I am assuming the first step they did, is take the inverse of $p$, so $p > n^{1/3} \Rightarrow p^{-1} < n^{1/3}$ then multiplied both sides by $n$. So $n/p < n^{2/3}$ Is this correct? I am just not sure if one could simply take an inverse of a number he pleases in an equation and reverse the inequalities. Thank you Thanks man, I should have checked for its truth before trying to figure it out. Really appreciate it! Ok I figured it out. Here is how its done $p > n^{1/3} \Rightarrow p^{-1} < n^{-1/3} \Rightarrow np^{-1} < nn^{-1/3} \Rightarrow n/p < n^{-1/3 + 1} = n^{2/3}$ You are correct but you made several typos that it appears everything you say is wrong. " Im trying to figure out the steps taken to go from $p>n^{1/3}$ to $p/n<n^{2/3}$" You meant (I assume) to type $\frac np < n^{\frac 23}$. $\frac pn < n^{\frac 23}$ is not a correct result. "I am assuming the first step they did, is take the inverse of p , so $p>n^{1/3}⇒p^{−1}<n^{1/3}$" I assume you meant to type $p^{-1} < n^{-\frac 13}$ and not $p^{-1} < n^{\frac 13}$. By coincidence the latter is true if $p > 1$ and $n > 1$ but it isn't true if $n < 1$. And the latter will not get you anywhere. "then multiplied both sides by n. So $n/p<n^{2/3}$" $n^{-\frac 13}*n = n^{-\frac 13 + 1} = n^{\frac 23}$ so this would be correct. However as you had incorrectly typed $n^{\frac 13}$, $n^{\frac 13}*n = n^{\frac 13 + 1} \ne n^{\frac 23}$ and so wouldn't be correct. But as $n^{\frac 13}$ wasn't correct in the first place, this is ultimately correct. So, yes, your reasoning was correct but you typos were all wrong. Thanks man, I figured that down and posted the solution below. Thank you for the explanation tho :) Nevermind I figured it out. For anyone who is curious $p>n^{1/3}⇒p^{−1}<n^{−1/3}⇒np−1<nn^{−1/3}⇒n/p<n^{−1/3+1}=n^{2/3}$
common-pile/stackexchange_filtered
Oracle APEX 5 Dynamic Action upon page load event does not work. What am i doing wrong? The program basically aims at retrieving some fields of a record and processing and displaying that on a textbox of static content region in apex 5 My database: LCD_MONItOR table Interface : PLSQL code that is supposed to execute on page load event. Declare lcd_id LCD_Monitor.LCD__NO%TYPE; tag LCD_Monitor.ASSET_TAG%TYPE; pp LCD_Monitor.PURCHASE_PRICE%TYPE; sal LCD_Monitor.SALVAGE%TYPE; ls LCD_Monitor.LIFE_SPAN%TYPE; accm LCD_Monitor.ACCUMULATED_DEP%TYPE; netbook Number; currDep Number; Begin select LCD__NO, ASSET_TAG, PURCHASE_PRICE,SALVAGE, LIFE_SPAN, ACCUMULATED_DEP into lcd_id, tag, pp, sal, ls, accm from LCD_MONITOR where LCD__No='40'; :LCD_NO:=lcd_id; :CURR_DEP:= (pp-sal)*(1/ls); :TOT_DEP:= (pp-sal)*(1/ls)+accm; :NBV:=pp-(pp-sal)*(1/ls)+accm; End; PS: I have returned the values to the textboxes in 'Affected Elements' Section in the properties. But when the page is loaded, no values appear in the textboxes. Any help would be appreciated. Not sure if its LCD__No or LCD_No. Check there is one additional _ Yes, its LCD__No (double underscore) What is the type of your dymanic action? Does user need to send any data to the server for computations? Its a page load event and about the data : No, it is retrieved from the database (LCD_MONITOR Table) What is the type of your True Action? True action with the type Execute PL/SQL Code hasn't property Affected Elements. Affected Elements is the property of the action with type Execute JavaScript Code. Obviously, that's not what you need. The True Action is Set value since I want to set value of the textboxes I changed the type to Execute PL/SQL Code, now one of the items' value appear whose value is not calculated but just assigned to the item. I think the problem lies here :LCD_NO:=lcd_id;:CURR_DEP:= (pp-sal)*(1/ls) :TOT_DEP:= (pp-sal)*(1/ls)+accm;:NBV:=pp-(pp-sal)*(1/ls)+accm; . Because the first assignment statement executes and displays and the rest dont. I'm not sure if I understood correctly what exactly are you doing. If you need just fill items with data, create a before header process (in Page Designer mode, it is in Pre-rendering -> Before Header. Write your code there, it should be enough. If you want to do it in Dynamic Action (I wouldn't recommend this way), you need to create a Dynamic Action with Event - Page Load, which will contain a True Action with properties: Action - Execute PL/SQL Code, PL/SQL Code - your code and Items to Return - LCD_NO,CURR_DEP,TOT_DEP,NBV But make sure your items really have such names, because by default APEX creates items with names like P10_LCD_NO, where 10 (for example) is a number of the page. No, Actually I intend to calculate depreciation from purchase price (table record) of LCD and then display it on the page item (textbox). And yes i have done the same way you are telling for dynamic action but it does not display any value Instead of directly assigning a calculated value to the textfields items, I assigned them to a variable first then assigned variables to the items i.e Before :CURR_DEP:= (pp-sal)*(1/ls); :TOT_DEP:= (pp-sal)*(1/ls)+accm; :NBV:=pp-(pp-sal)*(1/ls)+accm; Corrected currDep:= (pp-sal)*(1/ls); :CURR_DEP:= currDep; tot:= (pp-sal)*(1/ls)+accm; :TOT_DEP:=tot; netbook:=pp-((pp-sal)*(1/ls)+accm); :NBV:=netbook;
common-pile/stackexchange_filtered
Exportation of Access file table to Excel spreadsheet with VBA I am trying the following code to import data in an active worksheet using VBA, with an Access file as a source. The Access table to import is called "Table01", I have a error message when defining the query (Set daoQueryDef = daoDB.QueryDefs(Text)): "item not found in this collection". Do you know where is the problem? In the synthax? Sub Import() Dim daoDB As DAO.Database Dim daoQueryDef As DAO.QueryDef Dim daoRcd As DAO.Recordset Set daoDB = OpenDatabase("C:\Users\Desktop\Database\Database.mdb")> Text = "SELECT * FROM `Table01`" Set daoQueryDef = daoDB.QueryDefs(Text) Set daoRcd = daoQueryDef.OpenRecordset ThisWorkbook.Worksheets("Import").Range("A4").CopyFromRecordset daoRcd End Sub The issue is with the Set daoQueryDef = daoDB.QueryDefs(Text) line. There is no QueryDef already existing with a name equal to the value of Text. You need to use CreateQueryDef to define it. Set daoQueryDef = daoDB.CreateQueryDef("TempQueryDef", Text) Set daoRcd = daoQueryDef.OpenRecordset ThisWorkbook.Worksheets("Import").Range("A4").CopyFromRecordset daoRcd daoDB.QueryDefs.Delete dao.QueryDef.Name This method creates a new QueryDef with Text as its SQL string and opens it as a recordset, does the copy and then removes it from the QueryDefs collection at the end. See Microsoft's website for further examples, e.g. http://msdn.microsoft.com/en-us/library/office/ff194892.aspx EDIT (better): Using a temp QueryDef without needing to delete it afterwadrs (thanks Remou) Set daoQueryDef = daoDB.CreateQueryDef("", Text) Set daoRcd = daoQueryDef.OpenRecordset ThisWorkbook.Worksheets("Import").Range("A4").CopyFromRecordset daoRcd If you use an empty string for the querydef name, you can still work with the querydef, but it will not be saved. It's working, here's the working code: Sub Import() Dim daoDB As DAO.Database Dim daoQueryDef As DAO.QueryDef Dim daoRcd As DAO.Recordset Set daoDB = OpenDatabase("C:\Users\Desktop\Database\Database.mdb")> Text = "SELECT * FROM `Table01`" Set daoQueryDef = daoDB.CreateQueryDef("", Text) Set daoRcd = daoQueryDef.OpenRecordset ThisWorkbook.Worksheets("Import").Range("A4").CopyFromRecordset daoRcd End Sub
common-pile/stackexchange_filtered
How to track customer login? I want to track how many times customer logged in. So as output it will be like report. From this to this day X day logged in X times. You can create a separate module with separate database where you need to define a observer, in which you need to write how many times a customer logged in with time & date. <customer_login> <observers> <yourobservername> <type>model</type> <class>yourmodule/path_to_class</class> <method>customerLogin</method> </yourobservername> </observers> </customer_login> Your observer class would look like this: class YourCompany_YourModule_Model_Observer { public function customerLogin($observer) { $customer = $observer->getCustomer(); // ADD CURRENT SYSTEM DATE-TIME, CUSTOMER NAME, ID, ETC. IN THE DATABASE CREATED BY YOUR MODULE } } Thanks Rahul. Any free or paid plugin?. because i'm newbie to magento. Sorry, but didn't find any extension specifically for your need. Either you need to do the coding by yourself, or contact an experienced Magento developer.
common-pile/stackexchange_filtered
Opencsv : Not able to use the CsvToBeanFilter with CsvToBeanBuilder and annoted bean object I am not able to use the CsvToBeanFilter with CsvToBeanBuilder and annoted bean object. It gives "Caused by: java.lang.RuntimeException: java.lang.IllegalStateException: The header row hasn't been read yet." error. Here is my filter - private class AssetTypeFilter implements CsvToBeanFilter { private final MappingStrategy strategy; public AssetTypeFilter(MappingStrategy strategy) { this.strategy = strategy; } @Override public boolean allowLine(String[] line) { final int index = this.strategy.getColumnIndex("MF056"); final String value = line[index]; final boolean result = "CRDT".equals(value); return result; } } Here is my bean - @ToString @Data public class DsbISINCsv { @CsvBindByName(column = "ID", required = false) private String sourceId; @CsvBindByName(column = "MF056", required = false) private String assetClass; @CsvBindByName(column = "MF057", required = false) private String instrumentType; @CsvBindByName(column = "MF086", required = false) private String derivativeISIN; @CsvBindByName(column = "MF091", required = false) private String classificationType; } Here is the code to read CSV - public void process(File msg) { final List<MyBean> data = new ArrayList<>(); final HeaderColumnNameTranslateMappingStrategy< MyBean> strategy = new HeaderColumnNameTranslateMappingStrategy(); final Map<String, String> columnMap = new HashMap(); columnMap.put("MF056", "assetClass"); strategy.setColumnMapping(columnMap); strategy.setType(MyBean.class); // Parse one row at a time final CsvToBean<MyBean> reader = new CsvToBeanBuilder(getReader(msg)).withType(MyBean.class) .withOrderedResults(false) .withFilter(new AssetTypeFilter(strategy)) .build(); reader.forEach(a -> processData(a)); } Okay several things here. First, non-related but it caught my eye, is that you don't need to use the HeaderColumnNameTranslateMappingStrategy because you are doing a @BindByName in your object. Either get rid of the setMap or try the HeaderColumnNameMappingStrategy. Now as far as the problem goes it starts with that you should be using the IterableCSVToBean instead of the CSVToBean as that is one that allows your do process one at a time. That said I believe you have built your own version of opencsv as opencsv is built in Java 7 and thus does not support the .foreach method. Try an old fashion iterator to ensure that everything is processed sequentially and immediately as your implementation is either bypassing the parse altogether or it is threaded and is trying to process the second bean before the first (which the first bean processed is the one that reads and sets the header information).
common-pile/stackexchange_filtered
JAVA desktop application - online reservation technique I am a novice programmer and would like to develop a desktop application on JAVA "Bus Ticket Reservation". Multiple device may access from different places in this system. I have no idea in networking communication programming. Please help me with some topics: what technique should i learn to communicate with server from different computers to book or check a query ??? is it related with database?? should i use mysql database to track the booking? May be i asked dumb question, please give me some advice and if there any good tutorial. Since, you want remote access to data, you should go with setting up web-service (JSON/XML) Since you want to develop a desktop application, you should realize that database is going to be the important component of the application. The outline of steps which you must follow are - Develop a GUI interface which you will need to distribute to users and will serve as client application. Some basic features which you can provide in the client GUI would include choosing unique identifier (like username), entering booking details, looking at booking history and allowing cancellation. Develop a database backend which is capable of handling this data. The corresponding tables include - users, bookings and cancellations. Use JDBC to connect your java application with the backend. This task does not require knowledge of socket programming. It just requires basic GUI development skills and connecting the application with database using JDBC. You may choose MySQL or PostgreSQL as the backend database. Netbeans IDE provides excellent support for GUI development (Drag and Drop) and you should use it to reduce your development time. For connecting to MySQL through Java, you may go through this link - http://dev.mysql.com/usingmysql/java/ or google for plenty more. SYNCHRONIZATION Create a 15 minutes ('t' in general) timeout thread which is initiated once the user submits all the details. You should update the database by reducing the quantity of available tickets for this session. You can also maintain a table which stores active bookings. Within these t minutes, if the user confirms booking, remove the entry from active booking. Otherwise, add the ticket quantity back to available tickets and terminate the session. This is the simplistic way to implement it. http://in.bookmyshow.com folllows this model. With the GUI and database i have no problem. I am curious about the real time interaction and synchronization with other users. should i call an sql query after each second or something?? I have edited the answer. I guess thats what you are looking for. For Desktop application in networking field learn socket programming or FTP(File Transfer Protocole) and RMI( Remote Method Invocation) Why do you need socket programming for that? @JavaLearner for client server interaction.
common-pile/stackexchange_filtered
How do you set the specific url path you want to work with in cxf? I am using the annotated methods in CXF to create different functionality through web service calls. For some reason, all of my URL paths come off of {hostname}/services/status/{my_path}. I am using annoted methods like so: @Path("/{type:(?i)index}") public IndexServiceResource getIndexServiceResource() { return new IndexServiceResource(this.handlers); } I would like for the @Path to come straight off of the {hostname} instead of {hostname}/services/status. Where would this be set? You can bind CXFServlet "/services" which handles cxf web-services to main context "/" in your web.xml. <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd"> <web-app> <display-name>cxf</display-name> <description>cxf</description> <servlet> <servlet-name>cxf</servlet-name> <servlet-class>org.apache.cxf.transport.servlet.CXFServlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>cxf</servlet-name> <url-pattern>/services/*</url-pattern> </servlet-mapping> </web-app> Try to change url-pattern from "/services/*" to "/*". However I'm not sure is there any way to change "/status" to be also bind to main context "/*". Of course if your request are passing through Apache proxy then it is a possible to set mapping for example "http://my.domain" -> "http://internal.server/services/status". But this is done outside your code. I suppose "status" is required due to your Jaxrs server configuration (Through i am not sure). Please check your jaxrs server configuration in your context file. <jaxrs:server id="restContainer" address="/"> <jaxrs:serviceBeans> Does the address property contains status ?
common-pile/stackexchange_filtered
Proper types for generic onChange handler in react HTML form implemented with react stateful component. I am trying to write some generic on change handler for form elements but don't succeed to get it typed properly. Here is the code: interface SignupState { username: string email: string password: string password_confirmation: string } class Signup extends React.Component<{}, SignupState> { .... onFieldUpdate: (k: keyof SignupState) => (e: React.ChangeEvent<HTMLInputElement>) => void = (k) => { return (e) => { this.setState({ [k]: e.currentTarget.value }); } }; } I thought that this way I will be able to put something like <input onChange={this.onFieldUpdate('username')} /> but have following error on setState call: Argument of type '{ [x: string]: string; }' is not assignable to parameter of type 'SignupState | ((prevState: Readonly<SignupState>, props: Readonly<{}>) => SignupState | Pick<SignupState, "username" | "email" | "password" | "password_confirmation"> | null) | Pick<...> | null'. Type '{ [x: string]: string; }' is missing the following properties from type 'Pick<SignupState, "username" | "email" | "password" | "password_confirmation">': username, email, password, password_confirmation TS2345
common-pile/stackexchange_filtered
How does Australia split its legal profession? I just got an interesting edit suggestion to my recent question by someone who just registered (perhaps for the purpose of this edit suggestion). It proposes that "lawyer" is replaced with "junior barrister" because: australia splits its legal profession, so "lawyer" is wrong It also injects a link to the professional profile of the person cited in the question. What is the deal with the splitting of the legal profession in Australia? Is that just barristers and solicitors, pretty much like in New Zealand? Or something else? Is it actually wrong to call members of the legal profession in Australia lawyers? I would guess that "lawyer" is just a general term, and the lack of specificity does not make it wrong. Am I wrong? (I presume the actual purpose of the suggested edit is to inject the link and could speculate on who the user is, but that is irrelevant to this question.) The split is whether they follow Cleaver Greene's code of conduct or not. The Australian legal profession is separately regulated in each State and Territory. Each State and Territory has a de facto split profession, in that there is a group of lawyers known as the independent bar of that jurisdiction, who practise exclusively as barristers and conduct the majority of litigation in the higher courts. Each State and Territory has a de jure fused profession, in that all lawyers are required to be admitted to the legal profession by a State or Territory Supreme Court, and all practising lawyers are entitled to appear in the higher courts, although in practice this work is mostly done by barristers. There are differences in the specific rules and practices that apply to barristers in each jurisdiction, which causes debate and confusion about whether the Australian legal profession is split or fused. The relevant differences are: In NSW, Victoria and Queensland, lawyers are required to pass bar exams administered by the local bar association in order to call themselves barristers. In NSW and Queensland, the local bar association (like the Inns of Court) is also the regulatory body that issues practising certificates and investigates and disciplines barristers. In the smaller jurisdictions, membership of the bar association, and other professional obligations of barristers such as self-employment, may not be legally required to use the title of barrister. While there is an independent bar consisting of members of the bar association who voluntarily comply with the professional obligations of barristers, lawyers employed by law firms and the government conduct a greater proportion of the advocacy in these jurisdictions. Those barristers, are they like "barrister sole" in New Zealand (i.e. registered as such), or are they like "barristers and solicitors" but just only practicing as barristers? Under the Legal Profession Uniform Law, which applies in NSW, Victoria and WA, barristers accept a condition on their practising certificate which legally restricts them to practising exclusively as barristers. This seems to be equivalent to the NZ concept of “barrister sole.” I am not sure if barristers in the other small jurisdictions typically accept a legally binding condition on their practising certificate or merely agree to the non-statutory rules of the local bar association. In many Common Law nations, the distinction between solicitor and barrister is that the solicitors traditionally have direct access to clients and do much of the paperwork and discuss the planning with the clients. In some jurisdictions it was/is common practice that the barrister is not hired by the client but appointed by the judge. The barrister in turn works with the solicitor and presents the case in the court and has little to no access to the client. Historically, the division was much more stark, with solicitors working in the Court of Equity and barristers working in the Court of Common Law. Around the mid-1800s, the Court of Equity became defunct in the Common Law Legal system with the Court of Common Law fulfilling its duties and many Common Law nations changing how the split among lawyers now functions (often requiring separate tests to be a solicitor and a barrister). The split remains in England, Wales, Scotland, three states in Australia (New South Wales, Queensland, and Victoria), Ireland (both the Republic and Northern Ireland), and Hong Kong. In these jurisdictions, a lawyer will hold only one title. In jurisdictions where lawyers may, or even are expected to, hold both titles, the system is called a “fused system”. Here, lawyers start their careers as one of the two and pick up the license to act in the other capacity later if they choose. This covers the jurisdictions of Canada, Malaysia, Singapore, New Zealand, and the remaining Australian states. (Because Australia has a mix of fused and separated systems and state reciprocation, the three states with a separated system will reciprocate for states that allow for fusion. The reverse is not necessary, as fused states would only allow them for the license they already have.) The United States is fully fused and all lawyers are solicitor-barristers, for comparison’s sake. This is why the U.S. uses “attorney” and “lawyer” interchangeably despite the former being another term for barrister in certain jurisdictions (namely Scotland) while the latter term refers to solicitors and barristers collectively. The U.S. did previously have a separate system, but completely fused when Courts of Equity disappeared in the 1850s and, therefore, the term “solicitor” is still used in the legal profession, though these days it tends to be an artefact title for an office or position that predated the fusion (e.g., The Solicitor General of the United States a.k.a. the lawyer whose office represents the federal government in the Supreme Court). Modern usage of “solicitor” tends to refer to a government lawyer, and most of the states with Solicitor offices are one of the Original 13 States (not all of them, though). Only three states that were not part of the original 13 use the term (Ohio, West Virginia (likely a hold over from when it was part of Virginia, which no longer uses the term), and Oklahoma). It should be noted the average U.S. Citizens associate the word solicitor with traveling salesman or door-to-door evangelizers, and generally use the term in signage forbidding the practice on private property. 'It should be noted the average U.S. Citizens associate "solicitors" as "traveling salesman" or "door to door Evangelicals' - really, wow - that's interesting. FWIW, the division of professions in civil law countries (which is also not uniform) is quite different. Many have separate legal professions for notaries (who have formal lawyer level transactional law training), trial lawyers (similar to barristers), prosecutors, judges, and public law lawyers. Some also have both licensed non-trial lawyer legal practitioners akin to solicitors, in addition to many unlicensed people with undergraduate degrees with law who often work in business much the way someone with a finance or marketing major might, while others don't license solicitor type work. In pedantic U.S. terminology, one should really distinguish between "attorneys at law" who are lawyers, and "attorneys in fact" who are agents under powers of attorney and frequently are not lawyers. "and most of the states with Solicitor offices tend to be one of the Original 13 States" In most U.S. states the "solicitor general" is a senior lawyer in the attorney-general's office who is in charge of cases argued in the state supreme court and the U.S. Supreme Court on behalf of that state. A couple of U.S. states have independent legal paraprofessionals who have a limited practice in certain subject matter areas. Similar professionals exist in federal tax practice, and in federal patent and trademark practice before government agencies. "Soliciting" is also sometimes used as a euphemism for prostitution in U.S. English and in U.S. law. "The U.S. did have a previous have separate system but completely fused when Courts of Equity disappeared in the 1850s and as such" in the 1850s and earlier the legal profession was not formally or bureaucratically regulated. Individual courts determined who could argue cases before them (mostly based on referrals from people currently allowed to argue before it without formal education requirements or exams) but there were no law schools and no formal distinction between people who were and were not lawyers, who were men who practiced law like a businessman is someone who engages in business. Just a correction, according to https://austbar.asn.au/for-the-community/what-is-the-bar Victoria is also fused (unless things changed since 2019). @ohwilleke True, but I've never heard anyone refer to a prostitute or pimp as a "solicitor". @Barmar I've certainly heard that usage of the term. @Alan Dev, See this. You also see them in Canada, though I suspect not nearly as much as in the US @ohwilleke I've heard of prostitution being legally called "Solicitation of Sex" but never a prostitute being a solicitor. Generally the "No Solicitors/Solicitation Signs" on private property are to give notice to Door-to-Door solicitation that such acts are trespassing. I guess Ladies of the Night would be under similar notice though prostitution generally has a separate crime the property owner can call out. 37 states or U.S. territories (out of 56 entities total) had a solicitor general in 2008. Perhaps more do now because many have recently created the office. https://abovethelaw.com/2008/08/a-hot-new-trend-state-solicitors-general/ https://lawrepository.ualr.edu/cgi/viewcontent.cgi?referer=&httpsredir=1&article=1169&context=appellatepracticeprocess @deep64blue Ok now I'm imagining a funny situation where an American moves to the U.K. and puts up a "No solicitors" sign... Lawyer is perfectly fine Lawyer is a catch-all term for both barristers and solicitors. On a related tangent what about attorneys? @NeilMeyer oh, yes, we have attorneys, but they aren’t lawyers or legal professionals of any kind. An attorney is a person with the legal power to act in the place of someone else.
common-pile/stackexchange_filtered
perfect lens: expression for interface Suppose I want to find a function $(x,z) \mapsto y((x^2+z^2)^{1/2})$ which must represent the interface between two translucent media with different refractive index and which must yield a perfect lens, i.e. a lens without spherical abberation: light rays coming in from $y=-\infty$ and propagating parallel with the $y$-axis must be refracted at the interface in accordance with Snell's law and the outgoing light ray must hit the $y$-axis in a certain point $F=(0,c,0) \in \mathbb{R}^3$ with the "focus" $F$ independent of whichever incoming light ray we considered (this latter property is what makes the lens "perfect"). Suppose we agree to choose WLOG that $y(0)=0$. After some elementary geometry, I find that the problem reduces to the ODE $$\frac{x}{(x^2+[c-y(x)]^2)^{1/2}} = \sin(\alpha(x))\cos(\theta(x)) - \sin(\theta(x))\cos(\alpha(x))\\ \sin(\alpha(x)) = \frac{y'(x)}{(1+[y'(x)]^2)^{1/2}}=n\sin(\theta(x)) \qquad(1)$$ with $n>1$ the refractive index of the medium above the interface relative to the medium below. I believe giants such as Leibniz, Newton, Huygens must have arrived at this point and gotten stuck in finding a closed-form solution to this ODE. Browsing the web I found a paper claiming a closed-form solution (at least to a similar problem) and reading the contents of their article they claim the solution involves a simple expression without reverting to the use of non-elementary functions. I'm skeptical though, so therefore the following question: Q: Can solutions of the ODE (1), subject to the initial condition $y(0)=0$, be expressed in terms of elementary functions? What is the most transparent account of the solutions to this ODE? (the 2nd question can be understood in the same vein as how the Kepler problem may be difficult to solve with e.g. time as the independent variable, but if one promotes a related variable -namely the angle- as the independent variable a closed-form solution in terms of elementary functions is easily obtained.) (Apparently the problem of designing abberation-free lenses is colloquially known as the "Wasserman-Wolf problem") Apparently the problem ought to be solved with a closed-form expression. See this paper for details.
common-pile/stackexchange_filtered
sequelize findOne doesn't find a userId when that usedIf is in the db I am using node.js/express/sequelize lo log in a user. I'm testing making the requests in postman to see if it gets anything. I am testing a user and pw that I know are in the db but my findOne query in sequelize returns null even though the tested name is in the db. Here's the query in question: let { userId, pw } = req.body try{ const foundUser = await User.findOne({ where: { userId: userId } }); if (foundUser === null) { return res.status(401).send({ auth: false, token: null,error: 'name not found' }); } else { const passwordIsValid = bcrypt.compareSync(pw, foundUser.pw); if (!passwordIsValid) return res.status(401).send({ auth: false, token: null,error: 'name not found' }); const token = jwt.sign({ id: foundUser.id}, config.secret, { expiresIn: 86400 // expires in 24 hours }); res.status(200).json({auth:true,token:token}); } } catch (err) { res.status(500).json(err); } } my json I have body-parser implemented for jsonenter image description here on index js and the routing works as the userId and pwd values make it to the findOne query. However it still says that there are no results after the query. Terminal runs the following (userId is 'slim') Executing (default): SELECT id, username, userId, pw, createdAt, updatedAt FROM users AS users WHERE users.userId = 'slim'; 'slim' is both in the Json and in the 'userId' section of the db at the first place you use findAll, which returns array if it is not an issue just check if req.body returns proper value my bad I was using findOne but tried changing it to findall before posting this question. FindAll returned a 500 error. I'll edit accordingly it turns out the issue was because there was more than one 'slim' in the userId section of my db, it was acting funny. When I entered a truly unique value for userId, it returned the token as expected. Maybe it seems obvious but it's important that that value called for authentication in unique.
common-pile/stackexchange_filtered
How to solve PLS-00103 Oracle PLSQL error? I got an error PLS-00103: Encountered the symbol "END" when expecting one of the following: ( begin case declare exit for goto if loop mod null raise return select update while with << continue close current delete fetch lock insert open rollback savepoint set sql execute commit forall merge standard pipe purge json_object Here is my code: declare a int := 4; i int; begin for i in 1..10 loop dbms_output.put_line(i); if i=a then goto ax; end if; end loop; <<ax>> end; it is expecting a statement, for example dbms_output. Plus try to use exit instead of GOTO, to exit the loop. When PL/SQL encounters a GOTO statement, it transfers control to the first executable statement after the label. From the documentation: A label can appear only before a block (as in Example 4-21) or before a statement (as in Example 4-29), not in a statement, as in Example 4-30. As you can see in the examples, you can fix this by adding a null statement: declare a int := 4; --i int; begin for i in 1..10 loop dbms_output.put_line(i); if i=a then goto ax; end if; end loop; <<ax>> null; end; / In this case you can also just use exit instead of goto: declare a int := 4; --i int; begin for i in 1..10 loop dbms_output.put_line(i); if i=a then exit; end if; end loop; end; / fiddle In both cases I've commented out the declaration of i - you don't need to declare a loop variable, and even if you do the scope is different so they would be independent.
common-pile/stackexchange_filtered
IndexError: index 10 is out of bounds for axis 0 with size 10 I am numerically setting up a mesh grid for the x-grid and x-vector and also time grid but again I have set up an array for x (position) which should only be between 0 and 20 and t (time) would be from 0 until 1000 thus in order to solve a Heat equation. But every time I want for e.g., I make the number of steps 10, I get an error: "Traceback (most recent call last): File "/home/universe/Desktop/Python/Heat_1.py", line 33, in <module> x[i] = a + i*h IndexError: index 10 is out of bounds for axis 0 with size 10" Here is my code: from math import sin,pi import numpy import numpy as np #Constant variables N = int(input("Number of intervals in x (<=20):")) M = int(input("Number of time steps (<=1000):" )) #Some initialised varibles a = 0.0 b = 1.0 t_min = 0.0 t_max = 0.5 # Array Variables x = np.linspace(a,b, M) t = np.linspace(t_min, t_max, M) #Some scalar variables n = [] # the number of x-steps i, s = [], [] # The position and time # Get the number of x-steps to use for n in range(0,N): if n > 0 or n <= N: continue # Get the number of time steps to use for m in range(0,M): if m > 0 or n <= M: continue # Set up x-grid and x-vector h =(b-a)/n for i in range(0,N+1): x[i] = a + i*h # Set up time-grid k = (t_max - t_min)/m for s in range(0, M+1): t[s] = t_min + k*s print(x,t) arrays are zero indexed i.e. 0-9 You try to index outside the range: for s in range(0, M+1): t[s] = t_min + k*s Change to: for s in range(M): t[s] = t_min + k*s And it works. You create t with length of M: t = np.linspace(t_min, t_max, M) So you can only access M elements in t. Python always starts indexing with zero. Therefore: for s in range(M): will do M loops, while: for s in range(0, M+1): will do M+1 loops. Ya it really is working now but the values of of x are supposed to be divided in equally spaced intervals which would run from: a = 0.0 to b=1.0, and it just not seem to give me the values i want as it gives values over 1 Thanks as i now have it working and running properly @MikeMuller Great that it helped. BTW, you can accept an answer if it solves your problem.
common-pile/stackexchange_filtered
Can I throw an exception in apex and still log the caught exception? I'm really wrestling with the best error handling strategy. My goal is to handle all exceptions that I can identify, log them to a table in the database, and surface a helpful message about what happened to the user. The problem I am using an auth provider for SSO OAuth from one Salesforce instance to another. It's generally working fine but the registration handler has some complex logic, including a callout to another org for verification of some data. Sometimes the callout fails for a few different reasons and there are a handful of other infrequent but notable registration errors that we wish to log. The problem is that without throwing a custom exception, there is no way to communicate to the error handler page for the auth provider what happened, not that I see at least. Handled errors fail silently. When I throw an exception in my reg handler, whatever logging I had attempted gets rolled back. What I've tried I tried logging and then throwing the exception in the catch block in a bunch of places in my registration handler class. As I mentioned, this was a no go since the logging got rolled back. I've also tried not throwing the exception but then some of my logic in the reg handler gets subverted/ignored. I have yet to try rolling back to a savepoint in my catch blocks following known and handled errors, and this may solve this issue, although I wouldn't be able to surface anything helpful to the user at this point. Questions When would I use the Finally block? Can it be used for any purpose when throwing my own exception or would whatever logging I did get rolled back. Is there any way to force custom logging and save to the database while also throwing an exception? What other strategy should I try here? Finally, how do you think this should work? It seems like there is some logging path that you should be able to continue down in apex, even after an exception and a rollback. First please take a look at this answer for a partial solution / approach, Can I prevent an insert to be rolled back even if my class (later) runs into an exception?. Basically as per the Apex Developers guide the final commit transaction management is baked into Apex, meaning it will always rollback if you let the platform handle your exceptions, if you don't you have to manage the rollback scope yourself or accept any DML that has been issued be committed. If the entire request completes successfully, all changes are committed to the database. For example, suppose a Visualforce page called an Apex controller, which in turn called an additional Apex class. Only when all the Apex code has finished running and the Visualforce page has finished running, are the changes committed to the database. If the request does not complete successfully, all database changes are rolled back The only way to get control of this is to use the try/catch/finally semantics, along with Savepoints, and critically not throwing any exception (note that as per the answer above some system exceptions cannot be caught sadly). Since your implementing the Auth.RegistrationHandler interface your stuck with its method signature and thus cannot code any alternative way to pass errors back, not does there appear to be any support for this on the interface itself. Passing a null user back from createUser. What happens if you using try/catch/finally with a logging approach as above and then null back? I expect the system will handle this and present some general error message. Of course in this case your more detail errors will have been logged, since technically the call completed successfully. You would of course have to educate your users / admins to check your own log in this case. Given the frequency of the issues, perhaps this is tolerable? As regards the updateUser method, i don't see any way to infer errors with a successful execution of the method. Summary and System.debug? Sorry this is not the answer you wanted, but i believe this is the situation. Your not the first to want to implement such a logging approach as you can see. Ultimately its a matter of how far your prepared to go against the transaction management semantics of the platform vs resorting to having your Admins enable Debug Logs and adding System.debug output to your code to output messages to the standard platform log that can then be reviewed for your errors. Thanks for the comprehensive response. I think my only option is going to be to throw exceptions in the updateUser method as nulling out the user does not appear to work there, which leaves me back where I started. I dug into this and discovered quite a bit about this interface and came up with a creative work-around, which I'll post an answer. As a follow up to this thread and to answer this question should anyone happen up this, here is what I discovered: The Auth.RegistrationHandler interface at the heart of this question has two main methods, as Andy noted, createUser() and updateUser(). The former returns a user and the latter is a void method. I tried Andy's suggestion and pattern of try/catch/finally to log errors. This actually works fine for the updateUser method, since it is a void method. For the createUser method however, I tried to rollback in the catch block and log in the finally block but the rollback of createUser() passes a null or empty user back to the Auth.RegistrationHandler interface, which then causes an unhandled exception in the "parent" class to occur. The exception is Argument 1 cannot be null. Since this is an unhandled exception, the entire transaction including my logging gets rolled back. The solution that I've come up with is to catch all exceptions, then construct the stack trace and other important debug information into a new custom exception adding all of that info to the exception message, which I then throw. In my Auth Provider error page, I take the custom exception that I've thrown, which includes the stack trace and other useful info off the querystring and parse and log it there, as well as displaying what I want of that message (not including the stack trace) to the end user on that page. Nice! +1 from me! Usually, I use the finally after catching several different exception types, to reset variables used in a processing loop. As far as your logging concept, it is a good idea. There are two ways you can create records in the context of an exception. One would be to use partial processing dml instead of "all or nothing". This is done by using the "database" version of the dml. For example database.insert(my account list, false); The false allows partial processing. Then you can iterate over the results from the dml looking for exceptions. When you use partial processing you can still create records in your catch block. The other option, which may be better for your with scenario, would be to create a separate logger class and method, configured as a future method. Pass the error or list of errors to the future method and the logging records can be created out of the transaction context of the exception. Hope that helps you out. Jim Future methods also roll back in the event of an unhandled exception. My solution considers catching all exception types, which would allow the logging records to be saved. I encountered this exact issue recently and figured I would post my solution for anyone who finds this thread in future. The solution I came up with was to publish a Platform Event before throwing an exception from the createuser method. The Platform Event needs to be set to a Publish Behavior of 'Publish Immediately' so that it publishes even when the apex transaction encounters an exception. Then you can use a Platform Event Triggered flow or trigger to actually do the logging.
common-pile/stackexchange_filtered
Why does adding a product to a formula with update.formula introduce a vector? I'm trying to modify model formulas using update.formula from the base stats package, but adding a new product term does not do what I expected. For example, f <- y~x update.formula(f, .~.*z) I expected this to return: y~x*z But it returned: y ~ x + z + x:z Can anyone explain this? Is there a way to get the result I expected? y ~ x + z + x:z is the same as y~x*z. The latter is short-hand for the former. They don't evaluate the same. If x<-2 and z<-3, x*z returns 15 but x+z+x:z returns 7 8. What do you mean exactly by "evaluate"? My previous comment paraphrases the documentation in help("formula"). Thanks for pointing me to help(formula). It had the solution to this, which is to use update.formula(f, .~I(.*z)).
common-pile/stackexchange_filtered
ASP WebService high latency I am writing a WebService in .NET Framework 4.7.2. I am experiencing high latency on my requests. When I call a WebMethod using PostMan, it takes almost 2 seconds to even hit the constructor in my web service class. What would cause such high latency? I'm using Debug using IIS Express from Visual studio 2019. I have also tried Release Mode, and also "Run Without Debugging". Everything seems to take at least 2000ms latency for a seemingly simple request. This happens on every request (not just the first request). public class MyService: System.Web.Services.WebService { public MyService() { // Takes almost 2000ms to get to this point } } The rest of my code (constructor/WebMethod) executes almost instantaneously once it finally gets to my constructor. Why is there so much overhead/latency before it gets to my code? Is this due to IIS Express? Would it be faster using a full version of IIS? I come from background of ASP.NET Core, so I'm not to familiar with the inner workings of old/legacy ASP stuff. What sort of things should I be looking for to help with the request latency? check on global.asax nd the Application_BeginRequest to see if you run there anything... If this is a WCF app, try enabling logs and see how long does the service take to instantiate your request
common-pile/stackexchange_filtered
How to crawl / index pages behind a login? Is it possible (are there any tools out there) to crawl pages (not content, just url) that's behind a login? We are looking to creating a new site, and need to index each page on the old site in order to capture all the content, content types, map all urls to the new site, etc... I have a login and I'm not looking to add this to google or anything. Screaming Frog won't do it. And I can't involve the dev guys of the current site - so putting a script on the server won't work either. Any other way to do this? Yes you can,Integrate your crawler with "SELENIUM".Provide login credentials and you can get your work done. Few good links that may help you:- How to use Selenium with Python? http://www.quora.com/Is-it-possible-to-write-a-Python-script-for-opening-a-browser-and-logging-into-a-website-How-could-you-do-it https://selenium-python.readthedocs.org/en/latest/getting-started.html It may take time and research but yes it will be done, take care of the Logout page while crawling. A good option which you can explore is using Scrapy. Its a python based framework to for extracting the data you need from websites. This will help you to remote login into a site and download the relevant data. You can define and control the data you want to extract and how to process it. Also its much faster allowing to crawl and extract data from 16 page or more in parallel. Well, there is a workaround. You can use ExpertRec's custom search engine and set up a crawl behind login pages. Here's the blog with instructions: https://blog.expertrec.com/crawling-behind-login-authenticated-pages/ Though this is meant for building custom search engines, they have a free trial so you can set it up for free. And here's the workaround part. Once the crawl is complete, they let you export all the indexed URLs, and boom! there you have a list of all the pages that are behind the login.
common-pile/stackexchange_filtered
ScrollView not responding with LinearLayout I am using a ScrollView but it does not work. It is not responding. I was wondering if anyone can find something suspicious in my xml file. I do have other xml files using the same Android tool and they are working just fine. Here's my code : <?xml version="1.0" encoding="utf-8"?> <ScrollView xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent"> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent"> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:textAppearance="?android:attr/textAppearanceMedium" android:text="alias" android:id="@+id/alias" android:layout_marginTop="15dp" /> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:textAppearance="?android:attr/textAppearanceMedium" android:text="date_of_post" android:id="@+id/date_of_post" /> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:textAppearance="?android:attr/textAppearanceLarge" android:text="comment" android:id="@+id/comment" android:layout_marginBottom="15dp" /> </LinearLayout> </ScrollView> If you want it to scroll the LinearLayout needs to be wrap_parent. If it fills the screen it will start scrolling I don't see any issue with the codes, It should work properly. Are you inflating this view some where else or you are using as content view for activity? The DDMS View Hierarchy dump is priceless for layout issues like this. I'd suggest dumping the view hierarchy in the debugger. Try this <?xml version="1.0" encoding="utf-8"?> <ScrollView xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent"> <RelativeLayout android:layout_width="match_parent" android:layout_height="wrap_content"> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:textAppearance="?android:attr/textAppearanceMedium" android:text="alias" android:id="@+id/alias" android:layout_marginTop="15dp" /> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:textAppearance="?android:attr/textAppearanceMedium" android:text="date_of_post" android:layout_below="@+id/alias" android:id="@+id/date_of_post" /> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:textAppearance="?android:attr/textAppearanceLarge" android:text="comment" android:id="@+id/comment" android:layout_below="@+id/date_of_post" android:layout_marginBottom="15dp" /> </RelativeLayout> </ScrollView> Then you just don't have enough text to fill the view. Its not going to scroll unless its full Scratch that I just remembered you don't want a LinearLayout to be the child of a scroll view. Check my edit actually I'm sure it should be working because I have many items on my list. I'm starting to believe there is something working with my layout. Post the entire layout I'll spot it if I get a minute well a friend just solved my problem. I was not looking at the right layout... Thanks for your time and for your help Jasz ! I didnt see anything wrong in your xml. My suggestion is you should look at the display, did your textviews go over the screen or not? cuz if it the screen, there wont be anything to scroll. Hope it help ^^
common-pile/stackexchange_filtered
Python unable to install sklearn and datasets From this particular website http://scikit-learn.org/stable/tutorial/basic/tutorial.html I was trying to install a PIP called sklearn and datasets, by using ` pip install sklearn` pip install datasets . They have been succesfuuly downloaded but when I try to import that particular packages, I couldn't import that package. I am newbie to this packages and dependencies in python. Thanks in advance. You don't need to install the dataset separately. Scikit-learn has infrastructure to download them on the fly. Also, the pip package name is scikit-learn, not sklearn. Im not sure if it was installed as you have to type the following: pip install -U scikit-learn Also, Im not sure if datasets can be downloaded via pip. I think youre confusing installing a package and importing a package into code. I think you may need a brief intro to python programming. 'Automate the boring stuff' and 'learn python the hard way' are great and succinct intros that will get you up to speed on why your question is confusing at best and misguided at worst:) installation guide for scikitlearn http://scikit-learn.org/stable/install.html
common-pile/stackexchange_filtered
How to check if gun may shoot again (because animation has stopped playing)? When the user presses the fire button, I set a trigger: _animator.SetTrigger("HG_Shoot"); This trigger causes a "pistol shoot" animation to be played. The gun should only be able to shoot again as soon as the shoot animation has finished. I could check at each Update() if that certain animation is still being played like this: bool isAnimationStatePlaying(Animator anim, int animLayer, string stateName) { if (anim.GetCurrentAnimatorStateInfo(animLayer).IsName(stateName) && anim.GetCurrentAnimatorStateInfo(animLayer).normalizedTime < 1.0f) return true; else return false; } But I don't like the frequent checks. I would rather like to have a variable to would be set by the animator. Or I would set it at the beginning of the shoot animation. Because there are other animations that I have to check that would disallow shooting of the gun, too, like reloading the gun. This would make everything even more complicated. How can I solve this problem? Is this code really showing up in your profiler as a significant cost in your game? @DMGregory No, but my instincts tell me, and my programmer heart hurts because my current approach looks so horribly unprofessional. I want to check a variable only that would be set by the animator if a state changes or so. Remember what Knuth told us about our programmer instincts and the trouble they can lead us into. @DMGregory Yes, but I have so many other conditions that I would have to check: "IsDying", "IsClimbing", "IsJumping". See? That's why I was thinking about a variable that I could simply query. Any reason you can't just use Animation Events to Enable/Disable Firing? @Pheonix2105 Yes, I actually did that already as I have just seen in my code. But I was wondering if there was built-in method to handle such a common use case perhaps. You could use Unity's StateMachineBehavior component. I'll tell about it later. However, it's actually might be an overkill feature that might bring up more complexity to the project than needed. There's nothing wrong with your current approach as far as you keep things more or less readable and properly structured. The only other alternative (in addition to your current approach and StateMachineBehaviour approach) would be a timer that would count down in every frame to check if the shoot cooldown is over, or reload time is over, and it's also a commonly used approach. As for the isJumping, isClimbing, etc states when the gun shouldn't be able to shoot as well, these states should be managed in the character scripts while the gun's isShooting, isReloading, isJammed states should be in the gun's scripts. That's how you keep things manageable. Player clicks Fire button, you call Shoot() method in the character script that checks the character's states such as isJumping, etc, and then if everything is fine and the character is not busy you call the gun's Shoot() method that checks if the gun is not already shooting or reloading currently. Okay. The StateMachineBehaviour. This is a thing that allows you to get certain predefined events from the animator states (nodes in the animator controller window) so you can do your stuff when the animator has entered an animation state, is currently performing some animation or the animation is over and the control is going to transition to some other state. Here is the official manual: https://docs.unity3d.com/Manual/StateMachineBehaviours.html The basic workflow is: You open up the animator controller window of the gun's animator, select your 'Shoot' node, than in the inspector window you add a StateMachineBehavior component to the node. It should generate a script that has several methods like this: //OnStateExit is called when a transition ends and the state machine finishes evaluating this state override public void OnStateExit(Animator animator, AnimatorStateInfo stateInfo, int layerIndex) { } (Not sure if this is exactly how it's done though, I didn't use the StateMachineBehaviour for a long time). That's what you're looking for - an event that fires when the 'Shoot' animation is over. There is also the OnStateEnter(...) method available as well. So, you could manage the gun's 'canShoot` boolean flag like this: override public void OnStateEnter(Animator animator, AnimatorStateInfo stateInfo, int layerIndex) { GunScript gun = animator.GetComponent<GunScript>(); gun.canShoot = false; } override public void OnStateExit(Animator animator, AnimatorStateInfo stateInfo, int layerIndex) { GunScript gun = animator.GetComponent<GunScript>(); gun.canShoot = true; } You would need to add similar components to other animator nodes like the gun's 'Reload' node, the player's 'Jump' node, etc, so whenever these animations are played the gun's canShoot flag will be set to false and get back to true when the animation is over. Thank you, your timer approach is actually what I need. It just came to my mind again that the user can achieve a higher shooting speed (for example by weapon upgrades), so I definitively need the timer approach. Thank you very much, also for the state machine explanations. You could add an animation event to your shooting animation action which calls back your controller script and signals it that the player can shoot again. However, I generally prefer to not design my gameplay using the animation system. I instead design the gameplay first and then have the animation match the gameplay. A game is far easier to balance when all the relevant numbers are in one place. So I would usually define the fire rate of each weapon in the same place where I define the damage, range, accuracy and so on. Then I would experiment with those values until the game is properly balanced, and then take care of matching the animations to the gameplay. Matching animations to gameplay can also be automated by calculating the playback speed of animations based on gameplay variables. Thank you for the explanation. The pro tipp of having the animation match the game play and not the other way around will stay with me forever. Thank you!!!
common-pile/stackexchange_filtered
Faster way to apply a function over a column in pandas data frame I have to apply some multiple functions to a column to get the list of bigrams but it is painfully slow using the apply function the way I'm currently using. Do you have a way to boost the speed? def remove_stop_words(text): cleantext = text.lower() cleantext = ' '.join(re.sub(r'[^\w]', ' ', cleantext).strip().split()) filtered_sentence= '' for w in word_tokenize(cleantext): if w not in stop_words: filtered_sentence = filtered_sentence + ' ' + w return filtered_sentence.strip() def lemmatize(text): lemma_word = [] for w in word_tokenize(text.lower()): word1 = wordnet_lemmatizer.lemmatize(w, pos = "n") word2 = wordnet_lemmatizer.lemmatize(word1, pos = "v") word3 = wordnet_lemmatizer.lemmatize(word2, pos = ("a")) lemma_word.append(word3) return ' '.join(lemma_word) def get_ngrams(text, n ): n_grams = ngrams(word_tokenize(text), n=2) return [ ' '.join(grams) for grams in n_grams] df['bigrams'] = df.headline.apply(lambda x: get_ngrams(lemmatize(remove_stop_words(x)),n=2)) Edit: (based on comment) The data frame df contains 2 columns - 1. headline 2. Sentiment score headline - It's news headline, basically text on which I've to apply the function to get the bigrams of the headline Sentiment Score - I've to keep the score as well in the df dataframe hence need to get a column called "bigram" in the same data frame Dataframe df you won't be able to get around the apply to apply the functions. so unless you manage to speed up those, you might want to consider multiprocessing, to parallelize the process Can you share all relevant code and data? Please see: [mcve]. I've described the data frame and added an image of how it looks, hope it gives you enough idea @WhiteWalker Data in the post itself, please, not as an image. I found the best way to do this was to parallelize the process using the multiprocessing library. import numpy as np import pandas as pd import re import time from nltk import pos_tag, word_tokenize from nltk.util import ngrams import nltk from nltk.corpus import stopwords import nltk.data from nltk.stem import WordNetLemmatizer import random from multiprocessing import Pool def get_ngrams(text, n=2 ): n_grams = ngrams(text.split(), n=n) return [ ' '.join(grams) for grams in n_grams] def bigrams(df): df['bigrams'] = df.headline.apply(lambda x: get_ngrams(lemmatize(remove_stop_words(x)),n=2)) return df def parallelize_dataframe(df, func, n_cores=20): df_split = np.array_split(df, n_cores) pool = Pool(n_cores) df = pd.concat(pool.map(func, df_split)) pool.close() pool.join() return df df2 = parallelize_dataframe(df, bigrams) bigramScore = df2.explode('bigrams') Note: This is useful only when you have a large number of cores available if you just have 2-3 cores available this might not be the best approach as the overhead cost of parallelizing the process is also to be considered.
common-pile/stackexchange_filtered
White corner showing on black box with Border-radius I am getting a odd effect (currently in chrome). I have created my own overlay dialog box. which has a semi transparent background sitting on top of my website with a box on top of that. the top of the bar as you can see has a black background. The main part of the box is white thought. Its not the easyist to see but it is annoying me. The white is showing through from behind. (I know as if i change it to red it changes colour) Which you can see in the top right hand corner of the screenshots, just above the "X" Both the header and the box has a border radius 3px .blockUI .overlay { background: #f00; border-radius: 3px; margin: 0 auto; padding: 10px; overflow: hidden; position: relative; top: 20%; text-align: inherit; width: 600px; z-index: 10009; } blockUI .overlay h1 { background: #000; border-bottom: 2px solid #F48421; border-radius: 3px 3px 0 0; color: #FFF; font-family: 'Roboto', sans-serif; font-weight: 300; margin: -10px; padding: 10px; } Try a bigger border-radius (4px for example) for the white box, please. You can remove the border-radius from the heading, it should be clipped by overflow:hidden anyway. @Jayx In theory yes, but actually some engines still render stuff with overflow: hidden; and border-radius on top. (http://tech.bluesmoon.info/2011/04/overflowhidden-border-radius-and.html) @kleinfreund I did as you said and this has seemed to solve the issue. I reduced the h1 radius to 2px thanks Since overflow: hidden; along with border-radius seems to cause some rendering inconsistencies in some engines (take a look at this), one should use border-radius on both the parent and the child elements to achieve rounded corners. As you have noticed, you still get some wierd results with extra pixels "shining" through. Just reduce the border-radius of the child (or the other way round) to compensate this. blockUI .overlay h1 { border-radius: 2px 2px 0 0; } This certainly helps, but unfortunately some of the parent element still comes through even using this technique (in firefox at least) I had same problem. But I solved. .blockUI .overlay {background:#000;} and remake some! You should try on the parent div: -webkit-background-clip: padding-box; Bootstrap already does this: https://github.com/twbs/bootstrap/blob/v3.3.7/dist/css/bootstrap.css#L5908 Adding "backgroung-clip: context-box;" solved my issue. Thanks for the heads up Finally fixed this completely by adding this on parent and child divs. -webkit-perspective: 1000; -webkit-backface-visibility: hidden; -webkit-transform: translate3d(0,0,0); outline:none; border:none; text-decoration:none;
common-pile/stackexchange_filtered
Trying to reject Negative values in an ArrayList Class I'm a really green amateur at java. I'm trying to build an ArrayList Class I can call from my main program to add user int values into the arrayList, reject negatives and then return the value. Here's what I have so far: import java.util.ArrayList; import java.util.Scanner; public class ArrayInput { public static ArrayList<Integer> input() { //This collect user CU and place in an ArrayList ArrayList<Integer> cus = new ArrayList<>(); Scanner input = new Scanner(System.in); System.out.println("Enter a # total for a single item and then press enter. To quit type exit: "); while (input.hasNextInt()){ int value = input.nextInt(); if (value < 0) { System.out.println("Error: must not be negative numbers: "); break; //<----- I know the break isn't right, and here's where I can't figure out how to reject the negative and continue to collect positive #. } else { System.out.println("Enter a CU total for another single class and then press enter. To quit type exit: "); } cus.add(value); } return cus; } } Any help would be app Remove the break and put the add in your else statement block. Use a do while loop for your value = input.nextInt(); to prompt the user as long as the value is negative. import java.util.ArrayList; import java.util.Scanner; public class ArrayInput { public static ArrayList<Integer> input() { //This collect user CU and place in an ArrayList ArrayList<Integer> cus = new ArrayList<>(); Scanner input = new Scanner(System.in); int value; do { // do loop System.out.println("Enter a # total for a single item and then press enter. To quit type exit: "); value = input.nextInt(); if (value < 0) { System.out.println("Error: must not be negative numbers: "); } } while(value < 0); // loop as long as it's negative number System.out.println("Enter a CU total for another single class and then press enter. To quit type exit: "); cus.add(value); return cus; } This should keep prompting the user for the value as long as the number is negative. However I noted that your "Enter a CU total for another single class and then press enter. To quit type exit: " wouldn't work properly. Guess you haven't implement it yet? Things to note: this is not a main method. Therefore you shouldn't really get user to "continue to collect positive #.", however if that's what you really want you can use this loop method to keep asking the user. Also it would be better not to use Scanner to get input in this method. Instead get the input from the user in main method and call upon this method and passing in the input as an argument to add cus would be the right way of using methods. cus.add(value); will add only last value you should put it inside loop.OP wants to reject Negative values ad add positive ones to ArrayList.Not a big Mistake Taking DownVote Back and still To quit type Exit will work :) WoW, I got response quicker than I thought I would.Thanks that means a lot. Maybe I can clarify what I'm doing. I'm calling this arrayList class. I'm wanting it to prompt the user to enter positive ints and if there's negatives reject it, but then prompt the user to try again. I still need to figure out how to exit out after they're done entering the int into the arrayList. I think I'm making this harder than what It should be, that's what causing me to get lost. @TAsk putting inside cus.add(value); inside the loop will get add negative value. I'm looping the input value by user and keep requesting for the input value till user input a positive value then it will do the necessary add. This is what the user wants. However I noted that this is a method so he shouldn't really get the inputs, your answer would be the more correct way of using the method. But this is what OPs want which is not using the correct way of writing methods. @user3591640 keep your method short. You should do the re-prompting and checking of negative value in the main method. And instead your this method should take in the input value as an argument to do cus.add instead. So you don't really need to declare additional Scanner object to get the user input. This will make your codes neater. Also while (input.hasNextInt()){ } I'm not sure why you are using the loop for, but my guess is it will either return hit an error or return a false which will makes the code not running at all. @Sky Many thanks. I'm 6 weeks into learning Java, so neat code is still something I'm struggling with. I'm trying to consume as much info as possible. Thank you for your help, I've added you suggestions to my overflowing notebook. Thanks for your help. I think I have it working. Try this: if (value < 0) { System.out.println("Error: must not be negative numbers: "); } else { cus.add(value); System.out.println("Enter a CU total for another single class and then press enter. To quit type exit: "); }
common-pile/stackexchange_filtered
What do you call someone who desperately needs (or better said craves) everyone to like them? I have this friend who is in constant search for approval - and not only from his peers, but every single person he meets. He also needs to be the center of attention. Psychologically speaking: insecure. I think the most obvious choice would be needy itself: needy adj 2. Wanting or needing affection, attention, or reassurance, especially to an excessive degree. TFD Note that in AmE you will frequently hear the term "high maintenance" ("My girlfriend/boyfriend is so high maintenance!") used as a synonym for needy. Whereas needy has an alternate meaning that refers to someone who is merely poor or disadvantaged, high maintenance has nothing associated with it that absolves its target from blame. Yep, "needy" is definitely used in the US, among younger and especially female folks. As is "high maintenance". Another related term is "drama queen", for someone who always has a crisis which is more important than anyone else's concerns. If you want a more pejorative term, in the US, you would call him an attention whore a more polite version of this is attention hog If they tend to seek approval by trying to please everyone, then you could use sycophant noun a person who acts obsequiously toward someone important in order to gain advantage. (Google) or its synonyms: yes-man, bootlicker, brown-noser, toady, lickspittle, flatterer, flunky, lackey, spaniel, doormat, stooge, cringer, suck, suck-up (Google) Your friend wants to be a cynosure. TFD defines cynosure as a person or thing that attracts notice, esp because of its brilliance or beauty. Your friend may or may not attract every person, but he definitely strives to be one.
common-pile/stackexchange_filtered
How to assign contact Role by code? I have to assign a Role for a Customer? I am creating a Customer, after that, for creating a role, I have already the contact in GlobalAddressBook , I want to add a ROLE for this contact, I don't wanto to create a new record in DirPartyTable. I use this code: DirPartyRelationship::createRecordRelations("Vendor" , CompanyInfo::find().RecId , this.findDirPartyRecid().RecId , curext()); I created a record on Table DirPartyRelationship , but on GlobalAddress form (in HomePage) I can't find the new role for my Vendor. I sow some classes : DirParty , and nother, but I don't know how to use? If I have to use. Is there a class for creating a role by code? I don't know how I to do this. Thanks all, Enjoy! I appreciate your help!! I found one of the possible solution. If I already have a contact (example Vendor o Customer) I have to take its value in field Party and use this value forcing in the same field in the Cust/Vend Table. Exaple: if I have a Customer, go on VendTable, I take the value in Party field. When I create in CustTable my new Customer I force the value taken into in VendTablein field CustTable.Party. Automatically when I create a customer create a new role, with this system associate a Role.(for my Company). If you have more information updated my answer. Thanks all! References: https://community.dynamics.com/ax/f/33/t/170776 ; https://community.dynamics.com/ax/f/33/t/174210?pi51736=1#responses ; https://msdn.microsoft.com/en-us/library/vendtable.aspx .
common-pile/stackexchange_filtered
How do I launch android app from appium though it has permission denied exception I have a scenario to do a mobile automation with the androd app. The issue here is, I am getting Permission denied error when launching through appium. Appium forum suggested that, need to add the android: export= false parameter in their manifest. My question is, Is there any workaround to launch without amending the manifest. Sometimes apps have a specific activity that allows you to enter. It routes you to the main activity. Would be best if you could consult with the developers of the app to provide the activity name.
common-pile/stackexchange_filtered
Inverse Operator Methods for Differential Equations We have learned in class how to use inverse operator methods to solve ODE's (i.e. with the symbolic $D$). E.g, If I were asked to find a particular solution, $y_p$ to $(D-1)(D-2)[y] = x^{2}e^{x}$, then I would use the formula $\frac{g(x)}{D-a} = e^{ax} \int e^{-ax} g(x) dx$, where $g(x) = x^2 e^x$. However, here's the difficulty I'm facing; all the ODE's that we have learned in class with operator methods have been dealing with constant coefficient ODEs, what happens when you have variable coefficients? E.g. the ODE $xy'' +(2x -1)y' - 2y = x^2$ factorises to $(xD-1)(D+2)[y] = x^2$, so a particular solution $y_p$ should be $y_p$ = $\frac{x^2}{(xD-1)(D+2)}$. I can use the method outlined above for the $D+2$ bit, but what about $\frac{1}{xD-1}$? What does the inverse operator $\frac{1}{xD-1}$ mean? Thanks, Ben The reason you can write $$\frac{g(x)}{D-a}=\mathrm{e}^{ax}\int\mathrm{e}^{-ax}g(x)\mathrm{d}x$$ is that $$(D-a)\mathrm{e}^{ax}=0$$ and therefore $$(D-a)\left(\mathrm{e}^{ax}\int\mathrm{e}^{-ax}g(x)\mathrm{d}x\right)=g(x)\;.$$ You can generalize this for any operator of the form $s(x)D-t(x)$ (where in the above case $s(x)=1$ and $t(x)=a$): if you can find $h(x)$ with $(sD-t)h=0$, then the ansatz $$ \begin{eqnarray} (sD-t)\left(h\int gn\mathrm{d}x\right)=shD\int gn\mathrm{d}x=shgn\stackrel{!}{=}g \end{eqnarray}$$ leads to $$n=\frac{1}{sh}$$ and thus to $$\frac{g}{sD-t}=h\int \frac{g}{sh}\mathrm{d}x\;.$$ For instance, if we generalize your case slightly to inverting $xD-a$, i.e. $s=x$ and $t=a$, then $h$ must satisfy $(xD-a)h=0$. That leads to $h=x^a$, and thus to $$\frac{g}{xD-a}=x^a\int x^{-a-1} g\mathrm{d}x\;.$$ @RobertIsrael Hi Guys thanks for all your answers it really helps a lot. But one thing I don't understand. Say I wanted to solve the ODE $(D+2)[y]=g(x)$. Hence a particular solution would be $y_p = \frac{1}{D+2}[g(x)]$. Now from here if I were to expand $\frac{1}{D+2}$ using a series I would get one answer, but if I were to say that $\frac{1}{D+2}[g(x)] = e^{-2x}\int e^{2x} g(x) dx$, I would get a different answer, namely because of the $e^{-2x}$ out in front. Could anyone explain what's happening? Thanks. @David: I don't see why you get a different answer. I believe you can get the same series that you get from expanding $(D+2)^{-1}$ by starting from the integral solution and repeatedly integrating by parts (integrating $\mathrm{e}^{2x}$ and differentiating $g$). First of all, these operators don't commute when there are nonconstant coefficients, so be careful about the orders you put them in. If $(xD - 1)(D + 2) y = g$, that says $ (D+2) y = (xD - 1)^{-1} g$, and then $y = (D+2)^{-1} (xD - 1)^{-1} g$. Now $(x D - 1)^{-1} g$ would be the solution of $(x D - 1) v = g$, namely $x \int \frac{g(x)}{x^2}\, dx$. Hi Guys thanks for all your answers it really helps a lot. But one thing I don't understand. Say I wanted to solve the ODE $(D+2)[y]=g(x)$. Hence a particular solution would be $y_p = \frac{g(x)}{D+2}$. Now from here if I were to expand $\frac{1}{D+2}$ using a series I would get one answer, but if I were to say that $\frac{1}{D+2} = e^{-2x}\int e^x g(x) dx$, I would get a different answer, namely because of the $e^(-2x)$ out in front. Could anyone explain what's happening? Thanks.
common-pile/stackexchange_filtered
List installed sdk package via command line I want to list the installed sdk packages by command lines.(For some reasons I cannot use the GUI) I have done some research and found out several commands to list the available packages on the remote server, but I fail to find any command to list the installed sdk packages yet. Thanks I was looking for this, and found myself this hacky workaround: Could you share your hacky workaround? On windows type the command : %ANDROID_HOME%/tools/bin/sdkmanager --list With Android SDK Tools 25.2.3 (and higher): $ANDROID_HOME/tools/bin/sdkmanager --list See: https://developer.android.com/studio/command-line/sdkmanager.html#usage This lists all packages, installed or not. In its third form, all installed and available packages are printed out. Is there a variant that only returns the installed packages, and returns them in a useful format to reinstall the same package set somewhere else? There's no such variant as far as I know. Installed packages have their own table and the first column lists the package path, that you'll need when installing. So the info is there and just some shell magic is needed to extract it. Alternative commands from here sdkmanager --list --verbose since version 26.0.1 and find ~/.android-sdk/ -name package.xml -exec sh -c 'eval $(xmllint --xpath "//*[local-name()='\'localPackage\'']/@path" $0) && echo $path' {} \; to list only installed packages @DavidBerry sdkmanager --list | sed -e '/Available Packages/q' will quickly just print the installed packages (a "little" bit shorter than @albodelu variant). If you have your path set up, run sdkmanager --list_installed This will print out all the packages installed using sdkmanager. It doesn't work for me, the option isn't avalaible @crgarridos what's your version of sdkmanager? For me, it's 3.0 and I am on windows and the command '--list_installed' is listed by default when I run 'sdkmanager --help' I'm running on v4.0, so probably the option got removed This works on the latest version (v6.0 as of writing this). This should be the accepted answer. For those want to use awk getting the inner paragraph between "Installed packages" and "Aavaliable Packages", but not include "Installed packages" and "Aavaliable Packages" lines. sdkmanager --list | awk '/Installed/{flag=1; next} /Available/{flag=0} flag' see: https://stackoverflow.com/a/38972737/5558764 for detailed description and examples As described in $ANDROID_HOME/tools/android list --help list : Lists existing targets or virtual devices. list avd : Lists existing Android Virtual Devices. list target : Lists existing targets. list device : Lists existing devices. list sdk : Lists remote SDK repository. I guess you are looking for this: $ANDROID_HOME/tools/android list target You can learn more on the android tool in the Command Line Reference. Good luck! Cool, can you share the reference links? This answer did not answer the posters question. I have the same problem. To build my Android project, I want to automatically install the Android SDK and any modules it needs. I don't know how to tell if a module is already installed. In my limited investigation, it appears that: a) you can tell if a certain version of build-tools is installed by looking in the build-tools subdirectory where you installed the Android SDK (e.g. /usr/local/android-sdk-macosx/build-tools), b) perhaps other modules are stored in the add-ons subdirectory, c) target platforms appear to be installed in platforms. As noted, this doesn't answer the question of how to list packages that are already installed. This is listing AVD targets, nothing to do with the Q On my mac just sdkmanager --list was not working, path needed to be specified. Using android studio default SDK location the path is ~/Library/Android/sdk/tools/bin/sdkmanager --list As mentioned by @tnissi this is for Android SDK Tools 25.2.3 (and higher). Or add the path by: export PATH=$PATH:~/Library/Android/sdk/tools/bin in case you need only the installed packages with full names sdkmanager --verbose --list | sed -n '/^Installed packages:$/,/^Available Packages:$/p' It's not quite a listing, but the source.properties files give details of the provenance. I'm using this to compare SDKs on different machines: for i in $(find -name source.properties); do if [ -e ../other.sdk/$i ] ; then echo ========================= $i diff -wu $i ../other.sdk/$i | grep -v Pkg.License fi done I strip Pkg.License because it's hyoooj. A bit old topic but I had similar problem, And noticed that avdmanager lists installed platforms as targets "%ANDROID_SDK_ROOT%\tools\bin\avdmanager" list target Available Android targets:==============] 100% Fetch remote repository... ---------- id: 1 or "android-25" Name: Android API 25 Type: Platform API level: 25 Revision: 3 ---------- id: 2 or "android-28" Name: Android API 28 Type: Platform API level: 28 Revision: 6
common-pile/stackexchange_filtered
Would you put heavy tile floor-to-ceiling over this "blueboard"? We have an upstairs 9x5 bathroom in wooden construction. Ceiling height is 8 feet. Our contractor used a combination of "GoBoard" (concrete-type board) for the shower area, and "blueboard" for the remaining part of the bathroom. We purchased porcelain tile that is 12x24", 5/16" thickness, and this tile is heavy. Each piece of tile weighs about 8.5lb (so about 4.25 per sq ft). We'd like to tile from floor to ceiling to achieve a modern look, but don't want backerboard/tile to fail someday down the road, and come crashing down. The current dilemma is whether to: A. Scale down the plan and tile only a portion of the wall, perhaps the lower 4 feet. B. Ask the contractor to replace the "blueboard" with something stronger. C. Go ahead and tile over the blueboard. Was hoping someone could suggest ballpark figures of safe/unsafe load and if we're thinking correctly here. Many thanks. What you have is done all the time. In some cases it is set on regular drywall, a little weaker than the blueboard. The loading tests the shear strength of the screws and glue that holds the drywall in place, if it has it. If it was done like that on the ceiling, it would be a different matter. @isherwood and Jack, does this answer mean that the loading is near the probable shear strength of the blueboard as currently attached? At this point the only thing that could be done is to drive more screws. Do you think that should that be done? Ordinary drywall is quite strong in shear. It looks adequately fastened from here, but a few extra won't hurt. What is the spacing of the screws on the GoBoard? If the blue board outside the tub/shower surround is to be tiled, then wouldn't one want the same screw spacing there? One problem with tiling to the ceiling is that this increases the difficulty of fastening towel racks, toilet paper dispenser, clothes hooks, but the fastenings would be more secure. Thank you Jack and others for your thoughts. If the blue board is secured sufficiently to the studs, would the outer paper layer be a concern (the bond of the board's paper layer to the inner contents of the board being the weakest link?) Would presence of grout in final installation reduce the stress, with lower tiles somewhat supporting the weight of upper tiles? This is out of scope of the original question, but other concern that came up is the weight onto the building itself (again this is a wooden construction, 3rd floor unit.) Reading suggests that it isn't an issue since the tiles are so close to the studs, and they only compress the extremely strong stud downward without affecting the subfloor below (also, no rotational force, unlike if someone tried to hang an imaginary 270 lb refrigerator.) Regarding the comment about the paper layer, no the shear strength is tremendous as mentioned by isherwood. If it was a ceiling install, then those layers are stressed in a way they were not designed to be stressed. On the loading of the floor system, yes the load is transferred to the floor by the adhesive/thinset to the wallboard, whatever it may be and the grout picking up loading between the tiles, still transferring everything to the floor system. Now the question lies, what can the floor framing handle? IRC has minimums of construction, the builder may have followed or added to it.
common-pile/stackexchange_filtered
How to deploy a Python Azure Function app from a mono-repo? Following on from this question, I've got a mono-repo containing a Flask API and the first of what will be several Azure Function apps. I'm trying to deploy the app to Azure from an Azure DevOps pipeline. How do I deploy the app and tell azure where the entry point is? My python code is structured in a few folders underneath a /backend folder, like ./backend ./backend/domain/ - contains domain logic .py files ./backend/entrypoints/api - contains Flask app files ./backend/entrypoints/my-func - contains my new function app ./backend/... - various other folder hierarchies that are imported. I've got an AzureFunctionApp@2 task and it's pushing a zip of the project up to a Storage Account but I can't see any Functions registered in the Azure Portal. - task: ArchiveFiles@2 displayName: Package Function Apps inputs: rootFolderOrFile: $(Build.SourcesDirectory) archiveType: 'zip' archiveFile: '$(Build.ArtifactStagingDirectory)/nightly-import-$(Build.BuildId).zip' verbose: true - task: AzureFunctionApp@2 displayName: Deploy Nightly Importer inputs: azureSubscription: ${{parameters.azureServiceConnection}} appType: functionAppLinux appName: nightly-import-${{parameters.environmentMoniker}}-uks-01 package: '$(Pipeline.Workspace)/FuncAppsPackage/nightly-import-$(Build.BuildId).zip' deploymentMethod: auto verbose: true How do you publish a function app from within a mono-repo in such a way that all dependencies are deployed, including pip packages from the venv and 1st party python modules from outside the function app folder (my backend/domain and other modules)? Check if this article helps. @PravallikaKV I'm not sure it does. I can see they're zipping a sub-package but where are they saying "include all the other module and pip packages" (obviously they're using JS so they don't have pip packages). To deploy the Mono repo to Azure function app, configure rootFolderOrFile to the function directory in the workflow. YAML pipeline: - task: ArchiveFiles@2 displayName: 'Archive files' inputs: rootFolderOrFile: '$(Build.SourcesDirectory)/backend/entrypoints/my-func/*' # Path to your Function App code includeRootFolder: false archiveType: 'zip' archiveFile: '$(Build.ArtifactStagingDirectory)/$(Build.BuildId).zip' replaceExistingArchive: true - publish: $(Build.ArtifactStagingDirectory)/$(Build.BuildId).zip artifact: drop - task: AzureFunctionApp@1 displayName: 'Azure Functions App Deploy' inputs: azureSubscription: '$(azureSubscription)' appType: 'functionAppLinux' appName: '$(functionAppName)' package: '$(Pipeline.Workspace)/drop/$(Build.BuildId).zip' I have deployed the same using GitHub actions: Workfow: name: Build and deploy Python project to Azure Function App - appname on: push: branches: - main workflow_dispatch: env: AZURE_FUNCTIONAPP_PACKAGE_PATH: 'backend/entrypoint/my-func' PYTHON_VERSION: '3.11' jobs: build: runs-on: ubuntu-latest steps: - name: Checkout repository uses: actions/checkout@v4 - name: Setup Python version uses: actions/setup-python@v5 with: python-version: ${{ env.PYTHON_VERSION }} - name: Create and start virtual environment run: | python -m venv venv source venv/bin/activate - name: Install dependencies run: | pip install -r requirements.txt # Optional: Add step to run tests here - name: Zip artifact for deployment run: | mkdir -p package cp -r ${AZURE_FUNCTIONAPP_PACKAGE_PATH}/* package/ cp requirements.txt package/ cd package zip -r ../release.zip . - name: Upload artifact for deployment job uses: actions/upload-artifact@v4 with: name: python-app path: release.zip deploy: runs-on: ubuntu-latest needs: build environment: name: 'Production' url: ${{ steps.deploy-to-function.outputs.webapp-url }} steps: - name: Download artifact from build job uses: actions/download-artifact@v4 with: name: python-app - name: Unzip artifact for deployment run: unzip release.zip -d deployment - name: List files in deployment directory run: ls -R deployment - name: Deploy to Azure Functions uses: Azure/functions-action@v1 id: deploy-to-function with: app-name: 'appname' package: 'deployment' scm-do-build-during-deployment: true enable-oryx-build: true publish-profile: ${{ secrets.AZUREAPPSERVICE_PUBLISHPROFILE_C8CFCXXXXDCC }} Deployed to Azure: Portal: Thanks for the response @pravallikakv, but the function app references modules outside of it's root folder, e.g. in the /backend/domain folder, so they need to be bundled too, along with any pip dependencies. As I have shown in the GitHub workflow, it copies therequirements.txt folder(from root directory) too where I have function modules. @GregB, Are you able to deploy? If not, please share your repository link(excluding sensitive information), I'll try to deploy from my end.
common-pile/stackexchange_filtered
Lagrange Multipliers with $f\left(x,y\right)=x^2-y^2$ and "constraint" $g\left(x,y\right):=2y-x^2=0$ I am working on a problem from my textbook on Lagrange Multipliers. I feel I have these down now, but I am curious about this specific problem. Let \begin{align} f\left(x,y\right)=x^2-y^2\tag{1},\\ \text{and}\;g\left(x,y\right):=2y-x^2=0.\tag{2} \end{align} The first part is easy. Since $g$ is the "constraint" as they call it, we have \begin{align} \vec{\nabla}f\left(x,y\right)&=\begin{bmatrix}2x\\-2y\end{bmatrix},\tag{3}\\\lambda\vec{\nabla}g\left(x,y\right)&=\begin{bmatrix}-2x\lambda\\2\lambda\end{bmatrix}.\tag{4} \end{align} This gives us the set of equations \begin{align} 2y-x^2&=0,\tag{5}\\ 2x&=-2x\lambda,\tag{6}\\ -2y&=2\lambda\implies \lambda=-y,\tag{7} \end{align} and substituting $\left(7\right) $ into $\left(6\right)$ gives us $y=1$, meaning $x=\pm\sqrt{2}$. Then putting these points into the original equation $\left(1\right)$ gives me $\left\{\left(\sqrt{2},1,1\right),\left(-\sqrt{2},1,1\right)\right\}$, and I have graphed to confirm. But now what about $\left(0,0,0\right)$? It appears to be a relative minimum when I graph these two surfaces, but how do I get it to show up in my Lagrange Multipliers (unless it is not done in that way). I do notice initially that $\left(0,0,0\right)$ does satisfy both equations $\left(1\right)$ and $\left(2\right)$, however. But it does not seem this is impetus for being min alone. Thank you for your time, You have to make sure when solving the equations that you are not dividing by something that is zero. Having done your substitution for $\lambda$, you are left with $$ y-x^2=0 \\ 2x=2xy, $$ and if $x=0$, the second equation is satisfied, and then the first equation gives $y=0$.
common-pile/stackexchange_filtered
Testing whether mean sample difference between two groups is different in two different samples Suppose in a medical study there are the following students recruited to the study: 300 Japanese males, 500 Japanese females 600 Australian males, 700 Australian females The particular study is about if height difference between gender is more pronounced in countries with certain socio-economic institutional structure We do a unpaired t-test for the Japanese students, say the height difference between gender is 3cm We do a unpaired t-test for the Australian students, say the height difference between gender is 1.5cm How can we test if the Japanese gender height difference is more pronounced than that in Australia? Which statistical test would be suitable for this purpose, if you don't mind showing me the exact step-by-step calculations?
common-pile/stackexchange_filtered
Explanation of tac --before -b, --before The separator is attached to the beginning of the record that it precedes in the file. And I can't understand the following output: $ echo -e "Hello\nNew\nWorld\n!" > file $ tac file ! World New Hello $ tac -b file ! World NewHello Why there is no newline between New and Hello? tac works with records and their separators, attached, by default after the corresponding record. This is somewhat counter-intuitive compared to other record-based tools (such as AWK) where separators are detached. With -b, the records, with their newline attached, are as follows (in original order): Hello \nNew \nWorld \n! \n Output in reverse, this becomes \n\n!\nWorld\nNewHello which corresponds to the output you see. Without -b, the records, with their newline attached, are as follows: Hello\n New\n World\n !\n Output in reverse, this becomes !\nWorld\nNew\nHello\n That does look strange partly due tac works in somewhat counter-intuitive way as to me. Let's make use of clearly visible separators — commas. What would I expect to see as the result of the following command: % echo -ne 'A,B,C' | tac -s, ? Well, I see it as there's A separated from B separated from C. Thus (I conclude) being printed in reverse, they should constitute C,B,A. Let's check. Alas, it prints differently instead: % echo -ne 'A,B,C' | tac -s, CB,A, We can conclude tac sticks for original separators placement: A still has it afterwards, as well as B does, but C didn't have it and hence it's printed as is. What happens if I run tac with -b this time? % echo -ne 'A,B,C' | tac -bs, ,C,BA Seemingly it works this way for -b: it's going through the input in backward direction till it finds a separator. As it's found it's printed: ,. Then it prints the text it skipped while searching: C. Then the cycle repeats: ,B. As there're no separators left, just the remainder is printed: A. Why there is no newline between New and Hello? According to the explanation I've given above New would be on a new line because it was prefixed with new-line, but since Hello wasn't — it'd be printed as is. Regarding your first part, it helps to understand tac’s counter-intuitive behaviour if you consider that its initial goal was to reverse text files, which end with a \n. The configurable separator does suggest that it can reverse records separated by arbitrary characters, in which case you don’t expect the text to end with a separator, but it doesn’t work that way :-(. Your explanation of -b is a fairly accurate description of coreutils’ implementation of tac; note however that tac always searches backwards (even without -b). Indeed tac is always tac, even w/o -b
common-pile/stackexchange_filtered
Word Riddler - What am I? When we start, I'm an animal inside an animal. I got a name, just gotta build it. Change a letter and double one that I have, roll me around, oh wait, don't take that! Alright let's come back to the big state because I'm not a fan of that! Now that we're here, let's look ahead. I guess you need me before all else. What am I? HINT If making a building is something you wish, you'd better use me in order to flourish. HINT 2 Based in ND but part of SK, I help with farms in the U S of A. Only reasonable google result :p Keep searching :-) I think you are a Bobcat When we start, I'm an animal inside an animal. Bobcat has "cat" inside "bobcat". I got a name, just gotta build it. Bobcat has got the name "Bob" in it. Just gotta build it presumably references Bob the Builder. Change a letter and double one that I have, roll me around, oh wait, don't take that! bobcat → bobccat [double c] → oobccat [b→o] and anagram to tobacco and "roll around" is both anagrind and play on words for rolling tobacco. Thanks @M Oehm for contributing this in the comments. Alright let's come back to the big state because I'm not a fan of that! (From OP:) "Let's come to the big state" is a reference to the song "Ohio (Come back to Texas), and you are not a fan of the Ohio BOBCATS! Now that we're here, let's look ahead. I guess you need me before all else. (From OP:) Look ahead means scouting, and in boy scouts, the BOBCAT badge is the first badge required. HINT If making a building is something you wish, you'd better use me in order to flourish. Bobcat, for construction. HINT 2 Based in ND but part of SK, I help with farms in the U S of A. The Bobcat Company fits this description. The thing that you shouldn't take could be tobacco: Duplicate the c, change one b to an o and scramble. And the "roll around" could hint at rolling cigarettes. @MOehm Ooh! Thanks, I looked at a lot of words but missed that one. Well, I'm not super sure it's correct, because it also works the other way round: Duplicate the o and change a b to a c. Right on :) The 4th and 5th lines fit better than the description you gave, but if you want I'll be willing to edit it with the right reasoning Very Partial When we start, I'm an animal inside an animal. This has multiple possibilities like - Fox , Kangaroo, Reindeer, Numbat, Dormouse, Bobcat Change a letter and double one that I have, roll me around, oh wait, don't take that! If I take Fox $\rightarrow$ Fol(Replace a letter) $\rightarrow$ Fool(Double letter o) $\rightarrow$ Fool Around? Now, I'm not sure what needs to be done for the next step. Also, not sure if the second step is right or wrong. Hope someone else can figure it out. "Roll me around" might mean to anagram it. Just realized this after reviewing my post from yesterday. An anteater is an animal in an animal in a double sense (the ant is in the anteater's stomach). Potential answer with not-quite-complete reasoning: Aardvark When we start, I'm an animal inside an animal. Start with meadowlark. Meadowlark is an animal with owl inside it. I got a name, just gotta build it. Change a letter and double one that I have, roll me around, oh wait, don't take that! Change the l to a v and double the first a: Meaadowvark.Not sure about this piece, but add an r so you have me and r (for "roll") "around" the double letter: meaardvark. Now remove "ow" for "oh wait" => Meaardvark. Alright let's come back to the big state because I'm not a fan of that! Not sure about this part. Maybe just that we're looking at the whole word again instead of the individual pieces? Now that we're here, let's look ahead. I guess you need me before all else. Looking ahead, past the "me" at the beginning, so drop the "me" and get "aardvark". I feel like this is right but my reasoning is off in a few places. This is certainly some good logic, but it's not the answer I was looking for. My answer fits every part of the riddle perfectly (at least I hope so) :-) I'm just gonna guess on the word being BABY An animal inside an animal: I'm just assuming that humans could be considered to be an animal I got a name, you just gotta build it: Name given on birth perhaps Not sure about the word as I dont know what things are called in English, but roll the baby around and dont take it's feeding bottle or pacifier(according to google translate) Alright let's come back to the big state because I'm not a fan of that: Dont know what come back to the big state means Now that we're here, let's look ahead: To the future I guess you need me before all else: Need babies to not get extinct This is good logic, but not what I'm looking for sorry. Try following Techidiot's partial answers ;-) You are A Head. Every part of the clue seems to fit, but the letter-scrambling bit seems a bit arbitrary. Reasoning: (Starting from the bottom) I guess you need me before all else. I guess I need my head. Ahead means "before all else". Now that we're here, let's look ahead. Direct mention of "ahead" Alright let's come back to the big state because I'm not a fan of that! Nobody likes big-headedness I got a name, just gotta build it. Change a letter and double one that I have, roll me around, oh wait, don't take that! Since this bit is so very flexible, there are most likely several ways to end up at whichever word from an animal. Here's one that ends up in "A Head": Hare -> (change a letter) Hade -> (double the a) Haade -> (roll around, as in anagram) Ahead -> (oh wait, take another anagram) -> A Head When we start, I'm an animal inside an animal. A hare is an animal inside a harehound, for example. Well, that's the best I've got. I Am a... DNA I'm an animal inside an animal. Live inside body I got a name, just gotta build it. Deoxyribonucleic acid , build helical chains Change a letter and double one that I have, roll me around, oh wait, don't take that! GC base pair with three hydrogen bonds. Bottom, an AT base pair with two hydrogen bonds. Now that we're here, let's look ahead. I guess you need me before all else. A hereditary material in almost all other organisms. Nope, sorry not it :) Here's a partial answer... I am a... Elephant ("Ant" is an animal, inside "Elephant", another animal) I got a name, just gotta build it. Carpenter ant Change a letter and double one that I have, roll me around, oh wait, don't take that! Unsure... Alright let's come back to the big state because I'm not a fan of that! Unsure... Now that we're here, let's look ahead. Anticipate I guess you need me before all else. Antecedent
common-pile/stackexchange_filtered
Clock battery broken on Solaris - how to workaround until I can fix the battery My main Solaris server has an issue with its battery and thus I lose around 20 seconds per day. Currently I am using rdate once in the morning to synchronise the time. Which approach should I use until I can change the battery on a weekend? Should I switch from rdate to ntp? The machine runs plenty of cronjobs and thus I need to ensure that everything is started even when the time is changed. You should definitely run ntpd. Not only it automatically synchronizes with one or several servers, if you leave it running for a while, it calculates a correction factor for your hardware clock and can keep quite accurate time even if you lose connectivity to your time server(s). The main issue with rdate however that it sets the correct time immediately. Suppose it's 10:30, but your server's clock shows 10:25. If you set the time, you effectively lose 5 minutes. NTP on the other hand adjusts time gradually. To clarify that second comment: You (usually) want the time to be updated immediately at first, especially in your case where it's likely to be so incorrect. So the init script for ntpd should run rdate once to "jump" to the right time and then run ntpd to keep it in sync. Exactly, sorry I wasn't clear on that.
common-pile/stackexchange_filtered
Restsharp return null when Response have location header only, no body i am using RestSharp to consume the CapsuleCRM API. When you POST to create an entity, the API does not return anything in the body of the response, only a location header to the newly created row. Like so: http://developer.capsulecrm.com/v1/writing/ HTTP/1.1 201 Created Location: https://sample.capsulecrm.com/api/party/1000 So, if RestSharp is to be able to return an object, it must follow that location header url, and retrieve the new object from there, but this does not seem to be happening. This questions is similar to a different question, but not a duplicate: RestSharp returns null value when response header has location field Update: I have posted a hacky solution I came up with as an answer, but is there really no way for RestSharp to handle this by default? Please post your solution as an answer, not an update to your question. If you still want a better answer, leave your question open and people will provide one if they have one. Please also share sample code for both your question and solution. I was able to make this work by making a tweaked version of the public T Execute<T>(RestRequest request) where T : new() method, but it really feels like there should be a better solution to this. Source code at: https://github.com/bjovas/CapsuleDotNet/blob/master/src/CapsuleDotNetWrapper/CapsuleApi.cs public T CreateExecute<T>(RestRequest request) where T : new() { var client = new RestClient(); client.BaseUrl = BaseUrl; client.Authenticator = new HttpBasicAuthenticator(_authtoken, "x"); var response = client.Execute<T>(request); string locationUrl = (string)response.Headers.Where(h => h.Type == ParameterType.HttpHeader && h.Name == "Location").SingleOrDefault().Value; int id; if (int.TryParse(locationUrl.Remove(0, string.Format("{0}{1}", client.BaseUrl, request.Resource).Length), out id)) { var secondRequest = new RestRequest(); secondRequest.Resource = locationUrl.Remove(0, string.Format("{0}", client.BaseUrl).Length); secondRequest.RootElement = request.RootElement; return Execute<T>(secondRequest); } else throw new ApplicationException("Could not get ID of newly created row"); }
common-pile/stackexchange_filtered
How to find total number of friends groups I have a friendship graph as follows I want to find all the possible group of friends. What is the best algorithm to find these grouping. For example in this graph , possible friendship groups are as follows: 1,2,3,4,12,13,23,123,14,143,124,1234 If I use brute-force algorithm (starting from each vertex and do this 4 times), it generates lots of duplicates. could you provide a format for your graph data ? note that the most interesting question would be, how to find a linear algorithm which introduces the fewest number of errors ( and defining an error count function ) @igael I would prefer to store it as adjacency list because graph could be sparse in most cases. no problem, provide a format ( while the question remains : "find the number" and not "enumerate them" ) According to the Wikipedia it's NP-complete so you can only use brute-force for detecting such sets. The problem is called Clique problem and is one of first identified NP-complete problems. Yes it is NPH. I am looking for faster algorithm for sparse graph. Thanks I will check it According to the OP, 1234 is also a friendship group, but that is not a complete subgraph. OP's problem seems to me to find all possible connected components @NARAYANCHANGDER is 1234 ok? yes 1234 is a part of solution. In given graph the answer is 1,2,3,4,12,13,23,123,14,143,124,1234. @NARAYANCHANGDER how is 4 friend with 3? @bk2dcradle the problem is , if we count all possible connected components then for 1-2-3-1 we will get 123 as well as for 1-2-3 we will again get 123. hence, duplicate occurs. @xenteros 4 is not direct friend of 3 but if common friend 1 joins then 143 form a group. @xenteros if we pick 1, adjacent of 1 are 2,3 and 4 now 34 is a subset of 234. I posted the same thing in your previous answer but you deleted it. Could you please elaborate again your procedure. I am sorry if I could not get your answer. Thanks
common-pile/stackexchange_filtered
How to change the API Name of the Utility bar of custom application I have a custom application that i created, but I prefixed my custom application as XYZ_MYAPP, which was carried over to my utility bar setting and utility bar was named as XYZ_UTILITYBAR. now i want to change the prefxi to ABC. Changing the api name of the custom application is not changing the api name of the utility bar. I was trying to find a way to change the api name of the utility bar Can you provide an example screenshot? Utility bar is just a type of FlexiPage and is actually its own metadata even though, in the UI, Salesforce is basically creating/updating this for you through the Utility Items menu item when editing a custom application. The fact that Salesforce is doing this for you though means you're limited, in the UI, to what they provide. In this document, it mentions how the utility bar you created through the Lightning App Builder is linked to only that application (and you can only add or edit a utility bar through this). By edit, it's just the items that appear. However, that same document mentions you can associate a Utility Bar deployed through API to multiple Apps. That's your only option for existing apps (or, otherwise, you could've just created a new CustomApplication in the UI versus renaming an existing one). As it's referenced in CustomApplication by name, you'd need to update the CustomApplication after the fact to point to the new Utility Bar page. So the following steps should help you achieve what you want if the name is that important: Create a new FlexiPage with the desired name and copy the contents of the existing FlexiPage for the uitlitybar Change <masterLabel> to be your new name as well without the underscores. Deploy the page Modify the <utilityBar>newName_UtilityBar</utilityBar> part of your CustomApplication to use the new name and deploy.
common-pile/stackexchange_filtered
Constrained optimization where the choice is a function over an interval I would like to solve a constrained optimization problem where the choice is a function over an interval rather than a finite number of variables or a sequence. The problem is given by: $\max_{[x(i)]_{i=0}^1} \int_{i=0}^1 f(x(i))di$ subject to $\int_{i=0}^1 x(i)di = X$ where $x(i) > 0, \forall i \in [0,1]$, and $f:\mathbb{R}^{++}\rightarrow\mathbb{R}$ is a twice differentiable, strictly increasing and strictly concave function, i.e. $f'(x) > 0$ and $f''(x) < 0, \forall x \in \mathbb{R}$. An example would be $f(x) = \ln(x)$. I intuitively know that a solution is $x(i) = X, \forall i \in [0,1]$. I also can see that $x(i) = X$ must be true almost everywhere for any solution. Mimicking the heuristics of constrained optimization problems where the choice is over a countable number of points, I would assign a multiplier $\lambda$ to the constraint, and then obtain a candidate solution by: $\frac{\partial}{\partial x(i)}\left(f(x(i))\right) + \frac{\partial}{\partial x(i)} \left(-\lambda x(i)\right) = 0, \forall i \in [0,1]$ $f'(x(i)) = \lambda, \forall i \in [0,1]$ $x(i) = x(j) \equiv x, \forall i,j \in [0,1]$ $\int_{i=0}^1 xdi = X \Rightarrow x = X = x(i), \forall i \in [0,1]$ However, I do not know how to prove this, or which theorem to invoke. If the choice variable was a sequence, I would use Karush-Kuhn-Tucker. Which theorem should I use when the choice is a function over an interval rather than a sequence? What is the general name for this type of constrained optimization problem? Thanks a lot in advance. Generally it is a good idea to frame the question in terms of some 'well known' space. In this case, the $x$ must be integrable, so at a first cut, we take $x \in L^1[0,1]$. Your intuition is correct, and we can proceed directly or by using standard techniques such as Lagrange multipliers. It is generally more difficult with such problems to assert the existence of extrema. In this particular example we can appeal to convexity (through Jensen's inequality) to show that the average is the extremising value. Given that we know that an $\max$ exists, we can use Lagrange multipliers to compute a solution. One version of the theorem requires that the constraint function $g$ be surjective. The problem is (slightly relaxed) $\min \{ f(x) | g(x) = 0 \}$ where $x \in L^1[0,1]$, $f(x) = \int f \circ x$, and $g(x) = \int x$. We see that $g$ is surjective. It is straightforward to compute ${\partial f(x) \over \partial x}h = \int {\partial f(x(t)) \over \partial x} h(t) dt$ and ${\partial g(x) \over \partial x}h = \int h(t) dt$ and it is straightforward to check that derivatives are continuous. Then at a $\max$, say $x^*$, there exists a multiplier $\lambda$ such that ${\partial f(x^*) \over \partial x} + \lambda {\partial g(x^*) \over \partial x} = 0$. This reduces to ${\partial f(x^*(t)) \over \partial x} + \lambda = 0$ for ae. $t$. Since $f$ is strictly monotonic, we conclude that there is some constant $c$ such that $x^*(t) = c$ for ae. $t$ and from $g(x^*) = X$ we get $c= X$. Thank you very much for your answer. Could you also please tell me: (1) What is this type of problem generally called? (2) Do you know of any theorems such as Kuhn-Tucker that would declare under which conditions the Lagrangian heuristics result in (a.e.) necessary conditions? I feel like I can jury-rig a proof in this case by reformulating this as an optimal control problem and using Pontryagin's Maximum Principle, but I would like to know the more general theorem when I cannot immediately turn the constraint into a differential equation. I am not sure there is a general name, I suppose optimal control would be reasonable. I am no expert in this area. The Lagrange multiplier theorem is not a heuristic, it does provide necessary conditions (perhaps I missed your point?). (Note that Pontryagin's maximum principle is pretty big guns!) Showing that a solution exists is often a significant problem. The Lagrange multiplier method delivers necessary conditions under certain assumptions regarding the problem. If I were choosing $x \in \mathbb{R}^{k}$ with $k \in \mathbb{N}$, I would have used the Karush-Kuhn-Tucker theorem to claim that the first order conditions with respect to x were necessary conditions for a solution. For this problem, I do not know which theorem I can rely on, which is my main problem. There are a variety of Lagrange multiplier theorems set in banach space. "Lagrange multipliers on Banach spaces" -- this is exactly what I was looking for! Since the space of continuous functions over an interval with $L^p$ norm is a Banach space, this would definitely resolve my issue. Thanks a lot! I don’t think you need any of those fancy stuff here: the objective is a convex combination of function $f$ evaluated at infinite number of points. By Jensen’s inequality and due to concavity of f, the convex combination of f is less than f of the convex combination which is $X$ by the constraint. So the optimal value is less than X and is attainable too. Yes, I am aware of that. What I want to learn about is the theorem that works for a more general case. For instance, consider the objective function $\int_{i=0}^1 a(i) f(x(i)) di$ with some $a:\mathbb{R}^{++}\rightarrow\mathbb{R}^{++}$. The necessary conditions in this case would be $a(i) f'(x(i)) = \lambda, \forall i \in [0,1]$ almost everywhere. I thought a little more about the problem, and I guess one could formulate it as an optimal control problem by defining a state variable such that the last constraint works.
common-pile/stackexchange_filtered
Are there some projects that rate RPG source? like software metrics? I just wanted to know if you know of some projects that can help to decide whether the analyzed Source it is good code or bad RPG code. I'm thinking on the terms of Software metric, McCabe Cyclomatic Number and all those things. I know that those numbers are mere a hunch or two, but if you can present your management a point score they are happy and i get to modernize all those programs that otherwise work as specified but are painful to maintain. so yeah .. know any code analyzers for (ILE)RPG ? Note that this technically seems to be off-topic due to asking to recommend or find a book, tool, software library, tutorial or other off-site resource. We have developed a tool called SourceMeter that can analyze source code conforming to RPG III and RPG IV versions (including free-form as well). It provides you the McCabe Cyclomatic Number and many other source code metrics that you can use to rate your RPG code. If the issue is that the programs are painful to maintain, then the metric should reflect how how much pain is involved with maintaining them, such as "time to implement new feature X" vs "estimated time if codebase wasn't a steaming POS". However, those are subjective (and always will be). IMO you're probably better off refactoring mercilessly to remove pain points from your development. You may want to look at the techniques of strangler applications to bring in a more modern platform to deliver new features without resorting to a Big Bang rewrite. The SD Source Code Search Engine (SCSE) is a tool for rapidly search very large set of source code, using the langauge structure of each file to index the file according to code elements (identifiers, operators, constants, string literals, comments). The SD Source code engine is usable with a wide variety of langauges such as C, C++, C#, Java ... and there's a draft version of RPG. To the OP's original question, the SCSE engine happens to compute various metrics over files as it indexes them, including SLOC, Comments, blank lines, and Halstead and Cyclomatic Complexity measures. The metrics are made available as byprooduct of the indexing step. Thus, various metrics for RPG could be obtained. As of today (6 years later) there is still no RPG support. RPG is still only listed on the "tools in development" page. Sorry to disappoint. Sometimes things don't work out as expected :-{ The demand isn't very high (note that Front End Arts just added one 6 years after this answer!) We still have draft RPG support; it handles a generic version of RPG, but not any specific dialect completely. We have actually used it on a custom project, but won't mark it as available until we do handle a specific dialect completely. You can probably tell we've been busy with lots of other languages and tools.
common-pile/stackexchange_filtered
Not able to remove .xcworkspace even after running pod clean commands I am trying to remove pod dependency for committing in to gitlab I am referring Remove or uninstall library previously added : cocoapods when I do pod clean it is showing Unknown command: clean pod clean I am expecting to remove pod files while committing and after taking checkout I want to get pod file by running pod install You can add pods to your gitignore file. https://stackoverflow.com/a/34239746/5084797 pod file is getting removed when I do pod deintegrate, but pod clean is not working cocoapods-clean's (pod clean) github source appears to have been renamed, you can find it here now but all it does is: rm -rf Podfile.lock Pods *.xcworkspace. Please try below commands to clear all pod data. Also to ignore pod file while committing to git you can add pod folder path in .gitignore (hidden file) to ignore specific folder on code push. pod cache clean --all pod deintegrate OR rm -rf ~/Library/Caches/CocoaPods rm -rf Pods Also clear derived data of that app. I tried pod cache clean --all but .xcworkspace still exist @mobileapps can you update all the commands you have used to deintegrate pod?? Also I have edited may answer. sudo gem install cocoapods-clean pod deintegrate pod cache clean --all Same order I used Ok. Hope this url helps you https://stackoverflow.com/questions/16427421/how-to-remove-cocoapods-from-a-project
common-pile/stackexchange_filtered
Swift - Sample - How to play beep sound before and after recording using AVAudioRecorder? I want to implement similar record button like Whatsapp in iOS using Swift, where when user holds the button down, a beep sound indicates start, after which recording starts and when user releases the button, recording stops and another beep sound indicates recording finished. I tried implementing this feature using the following code: func startRecording(sender: UIDataButton?, callData: NSDictionary?) -> Bool { do { if (self.audioRecorder == nil) { AudioServicesPlayAlertSound(1110) // JBL_Begin self.audioSession = AVAudioSession.sharedInstance() try self.audioSession.setCategory(AVAudioSessionCategoryPlayAndRecord, withOptions: .MixWithOthers) try self.audioSession.setMode(AVAudioSessionModeVoiceChat) try self.audioSession.setActive(true) if (sender != nil) { dispatch_async(dispatch_get_main_queue(), { () -> Void in sender!.setTitle("Recording...", forState: .Normal) }) } try self.audioRecorder = AVDataAudioRecorder(URL: self.fileURL("\(CurrentTimestamp)_aud.mp4")!, settings: self.recordSettings) if (sender != nil) { self.audioRecorder.setRecorderSender(sender!) } if (callData != nil) { self.audioRecorder.setRecorderData(callData!) } self.audioRecorder.delegate = self if (self.audioRecorder.prepareToRecord()) { if (self.audioRecorder.record()) { NSLog("audioRecorder started recording") return true } else { self.audioRecorder = nil NSLog("audioRecorder not started") return false } } else { NSLog("audioRecorder failed to prepare") return false } } } catch let error as NSError { print("Error \(error.debugDescription)") if (self.audioRecorder != nil) { self.audioRecorder.stop() self.audioRecorder = nil } return false } return false } func finishRecording(sender: UIDataButton?) -> AVDataAudioRecorder? { var recorder: AVDataAudioRecorder? = nil if self.audioRecorder != nil { self.audioRecorder.stop() NSLog("audioRecorder stopped recording") recorder = self.audioRecorder AudioServicesPlayAlertSound(1111) // JBL_End self.audioRecorder = nil do { try self.audioSession.setActive(false) } catch let error as NSError { print("Error - AudioSession setActive False failed - \(error.debugDescription)") } if (sender != nil) { dispatch_async(dispatch_get_main_queue(), { () -> Void in sender!.setTitle("Push-to-Talk", forState: .Normal) }) } } But the problem is that the JBL_Begin alert sound never plays. Also, when I try to playback the recorded audio after recording, the volume of the audio is very low. Here is my code: func pressAudioControl(sender: UIButton!) { if audioPlayer.playing { audioPlayer.pause() self.imageView.image = UIImage(named: "MessagePlay") } else { do { self.audioSession = AVAudioSession.sharedInstance() try self.audioSession.setCategory(AVAudioSessionCategoryPlayAndRecord, withOptions: .DefaultToSpeaker) try self.audioSession.setActive(true) self.audioPlayer.volume = 1.0 audioPlayer.play() self.imageView.image = UIImage(named: "MessagePause") } catch let error as NSError { print("audioPlayer error \(error.debugDescription)") } } } Any idea why this problem occurs? Have you found solution for this? @Nij I'm probably a little late but I answered below. This is due to your AVAudioSession being active when you attempt to play your system sound. You need to play your system sound with completion, then set it to true and begin recording. AudioServicesPlaySystemSoundWithCompletion(SystemSoundID(1110)) { //Recording method here } Inside the completion block is where you will run you recording method including: try self.audioSession.setActive(true) Then before playing your ending system sound make sure to set it back to false. try self.audioSession.setActive(false)
common-pile/stackexchange_filtered
The repetition pattern of a random integer sequence Here is a problem that bothers me, could some one grand me some help? There is a sequence of N random integers, {$X_1,X_2,...,X_N$}. Each $X_i$ is uniformly chosen from a integer set {1,...,M}. For each specific values of the sequence, {$x_1,x_2,...,x_N$}, if there exits repetition, we put the all the duplicated variables in a bag. For example, when N = 6, M = 7, if the sequence is {$x_1=1,x_2=1,x_3=2,x_4=2,x_5=3,x_6=6,x_7=3$}, we put $x_1,x_2,x_3,x_4,x_5,x_7$ in the bag, and the bag size is 6 since we have 6 duplicated variables. My question is that, what is the average bag size? I know this can be solved by writing a simple program, but I am wondering if there exits an function relationship between N, M, and the average bag size. Thank you! Got something from an answer below? Each $x_i$ is not put in the bag if the $N-1$ other $x_j$ are different from $x_i$. This happens with probability $\left(1-\frac1M\right)^{N-1}$. This probability does not depend on $i$ hence the mean number of variables put in the bag is $$ \sum_{i=1}^NP[x_i\ \text{is put in the bag}]=N\cdot\left(1-\left(1-\frac1M\right)^{N-1}\right). $$
common-pile/stackexchange_filtered
There is something about bell To his great astonishment, the heavy bell went on from six to seven, and from seven to eight, and regularly up to twelve; then stopped. (A Christmas Carol) What does it mean? I think the clock is going like 6 to 12. Or isn't it? Yes, the bell is going from 6 to 12. The author phrased it in that way to show that the bell was going number by number, from 6 to 12 in regular intervals. (think number line) So the bell is ‘jumping’ from 6 to 7, then 7 to 8, then 8 to 9, then 9 to 10, then 10 to 11, then finally 11 to 12 instead of going from 6 to 12 without stopping. i am not acquainted with English bell. I can't imagine it. I am foreigner. So can you be more specific? (If it isn't inconvenient, can u include a picture?) @ErkhesNyamsaikhan This video shows a tower clock mechanism first playing its quarter chime (the chime plays every quarter hour), then striking the bell 12 times, which it does on hours only, for 12 noon.
common-pile/stackexchange_filtered
How would a keylogger bypass Wireshark sniffing? I often see malicious keyloggers being advertised as having anit-wireshark feature. Meaning their data can't be sniffed. Is it possible to do so? How would they do it? My guess is that they just check if Wireshark is running and don't send logs if Wireshark is running. So, this wouldn't work if you are capturing packets using a router or another computer. Am I right? No a keylogger won't check if a packet sniffer is running on the spied upon system. Just for the reason you guessed (a packet sniffer is never used on a suspected OS). Actually, I've played with a keylogger called "Gh0st Logger" and it does exactly what you're describing. If it detects that Wireshark is running, it doesn't send logs. Quite stupid technique, if you ask me. @Adnan: IMHO it's not as stupid as sending logs even if Wireshark is running. Maybe lazy, but not stupid. Normal users run wireshark only on their computer. @Adnan: Also it makes them to qualified to advertise the product as "Anti-Wireshark" which makes the script kiddies buy it thinking that they are immune. If an attacker roots a system they can install drivers which will hide malicious traffic from sniffers like wireshark, tools like netstat, or process utilities like task manager or PS. An attacker could have keyloggers, spam bots, ddos tools, anything they like running on a system and even administrators would be completely oblivious unless they ran an external sniffer. Meaning their data can't be sniffed. Is it possible to do so? How would they do it? One plausible way of accomplishing this is encrypting the data before sending it out. To the perspective of the packet sniffer, the data will appear as an encrypted stream without knowing what actually is being sent. The server receiving the data stream can then decrypt the data stream to obtain the actual data being sent. Some Googling suggests that at least some "anti-Wireshark" measures just look for processes running on your system named "Wireshark" and shutting them down. I hate to start out an answer like this, but I do not know if my answer will be 100% correct because there are many ways this could be done. One way could be to hook a DLL into predetermined sniffing processes like wireshark and then make modifications to the process memory to not display any packets being sent to a specific IP Address (the IP Address which is monitoring the keylogger). I'm sure there are other ways, but if I was attempting to create an anti-wireshark program, that's where I would start as to me it makes sense to do. The program would simply have to find the static memory address where wireshark prepares information for display, intercept the packets before their displayed and then use a conditional statement to decide whether to allow them to continue on their way to be displayed or whether to stop them from being displayed. However, it could just be as simple as finding the wireshark process and then calling the console command taskkill to terminate the process (like you said).
common-pile/stackexchange_filtered
Android Studio: Error "No target device" and the files and packages under project all are marked red In the project view on the left, all the files are marked red. But when I run the project in AVD, it runs normally. Does the red sign have any impact? When I connect my phone to Android Studio, it can't found my device. Instead it shows: Error running app:No target device found. This is the screenshot of my project: Just to make sure, have you cleaned and rebuilt the project? 1,you project added vcs,but the files no added. so the files is red.you could add this files into vcs,if you use git,you could run "git add ." 2,you could restart your AS or pc. Thanks for your suggestions, which is useful for me. I solved the two problems. And the second problem is the device's reason, I used other android device, it can connect, and work.My English is not well, take some trouble for your reading,please accept my apology and thanks your suggest again. I had same problem, just opened new project or if you have git pull the project again. some problem with the cradle and links in the project.
common-pile/stackexchange_filtered
What are the drawbacks to duplicating a class in different namespaces? I have a class called SimpleCommand. It is a single file class that implements ICommand in a very simple way (hence the name). I am finding that I am putting it several of my projects. (I just copy the code and add it into the project.) These projects are all in the same solution and resulting wpf application. My question is: Aside from increasing the size of my DLLs by a bit, what are the drawbacks to copying this code around? (I am trying to decide if it is worth the work to put it in a nuget package.) NOTE: I have not changed this code in years, and I don't plan to. I have found that a surprising amount of code that I don't plan to ever change eventually does change. Is there a special reason you are considering the nuget package? What about simply creating a dedicated project and putting the SimpleCommand there? When you need to use it, you simply reference the project. @EricJ. - and if that happens then a find/replace would allow a quick update of the changes... (Or I could go to a nuget package at that time) Right? Why don't you put it in a single library shared by your various projects. Generally speaking, maintenance is an issue, but you haven't changed it in years. I generally have a library of routines I reuse between projects because it's simpler to maintain and doesn't require copy and paste every time I create a new project. Why are you looking at putting it a nuget package? Why not just have a utility assembly that contains this class and anything else that's shared among projects? @NikolaAnusev - good point. I guess I am not doing that because my solution is so big that I usually start new stuff in a separate location then add it in later. Still, I could copy the dll over... @Vaccano: Depends on how extensively your common code is used. I find that little classes and utilities tend to get reused in many of my projects, so I put all of them in a library. The issue here isn't that there are various classes with the same name in different namespaces. The issue is that you're duplicating code, which is really bad idea. If you want to expand your SimpleCommand to ABitMoreComplexCommand you end up copying it all over. If you need to compare one command to another by type you couldn't do that reliably - heuristics you may implement could give you false positives Bottom line: make another project, put all reusable code there, don't copy it around OK, sounds right. I have 79 projects in my solution already... I guess one more won't hurt. Really? 79 projects in your solution? I can't imagine a situation where that's a good idea... Chances are your solution can be greatly refactored and optimized but in real business environments management holds the existing structure dear and would rather grow it than shrink it @Pete Me neither, but I used to work on an "enterprise" app which consisted of a solution that had, at one time, over 90 projects. Good ideas are not always brought to life :) @Pete - We are creating an enterprise level WPF Prism application. Prism likes things in separate projects. We have also found that the loosely coupled modularity also helps with maintenance, so we have not fought the design. (Though it does put a strain on Visual Studio.) Having lots of modules isn't necessarily a problem. I've worked on projects with far more than that. Having them all in a single solution is what seems like a bad idea. You mention the strain on Visual Studio. There's also the fact that it makes navigating the Solution Explorer a nightmare. Copying and pasting is the most innefficient way of reusing code, IMO. What happens if you ever decide to add a simple bool property to this class? you will have to do it as many times as you ever copied and pasted it. I suggest to group these reusable parts in a single DLL and reference them from multiple projects, instead.
common-pile/stackexchange_filtered
How make redirection with web service? I have a web-service which send JSON object as response to log my user. But if I take the URL of the service and I put it on my navigator I see the json object, how I can send the json througth a redirection ? Example : Facebook login -> if we take the action in the form that call facebook/login?... If facebook use JSON to send a response of the log i must see the JSON object if i call facebook/login?... but I was redirected to the main page, how that works ? Thank for your reply. You need to handle response from your web-service with Javascript. How ? with ajax ? I do this to get data in my page when the form is send, but how make redirection if the user put the form URL in the navigator ? do you use JS framework? Or plain javascript? Most of the frameworks send additional header 'X-Requested-With' for AJAX, so, in most cases you may simply check if $_SERVER['HTTP_X_REQUESTED_WITH'] is isset on backend. Not very good, but simple solution. But if you use vanilla JS, you can add it manually. So, in your login handler, just check if this header is set. If yes - return JSON object, if not — redirect this request to any page you find suitable I use vanilla JS. Can you tell me how $_SERVER['HTTP_X_REQUESTED_WITH'] works in this case ? I see your last message : I must send an header from my AJAX request to my page ? As for vaniila JS. Let's suppose you have xmlhttp = new XMLHttpRequest();. So, after xmlhttp.open('GET', URL, true); (yes, login through GET request is not a good idea, but this is just the example). And after open, you need to write the following xmlhttp.setRequestHeader('X-Requested-With', 'XMLHttpRequest'); I you need more informations for AJAX request I use the new fetch API : https://developers.google.com/web/updates/2015/03/introduction-to-fetch Well, as far as I understood, fetchAPI has Headers interface. So, I think that you'll find useful these links: 1) https://developer.mozilla.org/en-US/docs/Web/API/Headers 2)https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch#Supplying_your_own_request_object Then I create an header like : headers: { "X-Requested-With": "XMLHttpRequest" } ? After I check my $_server[http_x_request].. on my backend an redirect if not same header ? I think i found the solution : https://stackoverflow.com/questions/39708042/php-detection-of-fetch-api-vs-xmlhttprequest Thank for your help I did not know we can check if a request comes from ajax. The answer is to check the $_SERVER['HTTP_X_REQUESTED_WITH'] after sending an specific header in the AJAX request. I have a last question in like : Can i use a same like this the volley library, to allow the access to a php script only for an android app ? You can see an example on header in this link : https://gist.github.com/FabrizioCaldarelli/ad1118e5d8ab0661ba36
common-pile/stackexchange_filtered
Which functions trigger which authorizations for an apps script? When apps scripts run as the user, the user must authorize them to do certain things, depending on the functions used in the script. In the simplest case, there is no authorization, but if you use a function in the script like Session.getActiveUser().getEmail(), the authorization is something like: this app will "View your email address" and this app "Will know who you are on Google". If you access a spreadsheet in the script, it will say something like: this app needs permission to "View and manage your spreadsheets in Google Drive". 1) Is there any explanation of what those permissions really mean in detail? I believe the last one means "spreadsheets that are shared with the app...." and not all the user's spreadsheets! I want to be able to point the app user to Google's explanation, but I haven't found a link. 2) Which script functions will trigger a new permission? I know it seems pretty obvious, but I have one app that does not access a spreadsheet and yet I am getting "View and manage your spreadsheets in Google Drive" request. I could be that is because one of the earlier version of that app does access spreadsheets. Not sure! Thanks! PS: some discussion here, but not quite what I want. For question number 2, make sure that you've gone into your script's project properties and select "manage versions" to make sure that you have an updated version, and then go back to publish and change the published version to the most current version (that doesn't access the spreadsheet anymore). I think I found one stumbling block: even functions in code that is commented out and will never be run will trigger the authorization. I deleted the comments, and then it elicited the expected authorization. Since I undid the authorization, when I use the "latest version" I get the authorization prompt and can see what will be required of the user... So deleting out the commented section clears the request for auth on the spreadsheet? Makes sense, because it would probably be better for security to authorize anything that is possible within the content of the code, so it wouldn't trigger a re-auth of you uncommented the code after deployment. Yes, or perhaps I simply got a re-auth after cutting out comments. But in some sense it is odd because really the comments don't count and should not trigger authorization -- more experimenting needed!
common-pile/stackexchange_filtered
Understanding Operator Norm of Matrices Let $X$ denote the vector space of $n\times n$ complex matrices. To every matrix $A\in X$ one can associate two operator norms: Thinking of $A$ as a map $A\colon \mathbb{C}^n\to \mathbb{C}^n$ or $A\in L(\mathbb{C}^n)$ in short, we define $\|A\|_{L(\mathbb{C}^n)}=\sup_{v\in \mathbb{C}^n, \|v\|=1}{\|Av\|}$. Thinking of $A$ as a map $A\colon X\to X$ or $A\in L(X)$ in short, we define $\|A\|_{L(X)}=\sup_{B\in X, \|B\|_{L(\mathbb{C}^n)}=1}{\|AB\|}$. It is well-known that $\|A\|_{L(\mathbb{C}^n)}=s_1(A)$ where $s_1$ is the largest singular value of $A$. My questions are: Is there is a (spectral?) characterization of $\|A\|_{L(X)}$? or perhaps a relation between the two above norms? Is there any application of the second norm (in, say functional analysis)? I will explain below why I started thinking about this norm in the first place. I was trying to understand the following paragraph that lead to my questions above. "If $X$ is equipped with the operator norm $\|\cdot\|_{L(\mathbb{C}^n)}$, then its dual space $X^*$ is the space $X$ equipped with the trace norm $\|\cdot\|_1=\text{ sum of singular values}$, and vice versa." I still don't see why (3) has to be true, but if necessary, and if it turns out to be irrelevant to the other two questions, I can ask it in a separate question. Any help is appreciated. I will assume that the norm $\|AB\|$ in the definition of $\|A\|_{L(X)}$ is $\|AB\|_{L(\mathbb C^n)}$. The two norms are equal: you have, by definition, $$ \|A\|_{L(X)}\leq \|A\|_{L(\mathbb C^n)}, $$ since $\|AB\|_{L(\mathbb C^n)}\leq \|A\|_{L(\mathbb C^n)}\,\|B\|_{L(\mathbb C^n)}=\|A\|_{L(\mathbb C^n)}$. Conversely, $$ \|A\|_{L(X)}\geq\left\|A\,\frac{A^*}{\|A^*\|}\right\|_{L(\mathbb C^n)} =\frac{\|AA^*\|_{L(\mathbb C^n)}}{\|A\|_{L(\mathbb C^n)}} =\frac{\|A\|^2_{L(\mathbb C^n)}}{\|A\|_{L(\mathbb C^n)}} =\|A\|_{L(\mathbb C^n)}. $$ Regarding the dual $X^*$, it is not hard to see that one can write $$ X^*=\{\text{Tr}(B\,\cdot):\ B\in X\}, $$ giving the identification of every functional in $X^*$ with a matrix $B$. Now let us write $f_B=\text{Tr}(B\cdot)$ and let us look at the norm: $$ \|f_B\|=\sup\{|f_B(A)|:\ \|A\|_{L(\mathbb C^n)}=1\} =\sup\{|\text{Tr}(BA)|:\ \|A\|_{L(\mathbb C^n)}=1\} =\|B\|_1. $$ Here is a proof of the last equality: write $B=UDV$ the singular value decomposition. Using that unitaries preserve the norm, $$ \sup\{|\text{Tr}(BA)|:\ \|A\|_{L(\mathbb C^n)}=1\} =\sup\{|\text{Tr}(DA)|:\ \|A\|_{L(\mathbb C^n)}\} =\sup\{\left|\sum_jD_{jj}A_{jj}\right|:\ \|A\|_{L(\mathbb C^n)}=1\}= \sum_jD_{jj}=\|B\|_1. $$ Recently upvoted your answer, it served me well as starting point to a $C^*$omplement. Nice, thanks. $\ $ Expansion on the existing answer by taking a more general view on $X=L(\mathbb{C}^n)$: When equipped with the operator norm, then $X$ is a $C^*$-algebra (with Matrix multiplication as product, and Transpose + Complex conjugate as involution, just to make sure), and it's reasonable that Martin Argerami added the corresponding tag. He shows the equality $$\|A\|_{L(X)}:=\sup_{B\in X,\,\|B\|_X=1}\|AB\|_X\;\overset{!}{=}\;\|A\|_X$$ of the two norm expressions, and this equality holds true for every $\,C^*$-Algebra. With the very same proof: An inspection shows that only $\,C^*$-norm features are used, but no particular property depending on $L(\mathbb{C}^n)$. W.r.to applications of this fact: It is an ingredient of "Unitisation of a $C^*$-Algebra $A$", you may consult [Pedersen: "Analysis now", 4.3.9 Lemma], and here's a sketch of the recipe: With $A_1$ denoting $A$'s algebraic unitisation one starts with the algebra homomorphism $$A_1\to L(A),\;(a,\lambda)\longmapsto L_a +\lambda\cdot\operatorname{id}_A$$ in order to embed $A_1$ into $L(A)$, in which a norm and the unit are naturally available. $L_a$ denotes left multiplication by $a\in A\,$ (and the above homomorphism is injective iff $A$ has no unit). Then the norm is pulled back to $A_1$ where it does the $C^*$-job. The corresponding proof depends on the norm equality under consideration. You may switch to this "Unitization" post, astonishingly having found his home @MO. IIRC, the fact is also needed in the construction of the Multiplier algebra of a $C^*$-Algebra (which belongs to the unitisation context as well).
common-pile/stackexchange_filtered
Oracle Convert TIMESTAMP with Timezone to DATE I have DB with timezone +04:00 (Europe/Moscow) and need to convert a string in format YYYY-MM-DD"T"HH24:MI:SSTZH:TZM to DATE data type in Oracle 11g. In other words, I have a string 2013-11-08T10:11:31+02:00 and I want to convert it to DATE data type (in local DB timezone +04:00 (Europe/Moscow)). For string 2013-11-08T10:11:31+02:00 my desired transformation should return DATE data type with date 2013-11-08 12:11:31 (i.e. with local timezone transformation of time to +04:00 (Europe/Moscow)). Timezone of string may be different and +02:00 in string above is just example. I tried to do this with TIMESTAMP data type, but no success with time zone transformation. Except for situations that need 'local' times (ie, scheduling/planning, especially for timezones with daylight savings), it's usually best to store absolute timestamps stored in UTC (and translate on display/report). What are these timestamps being used for? I receive date in this timestamp format from external system and do not know why external system uses them. :( Found my answer.. but in case if you want to double check that timestamp is true or false, I found a good site for this. http://onlinetimestampconvert.com to_timestamp_tz() function with at time zone clause can be used to convert your string literal to a value of timestamp with time zone data type: SQL> with t1(tm) as( 2 select '2013-11-08T10:11:31+02:00' from dual 3 ) 4 select to_timestamp_tz(tm, 'yyyy-mm-dd"T"hh24:mi:ss TZH:TZM') 5 at time zone '+4:00' as this_way 6 , to_timestamp_tz(tm, 'yyyy-mm-dd"T"hh24:mi:ss TZH:TZM') 7 at time zone 'Europe/Moscow' as or_this_way 8 from t1 9 / Result: THIS_WAY OR_THIS_WAY ---------------------------------------------------------------------------- 2013-11-08 12.11.31 PM +04:00 2013-11-08 12.11.31 PM EUROPE/MOSCOW And then, we use cast() function to produce a value of date data type: with t1(tm) as( select '2013-11-08T10:11:31+02:00' from dual ) select cast(to_timestamp_tz(tm, 'yyyy-mm-dd"T"hh24:mi:ss TZH:TZM') at time zone '+4:00' as date) as this_way , cast(to_timestamp_tz(tm, 'yyyy-mm-dd"T"hh24:mi:ss TZH:TZM') at time zone 'Europe/Moscow' as date) as or_this_way from t1 This_Way Or_This_Way ------------------------------------------ 2013-11-08 12:11:31 2013-11-08 12:11:31 Find out more about at time zone clause and to_timestamp_tz() function. Thank you! select CAST(to_timestamp_tz('2013-11-08T10:11:31+02:00', 'yyyy-mm-dd"T"hh24:mi:ss TZH:TZM') at time zone DBTIMEZONE AS DATE) from dual will be correct way for me SELECT CAST((FROM_TZ(CAST(timezonefield AS TIMESTAMP),'GMT') AT TIME ZONE 'CET') AS DATE) FROM table; Converts a timestamp in GMT to date in Central European time if you want your timestamp with timezone to convert to a date in sync with "sysdate" then use the following: select cast(to_timestamp_tz('2013-11-08T10:11:31-02:00' ,'yyyy-mm-dd"T"hh24:mi:sstzh:tzm' ) at time zone to_char(systimestamp ,'tzh:tzm' ) as date ) from dual I cannot tell you how long I searched for some way to do this! to cast time stamp to date : cast(registrationmaster.Stamp5DateTime as date) >= '05-05-2018' AND cast(registrationmaster.Stamp5DateTime as date) <= '05-05-2018' you can manage timezones with CAST(x AT TIME ZONE 'YYYY' AS DATE), this helps me: WITH t1 (tm) AS (SELECT TIMESTAMP '2021-12-14 15:33:00 EET' FROM DUAL) SELECT 'EET' tz, CAST (tm AT TIME ZONE 'Europe/Kaliningrad' AS DATE) AS datetime FROM t1 union SELECT 'MSK' tz, CAST (tm AT TIME ZONE 'Europe/Moscow' AS DATE) AS datetime FROM t1 union SELECT 'CET' tz, CAST (tm AT TIME ZONE 'Europe/Prague' AS DATE) AS datetime FROM t1 union SELECT 'UTC' tz, CAST (tm AT TIME ZONE 'UTC' AS DATE) AS datetime FROM t1 Welcome to Stack Overflow. Code is a lot more helpful when it is accompanied by an explanation. Stack Overflow is about learning, not providing snippets to blindly copy and paste. Please edit your question and explain how it answers the specific question being asked. See [How to Answer]https://stackoverflow.com/questions/how-to-answer)
common-pile/stackexchange_filtered
How to promote/open app from Google search website results? Background When you search on Google's search engine website on an Android device (via Chrome web browser) something like "how to get to X" (where X is a geographic location, like a city name) , the first item that is shown is a card that allows to navigate to the location you've written. When choosing to navigate, there are 2 options: if the Android device has Google-Maps installed, it opens the app and navigates there. if the Android device doesn't have Google-Maps installed, it goes to the play store to the app's page, to install it. as shown below: In addition, on some cases, for something, Google can put an extra textbox to search within the website it has found, to get the results on it. Such a thing occurs for the Hebrew website "Zap" (which compares prices of products) : The question Is there a promotion-program or service or anything to promote a website/app/both this way (deep linking and search box)? If so, where should I start? Suppose you already have a website that can perform search queries, how do you do the check of whether the app is installed or not (inside the website, not via Google's search engine), and act accordingly? Can this be done only on Google Chrome app? What should be done (code in android-app, website and others) in order to have those features? For your first question, what you might be looking for is what is called App Indexing. As Google itself describes it: App Indexing lets Google index apps just like websites. Deep links to your Android app appear in Google Search results, letting users get to your native mobile experience quickly, landing exactly on the right content within your app. Basically, the App Indexing API is the one responsible for informing the web of the deep links present in your application. So, first of all, you'll have to add those deeplinks to your mobile application. You can do that in android by specifying Intent Filters and defining a schema like described here and on iOS by defining URLTypes as described here. Once you have your deeplinks working, you'll add the App Indexing API to your app through Google Play Services. Basically, you'll add calls to every onStart() and onStop() of the Activitys you're interested into indexing with code like: // in onStart() AppIndex.AppIndexApi.start(mClient, viewAction); // in onStop() AppIndex.AppIndexApi.end(mClient, viewAction); You can also find more details for the API and how to set it up in detail here. Since last month, you can also drive installs of your app through App Indexing, as noticed here. PS: If you're interested, there are nice DevBytes videos about App Indexing here and here. The search box in Google Chrome results is called Sitelinks Search Box, so if you do have already a querying mechanism on your website, all you have to do is implement the schema.org markup on it: <script type="application/ld+json"> { "@context": "http://schema.org", "@type": "WebSite", "url": "https://www.example-petstore.com/", "potentialAction": { "@type": "SearchAction", "target": "https://query.example-petstore.com/search?q={search_term_string}", "query-input": "required name=search_term_string" } } </script> After that, you'll have to wait a little for Google to update its crawlers with your new information. You can find detailed information about the markup with examples and troubleshooting here. What about the part that goes to the play store webpage of the app, if the app isn't installed? Also, how do I tell the App-Indexing API which type of queries/commands the app supports? By implementing App Indexing, your app will automatically present an install button if it's not installed yet, the video link I left previously talked about that, but in any case, I've edited the answer to make it more clear. About the types of queries and commands for App Indexing, that's the job of Deep Links. The link I left earlier explains how to do it, by defining the schema into your AndroidManifest.xml file. There is also a codelab that might help you. I don't understand how the "deep links" works. Suppose the app can only handle queries of telphone numbers, what should be done in order to tell Google Search to show the app only in case the query is of phone numbers? If you're just searching for numbers in Search, I fear there is no way to deep link directly, otherwise we would have an almost infinite number of apps trying to handle those links. You can define a deep link with your app schema and treat the numbers internally, so, for example, myapp://call=325458754 that would start a CallActivity with 325458754 as parameter. Also, you can define an Intent Filter to make your app a dialer, or even integrate it with Google Now why infinite number of apps? not all texts that are entered are valid phone numbers... Also, not all are for calling. I could, for example , search for phone numbers to show information about the person based on it.
common-pile/stackexchange_filtered
Using 9patch background makes text invisible in EditText I use a transparent 9patch image as a background in EditText and after that, no text inside EditText is visible. When I remove background, everything goes OK. Any idea? This is 9patch image: And this is EditText: <EditText android:id="@+id/areaEditText" style="@style/EditText" /> <style name="EditText"> <item name="android:layout_width">match_parent</item> <item name="android:layout_height">48dip</item> <item name="android:background">@drawable/edit_text_bg</item> <item name="android:layout_marginLeft">5dip</item> <item name="android:layout_marginRight">5dip</item> <item name="android:textSize">20sp</item> <item name="android:paddingRight">10dip</item> <item name="android:textColor">@color/text_dark</item> </style> Perhaps the font color is the same as the background color of whatever is behind the EditText. Background is white and textColor is black Post your 9-patch image here. check your fill area on 9patch, suppose it's wrong fill area is transparent. can you please share you 9patch I want to check it try picture, which i've posted I think your text view is not wide enough for the text amount you entered there I compared my 9patch with Android's in android sdk. I changed my 9patch and everything goes OK. This is WRONG patch: And this is CORRECT: you should not make a transparent background image, you can use a background color like this <TextView ... android:background="#CCFF0000" /> Please test it and tell me if it work in your case
common-pile/stackexchange_filtered
Is there any way to hide/flatten base types in WCF service data contracts? Consider the following simple example: [DataContract("{0}Base")] public class Base<T> where T : Entity<T> { // Common methods & properties. No WCF exposed properties } [DataContract] public class Employee : Base<Employee> { // WCF exposed properties } The base class Base has no properties of interest to the WCF service consumers, but WCF forces me to also annotate the Base class with a [DataContract] attribute. This essentially shows up on the service client as Employee : EmployeeBase with EmployeeBase being an empty class with no properties. I do not want to expose the Base<T> class to the service in this way, so what are my options? DTO for the Employee class - I'd rather not add this complexity "Flatten" the DataContract hierarchy so that the data contract for Employee does not expose that it inherits from Base<T>. Is this possible? How? Other solution? Thanks. Each class in hiearchy has to be serializable / DataContract. If you don't want to expose hiearchy you have to use DTO or you can try to implement IDataContractSuroggate for your Employee class. Looks like DTO or just accepting that the base object will be exposed. Actually, just stumbled upon this question, which I guess makes mine a duplicate: http://stackoverflow.com/questions/658361/wcf-serialization-with-object-inheritance
common-pile/stackexchange_filtered
Disabling prepared statements in TypeORM I'd like to disable prepared statements, is there a way to do this in TypeORM configuration?
common-pile/stackexchange_filtered
How can I copy text from a tmux window to the system clipboard? I am using Ubuntu 16.04 with tmux 2.1. Mostly I split the screen in two tmux windows split vertically. Frequently, I need to copy long pieces of text from the tmux window and paste it in the sublime text/browser. I have a feeling that xsel/xclip could be used to achieve the same. However, most of the how-to's floating in the Internet are severely bloated, trying to explain intricate configuration option without really explaining: What exactly do I need to configure in tmux.conf? How do I select a piece of text in the tmux window? How do I copy the selected piece of text? How do I paste the text from system clipboard to text editor/browser? I don't want to be a tmux guru. All I want to get the job done in simplest possible way. Any clue how to do that? really excellent article on all things tmux copy paste ubuntu, pretty much written for this question: https://www.rushiagr.com/blog/2016/06/16/everything-you-need-to-know-about-tmux-copy-pasting-ubuntu/ May refer to https://stackoverflow.com/questions/17255031/how-to-copy-from-tmux-running-in-putty-to-windows-clipboard tmux is a tool used primarily by programmers. The question should be reopened. Hard to imagine what good closing popular 6 year old questions like this does. I personally am using Ubuntu 18.04 in WSL2 . However this solution will work on Ubuntu 16.04 also. I have been using tmux-yank for copything text from tmux buffer to system clipboard. You would first need to set up Tmux Plugin Manager. Follow this link. Then set add tmux-yank plugin to your .tmux.conf file , see here. You can start by looking at the example configurations at: /usr/share/doc/tmux/examples$ You can also look at the current key bindings using ctrl+b+?. You can change these default key bindings in the .tmux.conf file. It depends on your settings how you select a piece of text in tmux window. You can map the key bindings as per vim. Enter the copy mode (ctrl+b + [), scroll to the start/end of the text you want to copy to the tmux clipboard, press v (provided the key bindings as per vim) to start copying. move to the other end of the text, press y to yank the text. press ctrl+b+] to paste the text. I am trying to figure out how to copy/paste from system clipboard on this version. Will update my answer if I have any luck. Thanks for your answer, I just realized that I mis-pressed it to ctrl+b+{. Searching tmux copy clipboard this question was shown and I'd like to share one of the ways how to deal with the problem if you're using tmux within VSCode. I use selection with the mouse with set -g mouse on setting in .tmux.conf; to get the selected fragment which is stored in tmux buffer I do cat | code - and paste in the running cat with Ctrl-b + ]; pasted fragment occurs in VSCode editor too, then it's easy to copy from the window. On tmux 1.8 running in ssh session under Putty 0.73 on Windows, below works for me. COPY: Use ctrl+b,] got to start line, press Spacebar (it will start selection and highlighting text), use arrow or PageUp to go to end line, press Enter to get all selected text in buffer. PASTE: ctrl+b,] set-window-option -g mode-keys vi bind P paste-buffer bind-key -T copy-mode-vi c send-keys -X copy-pipe-and-cancel "xclip -i -selection clipboard" This answers copying and pasting within tmux. OP is looking for a way to copy to system clipboard for use elsewhere.
common-pile/stackexchange_filtered
Next JS project deployment on local machine giving this error I have cloned an empty NextJS project from GitHub [only have initial project setup] and then I simply did: npm i npm run dev At localhost:3000, I am continually facing this: It seems something related to next or some other dependency. Does anyone has any idea why is it so? or what steps could I opt to resolve this? Where does MainData come from? Please provide a [mre]. Check if "MainData" variable is initialized and is array on first render and if not try wrapping it with some conditional like to delay rendering the list {MainData ? MainData.map(data => ...) : <p>Loading...</p>}
common-pile/stackexchange_filtered
Task.Run() blocks startup of .net core application public void Configure(...) { ... Task.Run(() => { var eventBus = app.ApplicationServices.GetRequiredService<IEventBus>(); eventBus.Subscribe<Event1, Event1Handler>("key"); }); } My scenerio covers rabbitMq absence on application startup. What I am trying to achieve here, is to run this task in the background and let my application start in normal way. What I get is that application still waits for execution of this task and after that is responsive. I would like to use .RetryForever() inside this task to establish connection with rabbitmq and then subscribe to queue, but in the meantime my service should work without rabbitmq. What am I doing wrong? Maybe I should change the way I try to initialize connection with rabbitMq? I replaced Task.Run invokation with proper class derving from BackgroundService. Then I in registered it as HostedService in Program.cs method: IHostBuilder CreateHostBuilder(string[] args) .ConfigureServices(services => { services.AddHostedService<MyHostedService>(); }); With this I achieved webApi start without interuption and background process which is trying to connect to rabbitmq until it achieves it.
common-pile/stackexchange_filtered
Azure AD B2C: error for on-premise ad fs as SAML identity provider I was trying to add our on-prem AD FS as SMAL identity provider in azure ad b2c. I followed this document and finished all steps. Then I tried the Run now endpoint (from aad b2c custom policy), and clicked the new IDP button (MY AD FS), I got the error: AADB2C: Unable to connect to the metadata endpoint 'https://MY.ADFS.COM/federationmetadata/2007-06/federationmetadata.xml' Some notes: I run the test from the AD FS Server machine I can access the metadata directly from URL https://MY.ADFS.COM/federationmetadata/2007-06/federationmetadata.xml in browser (on the AD FS Server machine) Not sure what I'm missing. Does it matter the AD FS server is corpnet wide only? Please help I got help from Microsoft. To resolve this error, just put the metadata file on a public storage so that B2C can access it.
common-pile/stackexchange_filtered
WPF Control: where is "OnLoaded" virtual function? In WinForm's control, there is an OnLoaded virtual function, but this seems to be missing in WPF control. I found this function very useful in some situations. For example, I could do something here after the control is "completely" initialized. In WPF control, there is an OnInitialized virtual function, but this function is called from InitializeComponent function which is too early and it doesn't allow derived class to setup. Is there any reason not to have this function in WPF? Or did I miss anything? You can attach to the Loaded event of your Window object and do what you want to do inside the event handler (assuming you are using c#): public MyWindow() //constructor { this.Loaded += MyWindow_Loaded; } private void MyWindow_Loaded(object sender, RoutedEventArgs e) { // do your stuff here } I know I could work it around like this, but I'm more curious why WPF removed that function. In fact, I was also wondering why OnLoaded was removed as a virtual function in WPF Window. Now, I have to do this extra hook to get back my Loaded function. Why? @miliu: I think the main reason is that in WinForms, OnLoad was a very important part of the (event-based) system. Certain things could only be done at that point in the Application lifecycle. In WPF however there is no real need to expose this event handler to the user. The framework does not use it (hence it's not virtual), so why should you? Thanks. This sounds reasonable. you will be looking for FrameworkElement.EndInit() This will work after the initialization process of the Element... I don't understand how the EndInit() function can help me here. Can you please elaborate? as you mentioned in your question "I could do something here after the control is "completely" initialized" EndInit isn't called after the control is completely initialized. It's called before OnApplyTemplate.
common-pile/stackexchange_filtered
RecyclerView not render cells with 0dp height I made an app with onboarding flow. I have a recyclerview in my MainActivity class and I want to update it when onResume hits(Right after the onboarding flow). So this how the recycler xml looks: <android.support.v7.widget.RecyclerView android:id="@+id/notifyRecycler" android:layout_width="0dp" android:layout_height="230dp" android:clipToPadding="false" android:orientation="horizontal" app:layoutManager="android.support.v7.widget.LinearLayoutManager" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" app:layout_constraintTop_toTopOf="parent" /> and this it the cell layout: <android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/container" android:layout_width="match_parent" android:layout_height="match_parent"> <View android:id="@+id/cardDetails" android:layout_width="0dp" android:layout_height="0dp" android:orientation="horizontal" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" app:layout_constraintTop_toTopOf="parent"> </...> I swap the data within the adapter with clear and add and everything works great when I change the cell layout view height from 0dp to match parent. It also works great for the first run from oncreate, but when I try to update from onResume it just not notify the data set changed. Here's the code of the adapter called from onResume function: public void setNewData(ArrayList<Model> models) { this.notifications.clear(); this.notifications.addAll(models); notifyDataSetChanged(); } in onCreate: adapter = new NotificationsAdapter(new ArrayList<>(), this); notifyRecycler.setAdapter(adapter); in onResume,I made boolan var to make it update only when resuming the app: ArrayList<NotificationModel> notificationsList = new ArrayList<>(); notificationsList.add(...); notificationsList.add(...); adapter.setNewData(notificationsList); Can you share the code for both onCreate and onResume ? how did you recognize that onResume not notify the data set changed, did you pass different dataset from onResume than onCreate ? yes it just a hardcoded dataset and pass it to the setNewData method if you are passing the same data set from both the method onCreate and onResume then you can't notice whether data set changed notified or not for the second call. please provide the onCreate and onResume method call along with dataset that you are passing to the setNewData method. updated the post As per onCreate and onResume code, sounds like there shouldn't be any issue. Tell me what the issue exactly you are getting ? . By looking the code I can see whatever items you set in the list notificationsList, those many items should be getting displayed properly. I am bit confused with your statement It also works great for the first run from oncreate, but when I try to update from onResume it just not notify the data set changed. What exactly is going wrong ?. It's understood your adapter will notify data set changed only once i.e from onResume. I know, as I said before everything works grear when the cell layout uses a real size or match parent for the view dimension,but when I try to use 0dp for the "cardDetails" dimension , the recycler shows nothing althought rhe layout inspector shows that the recyclerview has cells. Why do you need cards with size 0?, it is obvious cells with size zero won't be visible. Do you know how constraints work? Wierd solution, Solved by changing the parent ViewGroup from ConstraintsLayout to RelativeLayout.
common-pile/stackexchange_filtered
How to create a new(original) struts path? I have tried overriding existing StrutsPortletAction before with their existing struts path with success. However, I can't seem to do the same if I were to try creating my own struts action path. <hook> <custom-jsp-dir>/custom_jsps</custom-jsp-dir> <struts-action> <struts-action-path>/portal/set_viewers/</struts-action-path> <struts-action-impl>com.mine.blogs.hook.BlogEntryViewerStrutsPortletAction</struts-action-impl> </struts-action> </hook> The eclispe IDE gives me this error "/portal/set_viewers/" is not among possible values" and when I go ahead and deploy the built war anyways, tomcat errors as: com.liferay.portal.kernal.util.InstanceFactory can not access a member of class com.mine.blogs.hook.BlogEntryViewerStrutsPortletAction with modifiers "" Tried with struts-action-path as /blogs/set_viewers/ failed as well. This is the .java i'm using. Very basic actually. package com.mine.blogs.hook; import javax.portlet.ActionRequest; import javax.portlet.ActionResponse; import javax.portlet.PortletConfig; import javax.portlet.RenderRequest; import javax.portlet.RenderResponse; import javax.portlet.ResourceRequest; import javax.portlet.ResourceResponse; import com.liferay.portal.kernel.struts.StrutsPortletAction; public class BlogEntryViewerStrutsPortletAction implements StrutsPortletAction { BlogEntryViewerStrutsPortletAction(){ super(); } @Override public void processAction( PortletConfig arg0, ActionRequest arg1, ActionResponse arg2) throws Exception { // TODO Auto-generated method stub System.out.println("process1"); } @Override public void processAction( StrutsPortletAction arg0, PortletConfig arg1, ActionRequest arg2, ActionResponse arg3) throws Exception { // TODO Auto-generated method stub System.out.println("process2"); } @Override public String render( PortletConfig arg0, RenderRequest arg1, RenderResponse arg2) throws Exception { // TODO Auto-generated method stub System.out.println("render1"); return null; } @Override public String render( StrutsPortletAction arg0, PortletConfig arg1, RenderRequest arg2, RenderResponse arg3) throws Exception { // TODO Auto-generated method stub System.out.println("render2"); return null; } @Override public void serveResource( PortletConfig arg0, ResourceRequest arg1, ResourceResponse arg2) throws Exception { // TODO Auto-generated method stub System.out.println("serve1"); } @Override public void serveResource( StrutsPortletAction arg0, PortletConfig arg1, ResourceRequest arg2, ResourceResponse arg3) throws Exception { // TODO Auto-generated method stub System.out.println("serve2"); } } And the corresponding liferay-hook.xml <hook> <custom-jsp-dir>/custom_jsps</custom-jsp-dir> <struts-action> <struts-action-path>/blogs_entry/set_viewers/</struts-action-path> <struts-action-impl>com.mine.blogs.hook.BlogEntryViewerStrutsPortletAction</struts-action-impl> </struts-action> </hook> Are you extending your BlogEntryViewerStrutsPortletAction with BaseStrutsPortletAction ? Yes have done that. But I also realized that the IDE did not prompt me to create the methods required for overriding such as render, processAction etc... Its not mandatory to override all the methods, BaseStrutsPortletAction class has basic implementation of the methods. The error was because of the Constructor. I've removed it and it's now deploying properly Please try changing the struts action URL to something other than starting with "/portal". Liferay may be reserving "/portal" for portal level action paths. For example, <struts-action-path>/blogs_entry/set_viewers/</struts-action-path> I actually used '/blogs/set_viewers/' at first before trying using /portal
common-pile/stackexchange_filtered
Analytics hasn't updated keywords the last week, what could be the problem? The Keywords section under "Sources" in my GA account hardly updated at all. I KNOW I had more than 2 searches for a keyword, but GA doesn't show these? I have a GA account and I have a tracking code like this on my website: <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-xxxxxx-1']); _gaq.push(['_trackPageview']); (function() { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <script type="text/javascript"> function fnx(that, outbound) { try { var pageTracker=_gat._getTracker("UA-xxxxx-1"); pageTracker._trackPageview(outbound); setTimeout('document.location = "' + that.href + '"', 100) }catch(err){} } </script> First part is the GA tracking code. The second is just to be able to track clicks on some certain banners on the site. Anybody familiar with this kind of problem? Are you (or whoever did the search) using an ad blocker? They often block tracking scripts like GA. Also make sure it's not anything silly like the code not actually being on the page you go to, or you've told GA to ignore your IP address, or you have JS disabled. Make sure you are checking in the correct date range and checking every search term in the list. Perhaps try removing that custom code temporarily to check that it's not the cause of the problem. I don't know if GA does actually log every search term. For example it may not log long exact queries (in quotes) and it may not log things like site: queries.
common-pile/stackexchange_filtered
Print all the elements on a single given level of a binary tree I am required to print out(visit) the nodes on a single level of a binary tree. I don't see how this can be done but then again I not very skilled with algorithms in general. I know that in Breadth-First traversal you use a queue and that you start by putting the root node in the queue then you dequeue it visit it and enqueue it's children and then you dequeue the first enqued child visit it and enqueue it's children and so on... And by my understanding this makes it impossible to know exactly when one level ends and another begins unless you assign each node it's level when the binary tree is created and then just check the level when you are doing the Breadth-First traversal. Something like this(the code is in PHP but this is not a PHP related question it is a general algorithm related question - this is part of a function that adds a node to a binary tree storing the level in the node when each node is added): if($this->root == null) { $this->root = $node; $this->root->level = 1; return; } $nextnode = $this->root; $level = 1; while (true) { if($node->value > $nextnode->value) { if($nextnode->right != null) { $nextnode = $nextnode->right; $level++; } else { $nextnode->right = $node; $nextnode->right->level = ++$level; return; } } else if($node->value < $nextnode->value) { if($nextnode->left != null) { $nextnode = $nextnode->left; $level++; } else { $nextnode->left = $node; $nextnode->left->level = ++$level; return; } } else if($node->value == $nextnode->value) return; } So my questions are: Is this the only way of printing the nodes on a single level of a binary tree? Is there another way? Is there another way without storing the level when creating the tree? Would a recursive solution suite you? I wrote this in C, i hope this is not a problem for you. void traverse_tree_rec(TreeNode *ptn, int current_level, int targeted_level, (void*)(pVisit)(TreeElement*)){ if (ptn==NULL) return; else if(current_level == targeted_level) pVisit(ptn->entry); else{ traverse_tree_rec(ptn->left, current_level+1, targeted_level, pVisit); traverse_tree_rec(ptn->right, current_level+1, targeted_level, pVisit); } } void traverse_level(Tree *pTree, int level, (void*)(pFunction)(TreeElement)){ traverse_level_rec(pTree->root, 0, level, pFunction); } Needs the first and second clauses switched over or there's a null pointer dereference possible. It's also more natural to visit the left branch first! @Para, this makes it impossible to know exactly when one level ends and another begins unless .... You need not traverse the whole tree during the BFS traversal you are trying to do. You can modify the BFS psedocode given in wiki by introducing an array level[]; You have to do these: initialize level as 0 for each node. whenever u mark o in line: o ← G.opposite(t,e) assign level[o] = level[t]+1; after t ← Q.dequeue() if level[t] > targeted_level break;
common-pile/stackexchange_filtered
How do I hypenate correctly without creating gaps in paragraphs? I'm trying to get hyphenation working correctly. <!doctype html> <!-- lset language--> <html lang="nl"> <head> <link href="https://fonts.googleapis.com/css?family=Chivo:400,700,900" rel="stylesheet"> <title>HYPHENATE</title> <style> html { background: #fff; /* Warning: Needed for oldIE support, but words are broken up letter-by-letter */ -ms-word-break: break-all; word-break: break-all; /* Non standard for webkit */ word-break: break-word; -webkit-hyphens: auto; -moz-hyphens: auto; -ms-hyphens: auto; hyphens: auto; } .product-name { width: 113px; font-weight: 900; color: #231f20; font-size: 18px; line-height: 22px; text-transform: uppercase; overflow: hidden; font-family: "Chivo", sans-serif; background-color: grey; } </style> </head> <body> <div class="product-name">Bijzettafel Aspen met tijdschriftenrek</div> </body> </html> This results in a text box with is hyphenated as follows: I can forgive instances where words are hyphenated incorrectly as I understand that some words aren't always in 'htmls' dictionary. But what I find strange is that hyphenated words somethimes leave gaps in paragraphs. In this example this would make much more sense: BIJZETTA- FEL ASPEN MET TIJD- SCHRIFTEN- REK As after hyphenation there would be enough space after 'MET' TO PUT 'TIJD-' BEHIND IT. How can I fix the code so that hyphenated syllables automatically continue behind previous words when there would be plenty of space for it? The basic problem is that the browser has a hyphenation algorithm and you can't interfere with it. The browser will lay the text out as it wants. (The same is true in MS Word, InDesign or any other text software, of course. It's just that with proper layout software, you get more control over the text properties.) The reason that the browser has moved "TIJD-" to the next line is that it's fractionally too wide for the space the browser has left to place text in so it has no choice but to move it. You have two options for changing how the text flows. The first is to make a tiny adjustment to the element width, the font size or the font kerning. (You can do this across the whole text, or just to offending portions using a span.) This will change the maths behind the text flow and may let you produce a more aesthetic result. The second is to use hard spaces (&nbsp;), thin spaces (&#x2009;) or (as a real bodge) spans with padding and no real spaces at all, to try and force the browser to lay the text out as you want. But, because all browsers are different, you can't guarantee the result, whatever option you choose. If it's essential to get the right look, you'll need to use an image (but don't forget the accessibility if you do)! Strangely enough I found out that by commenting out 'overflow: hidden' and adding 'display: table' to the product-name class I got what I wanted. Removing 'overflow: hidden' made the syllables move nicely behind the previous words. When I went to another browser window those syllables moved down again for some reason, but that was fixed by adding 'display: table'. The resulting code below. Leading to above good result. Not a clue why this works but css sometimes works mysteriously :-) <!doctype html> <!-- lset language--> <html lang="nl"> <head> <link href="https://fonts.googleapis.com/css?family=Chivo:400,700,900" rel="stylesheet"> <title>HYPHENATE</title> <style> html { background: #fff; /* Warning: Needed for oldIE support, but words are broken up letter-by-letter */ -ms-word-break: break-all; word-break: break-all; /* Non standard for webkit */ word-break: break-word; overflow-wrap: break-word; -webkit-hyphens: auto; -moz-hyphens: auto; -ms-hyphens: auto; hyphens: auto; } .product-name { /* added display: table*/ display: table; width: 113px; height: 300px; font-weight: 900; color: #231f20; font-size: 18px; line-height: 22px; text-transform: uppercase; font-family: "Chivo", sans-serif; /*overflow: hidden;*/ background-color: grey; } </style> </head> <body> <div class="product-name">Bijzettafel Aspen met tijdschriftenrek</div> </body> </html>
common-pile/stackexchange_filtered
How to pass list to angular array I am a new to angular... I have an object list that I would like to pass to angular and use the ng-repeat function. Using NameList that was passed from my controller, I would like to display a list of id-names-states. Before, I did the following... <ul> @foreach (var item in Model.NameList) { <li>item.id - item.names - item.states</li> } </ul> the list would be something like... id: '1', name: 'John Doe', city: 'Phoenix' id: '2', name: 'Tony Hope', city: 'Queens' id: '3', name: 'Jane Doe', city: 'Frederick' id: '4', name: 'John Smith', city: 'Miami' id: '5', name: 'Tom Ford', city: 'Atlanta' After realizing angulars capabilities I would like to set up the list, with the ability to have the user filter based on names So my question is, How do I pass the NameList object to get populated with angular, or can I just populate the object and tie the list to angular somehow? This is what I have so far <div id="angularWrapper" data-ng-app="" data-ng-controller ="SimpleController"> <div>Name: <input type="text" data-ng-model="name" /> </div> @*I would like to pass Model.NameList to customers*@ <div<EMAIL_ADDRESS> <br /> <ul> <li data-ng-repeat="cust in customers | filter:name">{{cust.id + - + cust.name + - + cust.state}}</li> </ul> </div> Are you trying to call the server and load the results into the $scope.customers? I don't want to call the server. The NameList object comes from initial load. You are going to need to expand your question. Needs more details. We don't know what Model.NameList is. Good point @Jesus. I hope the edits makes the situation a bit clearer @MrM If you want to pass data from asp.net to angular, you can put a new API controller and request the data from angular. @JesusRodriguez that's where I am stumped... I had the answer posted by Beterraba set in a controller, but I just don't know how to pass the data to angular for the setup In your controller: $scope.customers = [ { id: '1', name: 'John Doe', city: 'Phoenix' }, { id: '2', name: 'Tony Hope', city: 'Queens' }, { id: '3', name: 'Jane Doe', city: 'Frederick' }, { id: '4', name: 'John Smith', city: 'Miami' }, { id: '5', name: 'Tom Ford', city: 'Atlanta' } ]; demo here : Plunker, but why question is tagged C# & asp.net & .net ? @dawuut because he wants to pass info from C# to angular. The list will not be hard coded to customers, like @JesusRodriguez said, the object will be coming from C# @MrM Then you shouldnt do comments like: "I don't want to call the server." :-P. @Beterraba.. apologies I think you're confused about how AngularJS binding works, you should read the guide on Data Binding: http://docs.angularjs.org/guide/databinding In the meantime here's a simple JSFiddle I think does what you're looking for: http://jsfiddle.net/mikeeconroy/75WPW/1/ <div ng-controller="myCtrl"> Name: <input type="text" ng-model="name" /> <ul> <li ng-repeat="cust in customers | filter:name">{{cust.id}} - {{cust.name}} - {{cust.city}}</li> </ul> </div> And the controller: angular.module('myApp',[]) .controller('myCtrl', ['$scope','mySrv',function ($scope,mySrv) { $scope.name = ''; $scope.customers = []; $scope.customers = mySrv.getCustomers(); }]) // fake service, substitute with your server call ($http) .factory('mySrv',function(){ var customers = [ {id: '1', name: 'John Doe', city: 'Phoenix'}, {id: '2', name: 'Tony Hope', city: 'Queens'}, {id: '3', name: 'Jane Doe', city: 'Frederick'}, {id: '4', name: 'John Smith', city: 'Miami'}, {id: '5', name: 'Tom Ford', city: 'Atlanta'} ]; return { getCustomers : function(){ return customers; } }; }); You could also set $scope.customers by using the resolve function of your route. I should note that the service call here is just to demonstrate how you may want to set up a server call, but in the service you're going to want to use promises, generated by calling $http or by using $resource and $q this way your interface isn't waiting on the server to finish. Although as I said before if this is all in a ngRoute then you may want to use the route's resolve function. This was actually helpful by pointing me in right direction. Thanks @m.e.conroy Great, glad I could help you out I should point out that the filter in the example will not only filter by name property of an object but by every property of the object so if you start typing the name of a city it will also filter on that. You can however filter on just a specific property, you'd have to change your ngModel from just name to something like name.id or name.name or name.city I came up with a solution that may have a possible alternative... <div id="angularWrapper" data-ng-app="demoApp" data-ng-controller="SimpleController"> <div> Name: <input type="text" data-ng-model="name" /> </div> <div> <ul> <li data-ng-repeat="eg in List | filter: name">{{ eg.Name }}</li> </ul> </div> <br /> <script> $(function () { var scope = angular.element('#angularWrapper').scope(); @foreach (var npo in Model.NameList) { @: scope.AddList({ Name<EMAIL_ADDRESS>}); } scope.$apply(); }); </script> </div> .js file function getList() { var self = this; self.Name = ""; } var demoApp = angular.module('demoApp', []); demoApp.controller('SimpleController', SimpleController); //could just load the function($scope) from simplecontroller.. function SimpleController($scope) { $scope.List = []; $scope.AddList = function (data) { var eg = new getList(); eg.Name = data.Name; $scope.List.push(eg); } }
common-pile/stackexchange_filtered
How to resolve the upper promise in a chained promise in TypeScript I have this method in a provider: get() { var debugOptionUseLocalDB = 0, prodata = [], serverAttempts = 0; return new Promise((resolve, reject) => { if (this.connectionStatus.f() === 'online') { return this.getDBfileXHR(this.dbUrl(), serverAttempts) .then(function (data) { // success console.log('-normal XHR request succeeded.'); resolve(data); }) .catch((reason)=> { ... }) } else{ ... } }) } And I am calling it from app.component.ts: this.updateProDB.get() .then( () => { let prodata = this.storageService.get('prodata'); this.imagesService.manageStoredImageUrlsNew(prodata); }) .catch((reason)=> { console.error('imagesUrl have not been managed, because updateProDb failed with error:' + reason) }); I am sure that this.getDBfileXHR() resolves because I see '-normal XHR request succeeded.' in the console. However, ̀ this.updateProDB.get()rejects, and we go to the.catch()̀`. Is resolve(data); the right way to resolve get() ? What is the rejection error? One option would be to instead of wrapping in a new Promise((resolve, reject) => { ... }) to instead just directly return this.getDBfileXHR(this.dbUrl(), serverAttempts) Yes but I need the wrapping, I removed some code here for clarity but there is some logic. Actually, I replaced return this.getDBfileXHR(this.dbUrl(), serverAttempts) .then(function (data) { // success by return this.getDBfileXHR(this.dbUrl(), serverAttempts) .then( (data) => { // success and its seems to work now....is it weird ? The get() resolves with data, but the caller ignores the result. Is that intentional? Furthermore, does this.storageService.get(... run synchronously? If not, prodData will be null when passed to manageStoredImageUrl() It's good that you've simplified the code for this post, but you may have removed too much. Yes storageService runs synchronously. Yes I don't need the result in the caller, so it's intentional, thanks for noting. Indeed, I may have removed too much, but I noticed that with too much code, there is often less help. So the resolve should be in an arrow function apparently, but how to manage this when you can't use => ?
common-pile/stackexchange_filtered
A generic list of generics I'm trying to store a list of generic objects in a generic list, but I'm having difficulty declaring it. My object looks like: public class Field<T> { public string Name { get; set; } public string Description { get; set; } public T Value { get; set; } /* ... */ } I'd like to create a list of these. My problem is that each object in the list can have a separate type, so that the populated list could contain something like this: { Field<DateTime>, Field<int>, Field<double>, Field<DateTime> } So how do I declare that? List<Field<?>> (I'd like to stay as typesafe as possible, so I don't want to use an ArrayList). It's an interesting idea to "stay as typesafe as possible", however, aren't you violating the http://en.wikipedia.org/wiki/YAGNI concept? Think about how are you going to access that list, do you really need it that specific? This is situation where it may benefit you to have an abstract base class (or interface) containing the non-generic bits: public abstract class Field { public string Name { get; set; } public string Description { get; set; } } public class Field<T> : Field { public T Value { get; set; } /* ... */ } Then you can have a List<Field>. That expresses all the information you actually know about the list. You don't know the types of the fields' values, as they can vary from one field to another. @Jon - Should the first class be a generic or just a simple class? @Giorgi, abstract class Field<T> looks like a typo. I've taken the liberty of correcting it. He still has to cast to get the actual value type... but this is about the only solution that I can think of too, without an actual "tuple" type. @tames, he's in a better position because the elements of his list must inherit from Field (or implement IField, in my example). The list is still more strongly typed than a list of objects @anthony... I agree, and I have used both interface and base class solutions. You can't declare a list of generic types without knowing the generic type at compile time. You can declare a List<Field<int>> or a List<Field<double>>, but there is no other common base type for Field<int> and Field<double> than object. So the only List<T> that could hold different kinds of fields would be List<object>. If you want a more specific type for the list, you would have to make the Field<T> class inherit a class or implement an interface. Then you can use that for the generic type in the list. Perhaps implement an interface. interface IField { } class Field<T> : IField { } ... List<IField> fields = new List<IField>() { new Field<int>(), new Field<double>() }; This leaves him in the same position because IField won't contain the type (T). Not a whole lot different from just using object because he'll still have to cast to get the value. @tames, he's in a better position because the elements of his list must implement IField (or inherit from Field, in Jon's example). The list is still more strongly typed than a list of objects. @anthony... I agree, and I have used both interface and base class solutions.
common-pile/stackexchange_filtered
Scipy Interpolation not good for fitting spot rates? Trying to calculate a simple spot rate of a bond that has 2 cashflows left. Maturity: 2025-05-15 Cashflows: $0.725$ coupon on 15-11-2024, then final on maturity Dirty price is $99.703$ If I calculate YTM the usual way, it ties up: $99.70 = \dfrac{0.725}{1.028061^{0.129}} + \dfrac{100.725}{1.028061^{0.625}}$ And, when I calculate the spot price of the last cashflow, I get $0.0283406$. This, as per below, ties up with the price: $99.70 = \dfrac{0.725}{1.028061^{0.129}} + \dfrac{100.725}{1.028061^{0.625}}$ But how can this value ($0.028$) be so different from my spot curve, which is coming from the univariate spline from the 4 points below? 0 Ttm Spot 1 0.129 0.032197 2 0.173 0.031714 4 0.342 0.030348 5 0.419 0.030995 Interpolation with in scipy.interpolate univariate interpolation You're not interpolating, you're extrapolating. That is, you're creating the spline with data from $t=0.129$ to $0.419$ and then you're asking it for values outside that range. It doesn't really have that information. Splines are especially bad for that, because you'll extrapolate with a cubic and it will become very large quickly. Plot your rates until $t=2$ or $3$ to see what I mean. If you want to have reasonable results for your home, you need more input data to cover that range. Does that mean that a lower degree polynomial (i.e. quadratic) works better for extrapolation? Do you have any references you can provide? Thank you! It doesn't work better; it might hide better the fact that you don't have information for that range of times. In general, using splines to interpolate or extrapolate yield curves is tricky and easily leads to "hallucinations". People do use splines, but they require tweaking / constraining to make economic sense. When trying to extrapolate, you might be better of with one of the following: If the yield curve of some related risky bonds is actually a spread over a riskless/swap curve, and you have more data for the swap curve, then assume that the spread stays constant beyond your last observation. See Interpolating a yield from two yields (giving more weight to one of the two) for more detailed discussion. If this isn't a spread over an underlying swap curve, then you could get the forward rate from the end of the yield curve that is observable, and extrapolate assuming the forward rate to be constant at longer tenors. We should also mention Nelson Siegel, although it's not helpful here. Thank you all! I have found this paper: https://cosspp.fsu.edu/econpapers/wpaper/wp2011_08_03.pdf which is extremely interesting and I think I will follow. Instead of extrapolating spots, it builds the forward curve with constraints and then calculates spots. But the most interesting part is at the end, which I will paste below: "The linear bootstrap with linear interpolation (LBLI) method is simply a piecewise linear interpolation of the spot curve using a bootstrap method to compute the spot rates at each node. This is straightforward for zero coupon bonds when the the spot rates at those maturities are directly observed. For bonds, we add one bond at a time and adjust the estimated spot rate up or down until that bond is correctly priced. Note that the linear segments determined in prior steps are not adjusted during this process. The resulting spot curve will be continuous but not differentiable at the ..ode points. Note first that the LBLI method produces zero pricing errors for both the zero coupon bills and the coupon bearing bonds. This is precisely what the LBLI algorithm is designed to do. The spot yields at each node are chosen to exactly price the security maturing at that node. Since there is no feedback from one node to previous nodes during the computations, zero pricing errors is an easy criteria to satisfy. The problem with this method is that, because the spot curve is piecewise linear, it produces discontinuities in the spot and forward curves at the nodes." If you work in an environment where models need to be reviewed / challenged by an independent model validation team, then simplicity - e.g. "this issuer has a 5-year bond trading with Z-spread n bps, therefore I assume that a new 10-year bond will have similar Z-spread", or "for this currency, 7Y and 10Y swap rates are observable, therefore I extrapolate the 15Y swap rate assuming constant forward rate" needs less explaining than something more sophisticated.
common-pile/stackexchange_filtered
PHP Fatal error: Call to a member function getBackend() on a non-object in I am getting an error on my websites home page including a custom attribute from my theme. PHP Fatal error: Call to a member function getBackend() on a non-object in /chroot/home/afgclass/WEBSITEDOMAIN/html/app/code/core/Mage/Eav/Model/Entity/Abstract.php Can you guys please help any suggestions? Sadly I have no backups ;( It's hard to tell what are you doing. However check this link Have you done any custom code in your application? Somehow you are using wrong attribute Id which is being checked by below function - #File: app/code/core/Mage/Eav/Model/Entity/Abstract.php public function isAttributeStatic($attribute) { $attrInstance = $this->getAttribute($attribute); $attrBackendStatic = $attrInstance->getBackend()->isStatic(); return $attrInstance && $attrBackendStatic; } So check your customization thoroughly. Got this reference from Alan Storm
common-pile/stackexchange_filtered
drawing commutative diagram I solved the problem I mentioned below, thank you very much for your suggestions. I want to use the diagram to appear in the article. I want to set the size according to the article in this example. I do not know whether I could express myself correctly. Thank you for all suggestions. Could you help me for drawing the following diagram ? What have you tried so far? Please show us the code ... I'd suggest you to read Prof. van Duck's TUGBoat article, (which was recently made publicly available) in which he thoroughly explains the basics of TikZ styles ans gives an example of a diagram. With that article you have the necessary tools to create the diagram you're asking us to do for you. Thanks for your suggestion, but I cannot draw it immediately and I need this diagram as soon as possible. I am not good drawing diagram at latex and do not have enough time. I am trying to conclude my paper in a few days. @FatmaErolKaynarca Everyone here's got things to do. People who answer questions here do it as a hobby, not as a job, so it's unlikely that someone will rush into drawing the complete diagram for you, simply because that's your job. Perhaps someone with enough free time will do all of it, perhaps they'll give you a start as Diaa did, and perhaps they will vote to close your question as "too broad" or something like that. That's why "do-it-for-me" questions are usually not very well received. @PhelypeOleinik I'm sorry to misunderstand myself. I know the people here are doing it to help someone. I didn't want to do my own job completely. Diaa's example was a good example what I wanted to do. I can't use the latex as well as you. What I want is an example that I can apply to my diagram. I'm sorry for taking your time... Please, check my answer edit and spend considerable time learning tikz. Have a nice day :) @FatmaErolKaynarca No need for apologies :) As I said, with this type of question you might or might not get the answer you want. That's why I pointed you a resource for you to learn to draw your own diagrams so that you don't depend on other people when you're short on time :) This is not a complete answer to your question. It is just a good example to start with knowing that there are many approaches to your problem. \documentclass{standalone} \usepackage{tikz} \usetikzlibrary{matrix} \begin{document} \begin{tikzpicture}[->,>=stealth] \matrix (dag) [matrix of nodes,% nodes={rectangle,draw}, column sep={2cm,between origins}, row sep={2cm,between origins}, ampersand replacement=\&] { \& |(1)| Start \& \\ |(11)| A \& |(12)| B \& |(13)| C \\ \& |(21)| End \& \\ }; \draw (1) to (11); \draw (1) to (12); \draw (1) to (13); \draw (11) to (12); \draw (12) to (13); \draw (11) to (21); \draw (12) to (21); \draw (13) to (21); \end{tikzpicture} \end{document} Edit I am not the TikZpert here in the slightest, but I spent some time converting your hand drawing into a simple code. Please, study it well since do-it-for-me questions are the most hated ones here :). \documentclass[12pt]{article} \usepackage{tikz} \usetikzlibrary{matrix} \begin{document} \begin{figure} \begin{tikzpicture}[->,>=stealth,] \matrix (dag) [matrix of nodes,% nodes={rectangle,draw}, column sep={3ex}, row sep={10ex,between origins}, ampersand replacement=\&] { \& |(01)| $\sigma$-rigid \& \\ |(11)| strongly $\sigma$-symmetric \& |(12)| strongly symmetric \& |(13)| symmetric \\ |(21)| strongly $\sigma$-skew reversible \& |(22)| strongly reversible \& |(23)| reversible \\ |(31)| strongly $\sigma$-IFP \& |(32)| strongly IFP \& |(33)| IFP \\ \& |(41)| Abelian \& \\ }; \draw (01.south west) -- (11.north east); \draw (01) -- (12); \draw (01.south east) -- (13.north west); \draw[<->] (11) -- node[midway,right]{text} (21); \draw (21) -- (31); \draw (31.south east) -- (41.north west); \draw (12) -- (22); \draw (22) to (32); \draw (32) -- (41); \draw[<->] (13) -- (23); \draw (23) -- (33); \draw (33.south west) -- (41.north east); \draw (11) -- (12); \draw (12) -- (13); \draw (12) -- (13); \draw (21) -- (22); \draw (22) -- (23); \draw (22) -- (23); \draw (31) -- node[above] {dummy} (32); \draw (32) -- (33); \draw (32) -- (33); \end{tikzpicture} \end{figure} \end{document}
common-pile/stackexchange_filtered
How to remove an part of values in R I have got a data frame like this: ID A B 1 x5.11 2,34 2 x5.57 5,36 3 x6,13 0,45 I would like to remove the 'x' of all values of the column A. How might I best accomplish this in R. Thanks! I have found a very easy way: data.frama$A <- gsub("x", "", data.frame$A)
common-pile/stackexchange_filtered
Join multiple table and bind into a single Listview using C# .net I got three tables to join named Books, Borrowers and Transactions. The database scheme is as below: Books(BookID,BookName,ISBN); Borrowers(BorrowerID,BorrowerName,BorrowerLevel); Transactions(TransactionID,BorrowerID,BookID,BorrowDate,ReturnDate); The corresponding class are Book, Borrower and Transaction respectively. Now i would like to select BookID,BookName,BorrowerID,BorrowerName,BorrowDate and ReturnDate from these three tables and to show in a listview having gridview control. XAML Code : <Grid> <ListView Margin="15,57,58,57" Name="borrowedBookList" IsSynchronizedWithCurrentItem="True" ItemsSource="{Binding }" KeyDown="borrowedBookList_KeyDown"> <ListView.View> <GridView> <GridView.Columns> <GridViewColumn Width="80" Header="Borrower ID" DisplayMemberBinding="{Binding Path=BorrowerID}"/> <GridViewColumn Width="220" Header="Borrower Name" DisplayMemberBinding="{Binding Path=BorrowerName}"/> <GridViewColumn Width="220" Header="Book Name" DisplayMemberBinding="{Binding Path=BookName}"/> <GridViewColumn Width="100" Header="Date" DisplayMemberBinding="{Binding Path=BorrowDate}"/> <GridViewColumn Width="100" Header="Return Date" DisplayMemberBinding="{Binding Path=ReturnDate}"/> </GridView.Columns> </GridView> </ListView.View> </ListView> </Grid> Now how can i join these tables and assign the result datacontext into borrowedBookList? Thankyou Arefin Sami borrowedBookList.DataSource = from borrower in Borrowers join transaction in Transactions on borrower.BorrowerID equals transaction.BorrowerID join book in Books on transaction.BookID equals book.BookID select new { borrower.BorrowerID, borrower.BorrowerName, book.BookName, transaction.BorrowDate, transaction.ReturnDate, } borrowedBookList.DataBind(); If my answer is working for you, you should upvote it and click the green arrow to accept it. Thom, i have another question. Check it out. i think you can help me. Thank you. have you looked into the hierarchicaldatatemplate class? Your model or viewmodel would need to contain the respective relationships. From there, the appropriate datatemplate should work nicely.
common-pile/stackexchange_filtered
How would one know a charms dependencies? If really really novice user is using Juju and wants to deploy wordpress how would he come to understand that mysql is required to deploy it. If you take another product xyz which isn't as popular as wordpress and has no deployment related articles available through google, then in this case the user has to go through a chain of activities on the terminal to finally understand and deploy the xyz product. The user has to do something like this on the terminal : charm get xyz or wget xyz from somewhere cd xyz cat config.yaml read the "requires" interface goto http://charms.kapilt.com/interfaces find the charm that provides the interface , say charm "abc" charm get abc execute juju deploy, etc You see what I mean... unless there is another way that I'm not aware of. How would one know a charms dependencies ? What you're talking about is called the "dependency resolver" in package managers. juju doesn't have one of these right now. But the idea is that it would work like apt, if you did a juju deploy wordpress it would know that you needed mysql or another database and give you some recommendations. This is actually more complicated than it seems, which is why we don't have it. In terms of deployment let's say you are deploying mediawiki and you have 3 mysql services already deployed, do we prompt you for a new one or do we just let you decide if you want to deploy a new one or explicitly specify which one you want to use? And that's just a 1-to-1 service relationship, when you have more levels to the stack each level complicates what you'd think you'd want to recommend. (This is why it's not in juju, we need to carefully think about how this would work before building assumptions into the tool). However there are 2 ways we're working on this to make it better: Charms should have a README file that explains how to use them. So a charm could say in it's deployment directions "I need mysql", but not all charms have them, including what other services are required. This is something we hope to improve by 12.04. We're working on the Charm browser to make it more obvious what a charm requires right on the charm's web page. Here is the bug report for the spec for the feature: https://bugs.launchpad.net/juju/+bug/732194 How do I subscribe to a bug?
common-pile/stackexchange_filtered
Java - too many BigDecimals? For more info, see my other question, here. So anyway, I'm using BigDecimals to represent currency in my application (it deducts a markdown percentage and adds sales tax), but it seems that If I use a BigDecimal for the price, everything needs to be BigDecimals. Is it OK to use a BigDecimal for the markdown percentage field (instead of a float), and also for the PST and GST constants (sales tax, 0.08 & 0.05)? Oh and also, do you think I should store the markdown field in percentage or decimal? Either way, I would have to convert it to the other for display, since I show p / 100 = d. And subtotal means the total cost before tax, right? Thanks!! Different industries will have different standards for this. In finance, for example, it's common to do calculations to 5 or even 8 decimal places even if you're only display 2 or 3. BigDecimals are preferred for being completely accurate for multiplication, addition and subtraction (division isn't normally an issue when it comes to currency amounts). Yes its fine - unless you have a specific problem - memory usage or something - stick with BigDecimals. You might find the NumberFormat useful for formatting. Yes I am using that, check my other question I posted to see the 24 comments on an answer where I figured out what way to format and display and store them :-).
common-pile/stackexchange_filtered
db2 rowset cursor parametrization Would there be a way to program a parameter that is not hard coded to this? In place of :SomeValue host variable in this question/snippet: EXEC SQL FETCH NEXT ROWSET FROM C_NJSRD2_cursor_declared_and_opened FOR :SomeValue ROWS INTO :NJCT0022.SL_ISO2 :NJMT0022.iSL_ISO2 etc.... Here is some clarification: Parametrization of the request like posted in opening question actually works in case I set the host variable :SomeValue to 1 and define host variable arrays for filling from database to size 1 like struct ??< char SL_ISO2 ??(1??) ??(3??); // sorry for Z/os trigraphs etc.. And it also works if I set the host variable arrays to a larger defined integer value (i.e. 20) and hard code the value (:SomeValue) to that value in cursor rowset fetch. EXEC SQL FETCH NEXT ROWSET FROM C_NJSRD2 FOR 20 ROWS INTO :NJCT0022.SL_ISO2 :NJMT0022.iSL_ISO2 ,:NJCT0022.BZ_COUNTRY :NJMT0022.iBZ_COUNTRY ,:NJCT0022.KZ_RISK :NJMT0022.iKZ_RISK I wish to receive the number of rows from the calling program (COBOL), a and ideally set the size of host variable arrays accordingly. To avoid variable array sizing problem, oversizing host variable arrays to a larger value would be good also. Those combinations return compile errors: HOST VARIABLE ARRAY "NJCT0022" IS EITHER NOT DEFINED OR IS NOT USABLE Question is unclear, because :SomeValue is a host-variable, and therefore not necessarily hard-coded. That syntax is supported by Db2-for-Z/OS v10 and higher. A host variable can not be used but a only a hardcoded number. This is why I'm asking and the question should be clear enough. Rowset cursors are enabled since DB2 v8 I think please edit your question to add the version of the Db2-for-z/os at your site, and also add the exact error message you get when you try the hostvariable. And in good tradition here is an answer to my own question. The good people of SO will upvote me for sure now. Rowsets are very fast and beside making host variable arrays arrays or for chars array arrays these cursors just require adjusting program functions for saving values and setting null values in loops. They are declared like this: FETCH NEXT ROWSET FROM C_NJSRD2 FOR 19 ROWS Rowset cursors can not change host array (that is array array) size dynamically. Unlike scroll cursors they can not jump to position or go backwards.They can however go forward not by the whole preset rowset number of rows but just by a single row. FETCH NEXT ROWSET FROM C_NJSRD2 FOR 1 ROWS INTO So to answer my question, to make the algorithm able to accept any kind row number requested for fetches it is basically just a question of segmenting the request to rowsets and eventually one line fetches until the requested number is met. To calculate loop counters for rowsets and single liners: if((iRowCount>iRowsetPreset)&& ((iRowCount%iRowsetPreset)!=0)) ??< iOneLinersCount = iRowCount % iRowsetPreset; iRowsetsCount = (iRowCount - iOneLinersCount) / iRowsetPreset; ??> if ((iRowCount==iRowsetPreset) _OR_ ((iRowCount%iRowsetPreset)==0)) ??< iOneLinersCount = 0; iRowsetsCount = iRowCount / iRowsetPreset; ??> if (iRowCount<iRowsetPreset) ??< iOneLinersCount = iRowCount; iRowsetsCount = 0; ??>
common-pile/stackexchange_filtered
.NET Double storage in DataTable? .NET looks like it's formatting a double inside a DataRow in the wrong format, so i can't load it in a second moment. If I store "0.000000001", .NET stores it as "1E-09.0", when it should be "1E-09". So Convert.ToDouble("1E-09.0") returns a FormatException. Here it is the code i use: // create table DataTable t = new DataTable("test"); t.Columns.Add("FirstInt", typeof(int)); t.Columns.Add("SecondDouble", typeof(double)); t.Columns.Add("ThirdInt", typeof(int)); // create row data object[] data = new object[] { 10, 0.000000001, 10 }; // add row data: "0.000000001" is stored as "1E-09.0" t.Rows.Add(data); // FormatException is thrown here, since "1E-09.0" should be "1E-09" double d2 = Convert.ToDouble(t.Rows[0]["SecondDouble"]); I also tried with cast, but the code throws me "InvalidCastException". The Double.Parse doesn't work as well. Solution: // create table DataTable t = new DataTable("test"); t.Columns.Add("FirstInt", typeof(int)); t.Columns.Add("SecondDouble", typeof(string)); // convert double to string t.Columns.Add("ThirdInt", typeof(int)); // create row data and convert value to string double value = 0.0000000001; string valueString = value.ToString("F9"); object[] data = new object[] { 10, valueString, 10 }; t.Rows.Add(data); // load data double d2 = Convert.ToDouble(t.Rows[0]["SecondDouble"]); How about double d2 = (double)t.Rows[0]["SecondDouble"];? Same. I updated the question to include casting. That sounds strange. Can you show the type of column from your real code? Console.WriteLine(t.Rows[0]["SecondDouble"].GetType());. SecondDouble column has different type from double (most probably string). In that case try to find the place where data is added to the table. Or redefine the table column to be of double type and change loading method. I actually did the opposite and it worked: stored double values as string, converting them to F9 format, then loaded. I can't reproduce your issue, and I don't see how the code you posted could produce your issue at all. A DataTable does not store a double value as "1E-09.0"; all it does is boxing it into an object. 1E-09.0 is just a representation, not the actual value of the double. Maybe in your real code there's something else going on? Nope, my code works exactly the same. .NET always convert the value 0.000000001 as 1E-09.0, if i specify the column type as double and i store the number with the DataTable.Rows.Add(object[] data) method. Now i forced all columns to have string type. In that way i can manage the double -> string convertion when creating the table and string -> double convertion does not throw the FormatException anymore.
common-pile/stackexchange_filtered
Set z-index to dynamically generated image label to prevent overlapped label hidden from image I am implementing drag and drop, user can drag few images and drop them in a div, and I dynamically append a p tag as label to each image once user click on a button. Currently I meet problem when I have 2 images which is very close to each other (one is on top of another). The appended p tag for the top images will be hidden by the bottom image. I tried to alert the z-index for each dropped image, and found out it is 'auto'. I guess I need to assign a new z-index for each div, but I tried in the function which i append the label, and it dint work as expect: function generateLabel() { var current = 5000; $('#rightframe img').each(function () { var cImgName = $(this).attr('id'); var width = $(this).width(); // To select the respective div var temp = "div#" + cImgName; $.ajax({ url: '/kitchen/generatelabel', type: 'GET', data: { containerImgName: cImgName }, async: false, success: function (result) { $(temp).append(result); // I guess the each function loop through each div according to the time it is created, so I try to assign a decreasing z-index $(temp).css('z-index', current); current -= 100; // To select the label for the image temp += " p"; // Set label width based on image width $(temp).width(width); } }); }); However, what I get is, bottom image which dropped later do NOT hide the label of the image above, but if the above image is dropped after than the bottom image, above image's label is hide by the bottom image. It's a very specific situation and I hope I do make myself clear... Hope can get some help here... Appreciate any feedback... do some drag and drops until your problem appears... check the z-indexes of theese elements. i i got threw your script i think you dont get the result as you except with the z-indexes. I am so glad that I able to work out a solution for this kinda weird problem. I get to one useful plugin, the jquery-overlaps which check 2 dom whether they are overlapped with each other or not. Then i assign a z-index to the label accordingly. Just to show my solution here, in case anyone jump into this bottleneck :) // To assign an increasing z-index to the label var count = 100; $('#rightdiv p').each(function () { // If any label overlaps with the image (used overlaps plugin) if ($(this).overlaps($('#rightdiv img'))) { // Increase count (the z-index) count += 10; // Set the parent div z-index 1st, if not the label z-index do not have effect $(this).parent().css('z-index', count); $(this).css('z-index', count); } }); Thanks! :D
common-pile/stackexchange_filtered
Ad words conversion without GDPR consent Is it possible to track Google Ad conversions on a marketing site, cookieless and without the GDPR consent? There are articles like such that explain that you can create a hash combining the IP address, user agent, and other data, to use that for tracking instead of cookies: https://helgeklein.com/blog/2020/06/google-analytics-cookieless-tracking-without-gdpr-consent/ However it only applies to Google Analytics, and I'm not sure if something similar is possible with Google Ads. Is anyone using, or aware of a conversion tracking mechanism that does not paradoxically decrease conversions through these terrible GDPR consent banners? I will describe a method which one of my friend's businesses used in the past. Though his use case was different, I think the same solution could work in your case. Though I can give you an outline of the method, you have to work on the nuances and implementation. The method involves importing conversions offline on a schedule. Steps follow: Google (with auto-tagging enabled) passes CGLID (unique to every click) along with every click. Ref: https://support.google.com/google-ads/answer/9744275?hl=en You have to store the converting GCLIDs with other parameters that may be required as part of step 3. You have to import conversions into Google Ads using CSV files. Templates and method have been discussed in detail at https://support.google.com/google-ads/answer/7014069 Yes, you need consent for conversion tracking, remarketing and other personal data collection/usage in the GDPR zone. GDPR forces us to gain consent for using and collecting personal data of EU users with Google Ads campaigns. Thing is - I don't care about my users data. I care how much Ad X led to conversions vs Ad Y. I'm trying to figure out a way to do it and keep it all anonymous.
common-pile/stackexchange_filtered
jar file does not open I created a jar file for my project , but the following warning appeared , and when double click on it , it does not open warning: [options] bootstrap class path not set in conjunction with -source 1.6 1 warning I'm using NetBeans 7.0.1 / Windows 7 The warning is not necessarily the problem with making it clickable. To make a JAR executable, you have to specify the 'main' class in the JAR's 'manifest' file, for example: Manifest-Version: 1.0 Main-Class: MyMainClass You then create the jarfile, specifying the manifest file above. If doing this manually, it's something like: jar cvfm myapp.jar myManifest *.class If you created the JAR from NetBeans instead, I expect there's a setting for this: Updated see Producing executable jar in NetBeans for information on this. If you don't specify the main class, then the JAR can be used as a library, but it can't be executed directly as a program without using a commandline script to specify which class to run, e.g. java -cp myjar.jar com.myco.myproj.MyMainClass which runs Java, putting your jarfile on the classpath (i.e. making all your classes available) and specifies that MyClass is the main class, i.e. the starting point for your application. MyClass must have a main method defined, or this won't work. sorry for my question , but how to specify the 'main' class in the JAR's 'manifest' file??? With its fully qualified name, like mypackage.myinnerpackage.MyMainClass. @DNA : Thanks any way, but I'm using netbeans , and I do not know from where to change these lines. Updated my answer - see the answers to this question which explain how to do this in NetBeans @DNA : Thanks. one more thing , why the jar file does not open file that I put them in the package , although they opened from the program??? I'm not certain what you mean - if you mean that you want your application to load a file from within the JAR, then you need to use the getResource() method to load a file from the classpath, rather than just creating a Stream or reader from a File object to load data from the file system. @DAN : one of my packages in my project coantains ".chm file". There is no problem when I opened it from the program, but when I make the jar, the .chm did not open when I clicked the button "help" The warning suggests that there may be a difference between the version of Java that some of your libraries/dependencies are written in and the version you compiled your project with. In my experience, this warning can usually be ignored. But that is certainly anecdotal. In the future, the warning can be disabled with the flag -Xlint:-options in "additional compiler options" in Netbeans. A more official explanation can be found here. Does it not open so that you can see the jar/zip contents? Or does it not execute? If you are trying to make it execute you need to make sure the project was compiled in that way. If it was compiled correctly and execution is still a problem, then I think you ran afoul of a problem with one of your dependencies being written for an older JVM than your code was compiled with. (If so, you should give us more information and see if we can determine which library is your problem and if there is a newer version that would suit you.) it does not execute. I run the project without errors , and it works fine. The jar file exists ,but not opening .
common-pile/stackexchange_filtered
Cutting one's nails at night I recently asked a friend if I could borrow his nail cutter, but he told me that he would prefer I do it in the morning because it isn't good to cut one's nails at night. When I asked him why, he told me it's some kabbalah stuff but he wasn't sure. Another friend also told me this, but he didn't know the details. I had never heard of something like this and it seemed kind if weird. Is this a thing? What is the reason for this? http://www.yahadoot.net/Answer.asp?id=322 @hazoriz Thanks, but you can't take for granted that everyone on this site is hebrew-fluent. I personally can't understand at that level. @Gabe12 I do not take it for granted (I myself was not fluent at all until recently) but if someone askes me I will be happy to do a Jew a favor @Gabe12 He brings a source that explains the reason why it should not be done (even after midday) and then brings a few sources (including the source that why it should not be done) that halachakli it is ok @hazoriz And what is that reason? @Gabe12 My unprofessional translation "since night is the time of judgements (opposite of kindness), and also nails are a place of impurity, and we should not cut them and provoke the forces of impurity in their time, which is night, similar to there are those that say that according to the secret (kabolo) it is forbidden to get a haircut at night." Others don't worry about these sorts of thins and regard them as mere superstitions. Note that apparently not clipping nails at night is a non-Jewish superstition. http://en.rocketnews24.com/2015/03/26/clipping-your-nails-at-night-may-cause-death-according-to-a-japanese-superstition/ Rabbi Dershowitz at Dinonline quotes the following regarding a source for not cutting nails at night: See Shu”t Yechave Daat from Rav Ovadia Yosef 4:20 who quotes from Rav Chaim Palagi that according to the kabala one should not cut hair or nails by night. Rav Ovadia disputes this, and claims that there is no problem according to halacha or kabbala to do so at night. The great answer hazoriz linked seems to be saying the issue of cutting nails at night is due to "nighttime being a time of judgement. Therefore, cutting the nails, which are an area of tumah, would be considered tantamount to awakening the powers of tumah."
common-pile/stackexchange_filtered
Spring PropertyPlaceholderConfigurer and passing multiple queries at startup I am working on some existing application and it loads single DB query at server startup . Now I want to pass more (may 3-4 queries) in same code instead one query. i.e.How I can pass multiple queries in spring Here is code- myspring.xml <property name="mypropertyfiles"> <list> <value>test1.properties</value> <value>test2.properties</value> </list> </property> <bean id="mybean" class="com.test.MyBean"> <constructor-arg><ref-bean="mypropertyfiles"/><const-arg> <constructor-arg><ref-bean="dataSource"/><const-arg> <constructor-arg><value>select pcode, pname from PRODUCT1</value> // Here only one query. **but I want to pass more queries like** //select pcode, pname from PRODUCT2, //select ocode, oname from ORDER1, //select ocode, oname from ORDER2 <const-arg> <property name="systemPropertiesModeName" value="SYSTEM_PROPERTIES_MODE_OVERRIDE" /> </bean> MyBean.java public class MyBean extends PropertyPlaceholderConfigurer { private DataSource dSource; private String dbQuery; // this is existing map to store PRODUCT1 table details Map product1Map = new ConcurrentHashMap(); //lly, I will create more product2Map,order1Map , order2Map to store my //queries data from PRODUCT2,ORDER1,ORDER2 tables // here it is taking only one query.But I want more queries ie list MyBean (Resource[] resources , DataSource dSource,String dbQuery){ super(); setLocations(resources); this.dSource=dSource; this.dbQuery=dbQuery; } @override public String resolvePlaceholder(String p,Peroperties p){ //some code..... loadQuery(); } loadQuery(){ JdbcTemplate j; j.execute(dbQuery,.......) // exsiting code has one query only{ public Map doInPreparestament(Preaprestatement ps){ rs =ps.executeQuery.. while(rs.next){ product1Map.put(rs.getString("pcode"),rs.getString("pname")); // only one map } } } } Questions - How I can pass multiple queries from "myspring.xml" file I want to use existing loadQuery method to load all my queries and put into other Maps i.e. product2Map,order1Map ,order2Map What's the point in having those queries in XML? Why not just put them in the code? this is existing code and don't want to change structure so thought if it possible to send all queries once from XML file.
common-pile/stackexchange_filtered
javascript concat() method adds newline randomly I'm writing a JS code that reads the checkboxes in a particular , checks if they're selected, and if yes, appends their value to a string. This is the code that I have: var checkboxArr = document.querySelectorAll('#div_name input[type="checkbox"]'); var str=""; for(var i =0; i< checkboxArr.length;i++){ var cb = checkboxArr[i]; if(cb.checked){ var newVal=cb.value; str=str.concat(newVal); str=str.concat(","); } } alert(str); The string that I get is: value1 ,value2 ,value3 How are these newlines coming in the string ? Also, the occurance of these newlines is random - sometimes they appear, sometimes I get the desired string. I also tried combining the concat() calls into 1 statement, and I used the += operator as well, but no luck. Any guidance is earnestly appreciated. Thanks Can you paste your HTML? check the page source in the browser (usually Ctrl+U in good browsers) - look at the value="whatever" for the check boxes ... is the last " on a new line? also, I suspect the values are actually not that short and you are simply misinterpreting the alert (also, you have no trailing , in the sample output, which you would surely get given your code) - use console.log instead of alert, see if the same mysterious new lines appear in the console That's all you need. Use js right :D var checkboxArr = document.querySelectorAll('#div_name input[type="checkbox"]'); var str = []; checkboxArr.forEach(function(cb) { if (cb.checked) str.push(cb.value); }); alert(str.join(', ')); and if you still have the same result check your html code. It seems like you have line break right after your value in checkbox filter and map would be nicer.. ;) yep, maybe. but forEach is always easier for noobies concat - is array method, not string method - then his code wouldn't work at all - according to your logic, String#concat doesn't exist, but it works, and adds a newline for your trouble I agree that string.concat is not what you want to use - but your answer would make no difference to the result given the same input "use js right" ... exactly - var str = [].filter.call(document.querySelectorAll('input[type="checkb‌​ox"]'), cb => cb.checked).map(cb => cb.value).join(); thanks, I know how 2 use call method or what U meaning :) have a nice day. Add ', ' in your join check implementation with ES6, not sure why you are getting new line, var btn = document.getElementById('btn'); btn.onclick = function(){ var checkboxArr = document.querySelectorAll('#div_name input[type="checkbox"]:checked'); var res = Array.from(checkboxArr).map(cb => cb.value.trim()).join(',') console.log(res) } <div id="div_name"> <input type="checkbox" value="cb_1" /> <input type="checkbox" value="cb_2" /> <input type="checkbox" value="cb_3" /> <input type="checkbox" value="cb_4" /> <input type="checkbox" value="cb_5" /> </div> <button id="btn">Check</button>
common-pile/stackexchange_filtered
Rollover Roth 401(k) when not eligible for Roth IRA I recently changed jobs and am in the process of rolling over my 401(k) to my standard brokerage account where I have a number of rollover IRAs. This time, however, I have both a 401(k) to Traditional IRA rollover but also $400 in a Roth 401(k), which is new to me. I'm stuck on how to proceed, due to what I see are the options available and the following roadblocks: From what I can tell, I am not eligible to open a Roth IRA (MAGI is too high). I am under 59 1/2 and the account is less than 5 years old so I can't take a penalty free distribution. My new employer's plan does not allow Roth 401(k) rollovers or contributions. It does not appear that I can keep the money in my current account unless I keep both the 401(k) and Roth 401(k) together, which I prefer not to do. With the small amount, I'm not worried about having to pay something to the IRS for this, but with all of the variables at play, I feel the wrong first step will result in penalties otherwise avoided. Additionally, my Roth 401(k) has an $11 loss at this point, so there's no growth. Any suggestions of how to proceed? Thanks! Your income may be too high to make a new deposit into a Roth IRA, but that is not what you are trying to do. Regardless of your income, you are allowed to create the new account to either receive Roth conversions, taking funds from a traditional pretax IRA and converting them to Roth or in this case, receiving funds from a Roth 401(k). The receiving broker should be more than happy to provide you with the paperwork and instructions on how to accomplish this. Contribute anyway to a Roth IRA! If you want to do a Roth IRA contribution and your salary is too high, google "Roth Backdoor". That is an intentional way to allow people to contribute, though it has odd complications if you have any traditional IRAs currently. If you aren't in a position to convert all your traditional IRAs to Roth, expect some taxes due, and weird paperwork. Rollovers from 401K to IRA. These are allowed, and are not considered "contributions", but are considered simply rollovers. Therefore, they don't count toward your contribution limits. There is generally no tax consequence for a 401K to IRA conversion. I wouldn't bother with a 401K to IRA rollover. 401K's are actually Federally protected, whereas an IRA can be taken from you by a state lawsuit in the wrong state. ... Unless you are being taken advantage of by the management company. Roth conversion is fine, but... You don't get to "rollover and convert" in a single motion. You need to decide whether you're converting to Roth inside your 401(K) before you roll it over, or inside your IRA after you roll over. The issue is that an "after you rollover" Roth conversion may have weird interactions with the Roth Backdoor mentioned above, if you don't convert all your IRAs to Roth in that year. Investing generally Additionally, my Roth 401(k) has an $11 loss at this point, so there's no growth. Yeah, that's not how investing works. Long term growth and short-term volatility are a matched set: if you want the highest long-term growth (and in an IRA you certainly do), then you accept the highest short-term volatility. Volatility is the small ups/downs. For instance there was a small "down" in 2020 during the late-February uncertainty and the March lockdowns of COVID. At the time, people thought it was the end of the world, but you can see it was just a blip. Heck, there'd been one in late 2018 and there was another last month. Your #1 goal is to make reliable investments in whole markets, which John Bogle discusses in his book "Common Sense on Mutual Funds". And then, to minimize expenses and fees, because those are a guaranteed total loss. DON'T evaluate investments by whether they made or lost money this month. Evaluate them by how they did compared to the index that they best reflect. So a US large-cap fund would be compared to the S&P 500. The S&P took a bit of a dive in the last month (4766 down to 4400; recovering now) so I'm not surprised your last month's performance was low. The question was, how was it compared to the index? Take your $16 loss, figure it out as a percentage, then look at the S&P 500 (or more appropriate index) values for the start and end day. You're not going to beat the index (science proves no stock picker's managed fund can beat the index by more than expenses and fees, other than by being lucky). But how close you come tells you how much of your investment is being eaten by fees or bad investments. his time, however, I have both a 401(k) to Traditional IRA rollover but also $400 in a Roth 401(k), which is new to me. Rollovers can always be done, regardless of how much you make this year, or how much is being rolled over. If you don't change the flavor there are no taxes due. That means that pre-tax goes into a traditional IRA, company match goes into a traditional IRA, and Roth goes into a Roth. One issue you may have is the low balance of $400 in your Roth account. Many of your investment choices will have a minimum advancement amount, and you might not be able to put that $400 into the investment that you want. Some may allow you to start with a low amount, if you can also set up a recurring deposit. I would make sure before rolling over the funds that you understand that your investment option with the $400.
common-pile/stackexchange_filtered
is there some option in curl to set the tcp reset timeout? I have a client and server using http to transmit files, I used tcpdump found that, every time after recieving the http header, the server sends a ack, but then the server receive 2 reset packet, some times recieve reset after successfully receiving a packet contain http content. the timeline of tcpdump data at the server side looks likes bellow: 01:10:01.553222------data:http header 01:10:01.553233----------ack 01:10:01.590075-----------reset 01:10:01.590103-----------reset the curl option setting code: curl_easy_setopt(curl_obj, CURLOPT_URL, url.c_str()); curl_easy_setopt(curl_obj, CURLOPT_WRITEFUNCTION, WriteData); curl_easy_setopt(curl_obj, CURLOPT_WRITEDATA, &sbuf); curl_easy_setopt(curl_obj, CURLOPT_COOKIEFILE, "cookie"); curl_easy_setopt(curl_obj, CURLOPT_POST, 1L); curl_easy_setopt(curl_obj, CURLOPT_READFUNCTION, ReadCallback); curl_easy_setopt(curl_obj, CURLOPT_READDATA, this); curl_easy_setopt(curl_obj, CURLOPT_POSTFIELDSIZE, block_size); curl_easy_setopt(curl_obj, CURLOPT_NOPROGRESS, 0); curl_easy_setopt(curl_obj, CURLOPT_PROGRESSFUNCTION, ProgressCallback); curl_easy_setopt(curl_obj, CURLOPT_PROGRESSDATA, this) So, what I want to ask is, is there some options in libcurl to set the timeout for reset tcp when not recieving a sent data's ack in some limited time? if the client and server are in the same city and have a fast internet connection, this system works fine, so there should not be some bugs in the business code. ps: curl returns errorno 56 Too many assumptions here. You are assuming that the resets are issued as a result of a timeout. They can be issued for other reasons. What behaviour are you experiencing at the application level that caused you to get this tcpdump? There are multiple callback options that allow the application to access the socket directly, like CURLOPT_SOCKOPTFUNCTION and CURLOPT_OPENSOCKETFUNCTION. But like a commenter on this question, I doubt that is the actual reason (or solution) for your problem.
common-pile/stackexchange_filtered