source
list
text
stringlengths
99
98.5k
[ "stackoverflow", "0050407771.txt" ]
Q: Connect two devices with websockets I am new to websockets, please excuse me if the answer to my question is too obvious. I'm using websocket-sharp, as my goal is to build a Unity3D client that connects to a server. (Actually I want to build it for webGL platform, so the client will be written in javascript). For now, both client and server are written in C#. When compiled on localhost it works perfectly, also with multiple clients and also over a secure connection using a self-signed certificate. It also works fine if the client connects to an echo server (ws://echo.websocket.org). So I moved forward and I tried to connect two of my computers. The idea was to run the server on linux and execute the client on a mac, so I substituted "localhost" for the linux IP on both client and server codes. When I execute it, Unity (client) keeps saying me "Not a local IP address" and it doesn't connect. I thought this could be a firewall issue, and that first I should open the port used... Is that the case? If so, how can I open a concrete port on mac and on linux? A: Finally I solved it. It was an issue with the server code, I don't know where was the error. Instead of using my c# server I used Node.js, and it works fine. I can connect from other computers without problems.
[ "apple.stackexchange", "0000288333.txt" ]
Q: Can you have symlinks across various backup disks/ volumes? Is it possible to have two backup disks, which, when connected to the same machine, can have directories symlinked to each other? I'm working on this triple redundant backup scheme in which not all data is replicated across all three disks, but when working in a given disk, I would still like to have access to files and scripts on another remote disk. A: Yes, symlinks can be pointed anywhere. They’ll only function correctly when the destination is mounted, but that’s to be expected. Something which might not be expected is if for some reason the path doesn’t match. The most likely reason would be if an incorrect mount occurred previously or two partitions have the same name, causing one partition to mount as /Volumes/Name (1), which won’t match what your symlink is looking for. If something doesn’t seem right, check everything is in order in your /Volumes folder.
[ "stackoverflow", "0055153682.txt" ]
Q: Render items | React Native Hi guys I have such a question. I have a token stored in AsyncStorage. How do I do if token = = = null I loaded Button 1 on the page, and if something is loaded in token Button 2 ? Please help me. A: The best way to do conditional rendering is by making use of states. First, create a state variable which will hold your condition with or without initial value based on what your logic is. this.state = { conditionalVariable : false } Second, create a variable that will hold your JSX to be rendered, inside the render method. ` render() { ... let conditionalContent = null; ... } Third, as soon as your token is available in your async storage, update/set your state. this.setState({ conditionalVariable : token }) Before you return, write your logic based on what tags to return when. ` if (conditionalVariable == token1) conditionalContent = <Button1 />; else if (conditionalVariable == token2) conditionalContent = <Button2 />; else conditionalContent = ''; // dont display Finally, inside your return, use your variable within {}. <View>{conditionalContent}</View> This way whenever your state is updated, your views will re-rendered.
[ "stackoverflow", "0035383352.txt" ]
Q: Combine two python list using its value logic - Python I would like to combine two lists in Python to make one list in the following way: a = [1,1,1,2,2,2,3,3,3,3] b= ["Sun", "is", "bright", "June","and" ,"July", "Sara", "goes", "to", "school"] and the output: c= ["Sun is bright", "June and July", "Sara goes to school"] A: Use a for loop to first accumulate the words into some kind of mapping data structure, and then use a list comprehension to create the desired output. >>> from collections import defaultdict >>> d = defaultdict(list) >>> for k, v in zip(a, b): ... d[k].append(v) ... >>> [' '.join(d[k]) for k in sorted(d)] ['Sun is bright', 'June and July', 'Sara goes to school'] A: Assuming that: a and b have the same length a is ordered a begin with 1 Try: a = [1,1,1,2,2,2,3,3,3,3] b= ["Sun", "is", "bright", "June","and" ,"July", "Sara", "goes", "to", "school"] c = [] for i in range(len(a)): if len(c)<a[i]: c.append(b[i]) else: c[a[i]-1] += " " + b[i] print c
[ "math.stackexchange", "0000466319.txt" ]
Q: Distributive Property Theory question I've been wondering about the theory behind the distributive property lately. For example: 2(pi * r^2) is just 2 * pi * r^2. However, when you add a positive number like +3. You get 2(PI*r^2 +3). But, that isn't just 2*PI*r^2+3. Its: 2pi*r^2 + 2*3. So I was wondering why that is. Why do you only have to multiply once with the whole multiplication part(with pi^r2), instead of having to multiply 2 by both pi and r^2. So then I thought isn't it just: (pi * r^2 + 3) + (pi * r^2 + 3)? Then, I tried to simplify that, thinking it would help me understand why...but all that did was make me more confused than when I started. Could someone help me understand please? A: So one thing to be absolutely certain about is that the Distributive Property is only relevant when there is both addition(or subtraction) combined with a common multiplier (or divisor). For example: 3(x) = x + x + x = 3x 3(x + 1) = (x + 1) + (x + 1) + (x + 1) = 3x + 3 Now, as for your original question regarding 2(pi*r^2): Notice that 2(pi*r^2) contains no addition or subtraction; therefore, the distributive property should not be used. When you want to add 3 to this expression, it starts to get tricky. 2(pi*r^2 + 3) = (pi*r^2 + 3) + (pi*r^2 + 3) = 2pi*r^2 + (3 + 3) = 2pi*r^2 + 6. Hopefully this makes the use of the distributive property a little clearer. Again, the important thing to remember is that for the distributive property to apply, there needs to be both multiplication AND addition. If one or the other does not exist in your expression, then the distributive property does not come into play, and you have to deal instead with the commutative property as well as good old Order of Operations. A: The distributive property, and most basic properties of real numbers, comes from geometry. A non-negative value corresponds to the length of a line segment. Adding values corresponds to placing two segments together and measuring their length. Since the order that the segments are placed does not change the total length, addition is commutative. Looking at three segments, the length is the same if the first two are placed and then the third, or the last two are placed and then the first. Therefore addition is associative. Multiplying two segments corresponds to getting the area of a rectangle with sides the lengths of the two segments. Since swapping the two segments just rotates the rectangle by 90 degrees, which does not change the area, multiplication is commutative. Consider two rectangles with a common height $h$ and bases $a$ and $b$. Their areas are $ah$ and $bh$, and the sum of the areas is $ah+bh$. Place these two rectangles together so their common height lines up. They now form a single rectangle with base $a+b$ and height $h$, and the area of this rectangle is $(a+b)h$. This means that $ah+bh = (a+b)h$, which is the distributive law. These laws were, of course, extended to other type of numbers (real, complex, fields, ...), but they all started with geometry. Off topic but interesting: Try to prove that $\sqrt{2}$ is irrational using only geometric concepts and proofs. No algebra is allowed. (I think I'll even propose this as a question.)
[ "stackoverflow", "0008501414.txt" ]
Q: I want to get the session name parameter by knowing its position c# If I cycle all the session vars with a for I'll know each position and value of the session var but I want to know the session var name. for ( int i=0; i<Session.count; i++) { Response.write(Session[i].ToString()); } But I want to retrieve Session var by Name like Response.write(Session["SessionVarName"].ToString()); A: Use the Keys property of Session. for ( int i=0; i < Session.Keys.Count; i++) { Response.write(Session.Keys[i]); }
[ "stackoverflow", "0005534112.txt" ]
Q: jquery effects are NOT working I have some experience in PHP but not in JQuery that much. My admin.php page has a div which has id named "table1" where content gets loaded via ajax: document.getElementById("table1").innerHTML=xmlhttp.responseText; xmlhttp gets data from sorgula1.php page which has some JQuery effects like highlighting table rows. When I'm trying to run the sorgula1.php alone, the highlighting works but when it is loaded via ajax to admin.php, highlighting and other JQuery effects are not working. I've tried everything to make it work but, I always failed. For those of you who will ask me to remove the $(document).ready(function() statement, I'm informing you that it doesn't work. Here is the sorgula.php code: sorgula1.php please be specific about the answers guys.Thanx for all answers. A: Maybe when you use innerHTML property, the javascript doesn't work. I think you can solve this problem by using jQuery load() function.
[ "stackoverflow", "0025825960.txt" ]
Q: Weird JS syntax: math operator in function declaration I just played with Twitter API and found very weird construction. It's division operator between function name and arguments passing. c/({"count":8098,"url":"http:\/\/example.com\/"}); I supposed that this should throw parser exception, but it works − just returning NaN instead of undefined. Also it works similar with * and - operators, while + returns c.toString() (or .valueOf, I dunno). Even more, it's really syntax error thrown if i don't pass object to function. Here's examples: function c() {} >> undefined c >> function c() {} c/() >> SyntaxError: Unexpected token ) c/({}); >> NaN c+({}) >> "function c() {}[object Object]" c({}) >> undefined I ran this in Chrome, but I belive it works everywhere if Twitter put it in response. So. Why this even work, and how it works exactly? I believe this somehow releated to function returning value and its implicit type coercion, but I still don't get it. A: Your URL is not escaped in that API call so twitter reads it incorrectly and creates meaningless syntax. If you set the URL parameter to an escaped value (via encodeURIComponent) it will produce c({some:"Object"}) which is a JSONP response - JSONP is inherently a function call and works by injecting a script tag. So, twitter does not produce this response deliberately, you're passing it problematic parameters and it's not failing gracefully. As for why dividing a function in an object is NaN - in JS generally math operators don't throw very often. JavaScript is telling you - you tried to perform a math operation that doesn't make sense and the result is not a number - NaN. For the funky results: c/() Is just invalid syntax, simply put you're diving something by nothing, 5/() would fail equally well. c/({}) Diving a function by an object makes no sense, so it is giving you "Not a Number". I can add a spec quote but I don't think there is much more to add beyond "There is no way to interperet this differently". c+({}) The + operator performs string concatenation in addition to numeric addition - so what's happening here is that toString is called for both the function and the object and you see the concatenated result. c({}) This is just the return value of the function call
[ "stackoverflow", "0002853333.txt" ]
Q: Multiple Condition Coverage Testing When using the White Box method of testing called Multiple Condition Coverage, do we take all conditional statements or just the ones with multiple conditions? Now maybe the clues in the name but I'm not sure. So if I have the following method void someMethod() { if(a && b && (c || (d && e)) ) //Conditional A { } if(z && q) // Conditional B { } } Do I generate the truth table for just "Conditional A", or do I also do Conditional B? Thanks, A: I might be missing something here but, the way you wrote the code in your question, conditions A and B are completely independent of each other. You therefore won't cover all of the code unless you test both conditionals.
[ "stackoverflow", "0050688468.txt" ]
Q: Python SQLAlchemy pyodbc.Error: ('HY000', 'The driver did not supply an error!') Hi Everyone I Am working right now with Pandas and MSSQL. I have bene working ok but recently after an SQlalchemy update i am getting the following error when I am trying to upload information into the DB via df.to_sql pyodbc.Error: ('HY000', 'The driver did not supply an error!') My connection is defined as follows engine = create_engine('mssql+pyodbc://Reporter:******@localhost:1433/SourcingDb?driver=SQL+Server') df.to_sql('ProductivityDeck', con=engine, if_exists='replace', index= False) and the full error I get is this one Traceback (most recent call last): File "C:\Python\Python36\lib\site-packages\sqlalchemy\engine\base.py", line 1182, in _execute_context context) File "C:\Python\Python36\lib\site-packages\sqlalchemy\engine\default.py", line 470, in do_execute cursor.execute(statement, parameters) pyodbc.Error: ('HY000', 'The driver did not supply an error!') The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:/Users/H212310/PycharmProjects/untitled2/UpdateCEDeckv2.py", line 23, in <module> df.to_sql('ProductivityDeck', con=engine, if_exists='replace', index= False) File "C:\Python\Python36\lib\site-packages\pandas\core\generic.py", line 2127, in to_sql dtype=dtype) File "C:\Python\Python36\lib\site-packages\pandas\io\sql.py", line 450, in to_sql chunksize=chunksize, dtype=dtype) File "C:\Python\Python36\lib\site-packages\pandas\io\sql.py", line 1149, in to_sql table.insert(chunksize) File "C:\Python\Python36\lib\site-packages\pandas\io\sql.py", line 663, in insert self._execute_insert(conn, keys, chunk_iter) File "C:\Python\Python36\lib\site-packages\pandas\io\sql.py", line 638, in _execute_insert conn.execute(*self.insert_statement(data, conn)) File "C:\Python\Python36\lib\site-packages\sqlalchemy\engine\base.py", line 945, in execute return meth(self, multiparams, params) File "C:\Python\Python36\lib\site-packages\sqlalchemy\sql\elements.py", line 263, in _execute_on_connection return connection._execute_clauseelement(self, multiparams, params) File "C:\Python\Python36\lib\site-packages\sqlalchemy\engine\base.py", line 1053, in _execute_clauseelement compiled_sql, distilled_params File "C:\Python\Python36\lib\site-packages\sqlalchemy\engine\base.py", line 1189, in _execute_context context) File "C:\Python\Python36\lib\site-packages\sqlalchemy\engine\base.py", line 1402, in _handle_dbapi_exception exc_info File "C:\Python\Python36\lib\site-packages\sqlalchemy\util\compat.py", line 203, in raise_from_cause reraise(type(exception), exception, tb=exc_tb, cause=cause) File "C:\Python\Python36\lib\site-packages\sqlalchemy\util\compat.py", line 186, in reraise raise value.with_traceback(tb) File "C:\Python\Python36\lib\site-packages\sqlalchemy\engine\base.py", line 1182, in _execute_context context) File "C:\Python\Python36\lib\site-packages\sqlalchemy\engine\default.py", line 470, in do_execute cursor.execute(statement, parameters) I have tried to rollback to a lower version of SqlAlchemy, Update the ODBC driver in windows and upgrading the python installation and it keeps coming back. Any ideas in how to fix this issue? A: OK this was a "silent error for a known bug in pandas 23, downgrading to v22 makes the error go away and you can upload 1000+ rows. this is being worked out on https://github.com/pandas-dev/pandas/issues/21103
[ "stackoverflow", "0002438000.txt" ]
Q: How do i implement tag searching? with lucene? I havent used lucene. Last time i ask (many months ago, maybe a year) people suggested lucene. If i shouldnt use lucene what should i use? As am example say there are items tagged like this apples carrots apples carrots apple banana if a user search apples i dont care if there is any preference from 1,2 and 4. However i seen many forums do this which i HATED is when a user search apple carrots 2 and 3 have high results while 1 is hard to find even though it matches my search more closely. Also i would like the ability to do search carrots -apples which will only get me 3. I am not sure what should happen if i search carrots banana but anyways as long as more items tagged with 2 and 3 results are lower ranking then 1 when i search apples carrots i'll be happy. Can lucene do this? and where do i start? I tried looking it up and when i do i see a lot of classes and i'll see tutorials talking about documents, webpages but none were clear about what to do when i like to tag something. If not lucene what should i use for tagging? A: Edit: You can use Lucene. Here's an explanation how to do this in Lucene.net. Some Lucene basics are: Document - is the storage unit in Lucene. It is somewhat analogous to a database record. Field - the search unit in Lucene. Analogous to a database column. Lucene searches for text by taking a query and matching it against fields. A field should be indexed in order to enable search. Token - the search atom in Lucene. Usually a word, sometimes a phrase, letter or digit. Analyzer - the part of Lucene that transforms a field into tokens. Please read this blog post about creating and using a Lucene.net index. I assume you are tagging blog posts. If I am totally wrong, please say so. In order to search for tags, you need to represent them as Lucene entities, namely as tokens inside a "tags" field. One way of doing so, is assigning a Lucene document per blog post. The document will have at least the following fields: id: unique id of the blog post. content: the text of the blog post. tags: list of tags. Indexing: Whenever you add a tag to a post, remove a tag or edit it, you will need to index the post. The Analyzer will transform the fields into their token representation. Document doc = new Document(); doc.Add(new Field("id", i.ToString(), Field.Store.YES, Field.Index.NO)); doc.Add(new Field("content", text, Field.Store.YES, Field.Index.TOKENIZED)); doc.Add(new Field("tags", tags, Field.Store.YES, Field.Index.TOKENIZED)); writer.AddDocument(doc); The remaining part is retrieval. For this, you need to create a QueryParser and pass it a query string, like this: QueryParser qp = new QueryParser(); Query q = qp.Parse(s); Hits = Searcher.Search(q); The syntax you need for s will be: tags: apples tags: carrots To search for apples or carrots tags: carrots NOT tags: apples See the Lucene Query Parser Syntax for details on constructing s. A: Lucene for .net seems to be mature. No need to use Java or SOLR The Standard query language for Lucene allows equally ranked search terms and negation So if your Lucene index had a field "tag" your query would be tag:apple* OR tag: carrot* Which would give equal ranking to each word, and more rank weighting to document with both tags To negate a tag use this tag:carrot* NOT tag:apple* Simple example to show indexing and querying with Lucene here
[ "gamedev.stackexchange", "0000069162.txt" ]
Q: Use large image individually, or in TextureAtlas? Does it make any sense to include a large image (with dimensions of say 1920x1080) in a TextureAtlas and then use it with libgdx for example? Or should I rather use it individually and include the .png file into the assets folder as it is? Thank you. A: Use it individually. Texture atlases are used to gain efficiency by minimising texture swaps for many small textures, and avoiding wastage due to textures having to be bumped up in size to dimensions that are a power-of-two. A single image on an atlas gains you nothing except more book-keeping, and if the atlases are required to be power-of-two in size, your example image would need to be 2048x2048. That's a lot of wasted space. The original tags included Android, which brings some extra factors to the discussion: A 1920 x 1080 image will most likely need to be compressed to work on Android anyway, which comes with a need for power-of-two sizing. PNG is not a native format, so any PNG images will have to be converted and probably compressed before use. So even storing and using it individually, for loading and rendering it will be bumped up to 2048x2048 before it's compressed. You could use it at its native resolution uncompressed, but it would be massive in memory, and you probably want to avoid that. In practice we've always used compression on full-screen backdrops, but left texture atlases uncompressed (because the quality drop is far more noticeable on the smaller sprites); that's a pretty common policy for most places I believe. A: First of all 1920x1080 is not power of two, even if your card support NPOT textures I think it's a best practice to use a POT texture. Second let's calculate the size in bytes. 1920 * 1080 * 4 = 8294400 bytes that is around 8mb of memory. Since the answer is tagged as android I assume you are talking about a mobile platform. A lot of the mobile platforms can't handle more that 2048*2048Citation needed. So if you are talking about it as a stand alone texture that's big! If it was part of an Atlas that's even worse, I assume the atlas will be much bigger. My advise use it as stand alone. And make sure you use don't alot of memory, you might need to scale it down.
[ "stackoverflow", "0017727221.txt" ]
Q: postLink generates invalid code at CakePHP 2.3 I am using CakePHP 2.3 I have two environments where I have my web application. At the testing environment with the exact same version of the application (all files are the same) I am having a problem with the Form->postLink method. It shows this error on the Javascript console: Uncaught TypeError: Object # has no method 'submit' users:119 onclick Comparing the resulting HTML from both environments I can notice that the attributes name and id generated by this method are repeated more than once in the same page (which shouldn't be like that). This is the code use to generate those post links: foreach($users as $user){ $delete = $this->Form->postLink(__('Delete'), array('action' => 'delete', $user['user_id']), __('Are you sure you want to delete %s?', $user['user_id'])); } This is the problematic generated HTML with repeated values for id and name as you can see: <!-- link 1 --> <form action="delete/1/" name="post_51e8019d095f1" id="post_51e8019d095f1" style="display:none;" method="post"> <input type="hidden" name="_method" value="POST"/> </form> <a href="#" onclick="if (confirm(&#039;Are you sure you want to delete blabla?&#039;)) { document.post_51e8019d095f1.submit(); } event.returnValue = false; return false;">Delete</a> <!-- link 2 --> <form action="delete/2/" name="post_51e8019d095f1" id="post_51e8019d095f1" style="display:none;" method="post"> <input type="hidden" name="_method" value="POST"/> </form> <a href="#" onclick="if (confirm(&#039;Are you sure you want to delete blabla22?&#039;)) { document.post_51e8019d095f1.submit(); } event.returnValue = false; return false;">Delete</a> Why is this happening? Could it be related with the configuration of the web server somehow? I don't see another explanation for it... Thanks. A: The problem was caused by a bug in IIS 7.0.6000.16386 and the PHP function uniqid as pointed out here. I am using a slightly different version in both environments ( IIS 7.0.6000.16386 vs IIS 7.5.7600.16385) and that was the cause of the problem. In order to solve it I modified the file lib/Cake/View/Helper/FormHelper.php chaning the line $formName = uniqid('post_'); inside the postLink function to: $formName = uniqid('post_', true); That adds more entropy and as the documentation says: If set to TRUE, uniqid() will add additional entropy (using the combined linear congruential generator) at the end of the return value, which increases the likelihood that the result will be unique. Update Ended up having to add one more change due to problems with javascript in forms. I added one more line after $formName = uniqid('post_', true); so it looks like: $formName = uniqid('post_', true); $formName = str_replace('.', '', $formName);
[ "stackoverflow", "0011825363.txt" ]
Q: Callouts for MKAnnotations randomly not appearing I have a little issue with MKMapView and its annotations, and I can't find what's happening here. The issue is that sometimes, when I tap an annotation, its callout won't appear. If I tap it again, it still won't appear. If I tap another annotation and after that I tap the first one again, the callout will appear. I checked with an NSLog for title and canShowCallout in didSelectAnnotationView and everything's ok there (the first isn't null and the second is set to true). What else could make the callouts not appear? A: Found this, which seems to work. I don't really like this kind of workarounds, but as there's no other solution I guess that I have to use what I have...
[ "math.stackexchange", "0000374062.txt" ]
Q: independent $L^2$ distance random variable When you have independent random variables with $L^2$ distance between each of them is some fixed constant. Say expectation of each of those random variables are zero THEN How can i conclude that that this sequence can NOT converge in probability to a limit? I believe this should be true. How to show it? Thank you! A: Such a sequence can converge in probability. For example, take the sequence $X_1$, $X_2$, $\dots$ of independent random variables where $$ X_n:=\left\{\begin{array}{ll} 2^n, & \text{with probability } 2^{-2n}\\ -2^n, & \text{with probability } 2^{-2n}\\ 0, & \text{with probability } 1-2^{-(2n-1)}. \end{array}\right. $$ Then, for each $n$, $${\Bbb E}X_n=2^{-2n}\cdot2^n+2^{-2n}\cdot(-2^n)=0,$$ $${\Bbb E}X_n^2=2^{-2n}\cdot (2^n)^2+2^{-2n}\cdot(-2^n)^2=2,$$ so for all $i<j$, \begin{eqnarray*} {\Bbb E}[(X_i-X_j)^2]&=&{\Bbb E}(X_i^2)+{\Bbb E}(X_j^2)-2({\Bbb E}X_i)({\Bbb E}X_j)\\ &=&2+2-2\cdot0\cdot0\\ &=&4. \end{eqnarray*} Therefore, this sequence satisfies the given conditions, but it converges in probability to $0$.
[ "stackoverflow", "0005589292.txt" ]
Q: CSS3 Box Shadow Direction I'm a total CSS3 noob, so please bear with me. I have the following HTML: <input name="firstName" id="firstName" type="text"><span class="tip">Just a tip</span> ... with the following CSS applied to the "input" field and "span" tag: input[type="text"], input[type="password"], textarea { border-top:1px solid #5F5F5F; border-left:1px solid #5F5F5F; border-bottom:1px solid #5F5F5F; border-right:1px solid #5F5F5F; border-top-left-radius:5px; border-bottom-left-radius:5px; padding:10px; width:200px; } input[type="text"]:hover, input[type="password"]:hover, textarea:hover { border: 1px solid #22C3EB; -webkit-box-shadow: 0 0 5px #22C3EB; -moz-box-shadow: 0 0 5px #22C3EB; box-shadow: 0 0 5px #22C3EB; } input[type="text"]:focus, input[type="password"]:focus, textarea:focus { border: 1px solid #972324; -webkit-box-shadow: 0 0 5px #972324; -moz-box-shadow: 0 0 5px #972324; box-shadow: 0 0 5px #972324; } .tip { font-size:11px; border-top:1px solid #22C3EB; border-right:1px solid #22C3EB; border-bottom:1px solid #22C3EB; border-left:1px solid #5F5F5F; border-bottom-right-radius:5px; border-top-right-radius:5px; padding:12px 10px 10px 10px; width:200px; } .tip:hover { border: 1px solid #22C3EB; -webkit-box-shadow: 0 0 5px #22C3EB; -moz-box-shadow: 0 0 5px #22C3EB; box-shadow: 0 0 5px #22C3EB; } Basically, it is a rounded text field, with another span tag on the right, which also has rounded outer edges. It looks similar to the Twitter sign-up page. If you click on each input field field, you will get a general idea of the way my input and span tags are styled. Is there a way to prevent the "box-shadow" from casting a shadow between the "input" and "span" fields? So, no shadow on the right side of the "input" field, and no shadow on the left side of the "span" tag? Please note I am trying to support both Mozilla and Webkit rendering engines in this CSS. Thank you for your time, spryno724 A: use inner-wrap and use box-shadow: -5px 0 0px #FFFFFF; http://jsfiddle.net/pramendra/y67Yt/3/
[ "stackoverflow", "0009145383.txt" ]
Q: Event handling for geometries in Three.js? I am looking for some kind of event handling for geometries/cameras/lights(things we add to scene) in three.js ? I googled but couldn't find anything relevant. I did a simple Sphere rendering and tried to see the DIV contents in firebug, but there's just one canvas, and adding any "onclick" to the canvas makes the event for all the canvas, that is, its not just for the sphere or light. Any suggestions ? A: You need to a couple o things to get interactivity in 3D: get a vector for the mouse position unproject the mouse vector based on the camera shot a ray from the camera position, towards the unprojected mouse vector check what object(s) interesect with that ray and update accordingly. It might sound complicated, but the code's already there: function onDocumentMouseDown( event ) { event.preventDefault(); var vector = new THREE.Vector3( ( event.clientX / window.innerWidth ) * 2 - 1, - ( event.clientY / window.innerHeight ) * 2 + 1, 0.5 ); projector.unprojectVector( vector, camera ); var ray = new THREE.Ray( camera.position, vector.subSelf( camera.position ).normalize() ); var intersects = ray.intersectObjects( objects ); if ( intersects.length > 0 ) { intersects[ 0 ].object.material.color.setHex( Math.random() * 0xffffff ); var particle = new THREE.Particle( particleMaterial ); particle.position = intersects[ 0 ].point; particle.scale.x = particle.scale.y = 8; scene.add( particle ); } /* // Parse all the faces for ( var i in intersects ) { intersects[ i ].face.material[ 0 ].color.setHex( Math.random() * 0xffffff | 0x80000000 ); } */ } This code above from the canvas_interactive_cubes example that comes with the library. When in doubt, it's always good to check if there's an example that solves the problem already.
[ "stackoverflow", "0028402850.txt" ]
Q: How to communicate between Android and Javascript? I need to communicate Android and Javascript. I want to call Javascript function in Android and send parameter to Javascript 'a','b','c' Android: public boolean shouldOverrideUrILoading(WebView view, String url) if(url.contains("http://localhost:8080/login.html)){ view.loadUrl("javascript:setDevice('"+a+"','"+b+"','"+c"');"); JavaScript: function setDevice(a, b, c){ jQuery("#a").val(a); jQuery("#b").val(b); jQuery("#c").val(c); } Somebody help me plz.. A: To communicate javascript with Android webview you should use Webviewclient and Webcromeclient as view.setWebViewClient(new WebViewClient()); view.setWebChromeClient(new WebChromeClient()); view.getSettings().setJavaScriptEnabled(true);
[ "stackoverflow", "0044743559.txt" ]
Q: HTML5 - Prevent Fullscreen Mode I'm using the Fullscreen API with an embedded YouTube video to detect whether or not the browser window has entered fullscreen mode. I have that working great. What I'd like to do is prevent from occurring the default behavior of entering fullscreen mode. I'd like to put in my own fullscreen mode logic so that I can overlay DOM elements on top of the YouTube Player. Currently, I can exit fullscreen mode immediately after entering it, but that results in a poor and confusing experience for the user. One workaround is to remove the fullscreen button using YouTube's Player API parameters and add my own button with my own logic, but this is not ideal because users can still double-click on the YouTube player to make it full screen. Here's my code for detecting the fullscreen state of the browser: $(document).on("fullscreenchange webkitfullscreenchange msfullscreenchange mozfullscreenchange", function(event) { onFullScreenChange(event); }); function onFullScreenChange(event) { var fullScreenElement = document.fullscreenElement || document.msFullscreenElement || document.mozFullScreenElement || document.webkitFullscreenElement; var isFullscreen = !!fullScreenElement; console.log("In fullscreen mode?", isFullscreen); if (isFullscreen === true) { // TODO: Prevent the browser from entering full screen mode. These three lines don't prevent that behavior event.stopImmediatePropagation(); event.stopPropagation(); event.preventDefault(); return false; // The commented code below works. Ideally, we'd want to prevent the browser from even entering full screen mode //document.webkitExitFullscreen(); } } Using preventDefault(), stopPropagation(), and stopImmediatePropagation() didn't work, so I'm stuck at this point. How can I prevent the browser from entering fullscreen mode, if indeed it is possible? A: Using youtube iframe api Disable full screen button: fs: 0 Disable Keyboard controls: disablekb: 1 When player loaded, remove full-screen option: // Get DOM video player not YT videoplayer videoPlayer = document.getElementById('player'); // don't allow full screen videoPlayer.allowFullscreen = false; Trigger full-screen on DOM player (iframe in our case) with Fullscreen_API videoPlayer.requestFullScreen() Full screen leave will happen if ESC key is pressed or video ends (custom event handling) JsFiddle Working example: <!DOCTYPE html> <html> <body> <!-- The <iframe> (and video player) will replace this <div> tag. --> <div id="player"></div> <br /> <button id="fullScreenPlayer">Full Screen Player</button> <script> // DOM player var videoPlayer; // This code loads the IFrame Player API code asynchronously. var tag = document.createElement('script'); tag.src = "https://www.youtube.com/iframe_api"; var firstScriptTag = document.getElementsByTagName('script')[0]; firstScriptTag.parentNode.insertBefore(tag, firstScriptTag); // This function creates an <iframe> (and YouTube player) // after the API code downloads. var player; function onYouTubeIframeAPIReady() { player = new YT.Player('player', { height: '390', width: '640', videoId: 'nAgKA7R4Fz4', // params: https://developers.google.com/youtube/player_parameters?playerVersion=HTML5 playerVars: { 'fs': 0, 'disablekb': 1, 'rel': 0 }, events: { 'onReady': onPlayerReady, 'onStateChange': onPlayerStateChange } }); } // The API will call this function when the video player is ready. function onPlayerReady(event) { event.target.playVideo(); // Get DOM video player not YT videoplayer videoPlayer = document.getElementById('player'); // don't allow full screen videoPlayer.allowFullscreen = false; // Listen for fulscreen changes, if you need custom logic here, but I won't recommned that, it's to complex and you don't have control inside YT iframe videoPlayer.addEventListener("fullscreenchange", fullScreeCallback, false); videoPlayer.addEventListener("webkitfullscreenchange", fullScreeCallback, false); videoPlayer.addEventListener("msfullscreenchange", fullScreeCallback, false); videoPlayer.addEventListener("mozfullscreenchange", fullScreeCallback, false); } // If the video reach the end then player will leave full screen function onPlayerStateChange(event) { if (event.data == YT.PlayerState.ENDED) { leaveFullscreen(); } } function stopVideo() { player.stopVideo(); } // fullscreen event handller function fullScreeCallback(e) { // do what you like when you catch the event console.log(e); return false; } var goFullscreen = function () { if (videoPlayer === undefined) throw "player is undefined"; if (videoPlayer.requestFullScreen) { videoPlayer.requestFullScreen(); } else if (videoPlayer.mozRequestFullScreen) { videoPlayer.mozRequestFullScreen(); } else if (videoPlayer.webkitRequestFullScreen) { videoPlayer.webkitRequestFullScreen(); } } var leaveFullscreen = function () { if (document.cancelFullScreen) { document.cancelFullScreen(); } else if (document.mozCancelFullScreen) { document.mozCancelFullScreen(); } else if (document.webkitCancelFullScreen) { document.webkitCancelFullScreen(); } } document.getElementById('fullScreenPlayer').addEventListener("click", function(e) { goFullscreen(); }, false); </script> </body> </html>
[ "stackoverflow", "0014160679.txt" ]
Q: Start `RemoteWebDriver` server separately from creating a `webdriver.Remote` instance? Using the Selenium Python bindings, is it possible to start the RemoteWebDriver server separately from creating a webdriver.Remote instance? The point of doing this would be to save time spent repeatedly starting and stopping the server when all I really need is a new instance of the client. (This is possible with ChromeDriver.) A: the server is started independently. creating an instance of webdriver.Remote does not start the server.
[ "stackoverflow", "0024202572.txt" ]
Q: R beanplot comparison including a vector of zeros I am hoping to use beanplot to show a visual comparison of 4 increments in a categorical predictor variable as plotted against a response variable. My issue is that one of the increments is a vector full of zeros so understandably the shapiro.test phase of the beanplot routine will not work. (this is the error I get) Error in shapiro.test(x) : all 'x' values are identical Is there a way I can bypass this and say if there is a vector of zeros then do nothing for that increment and move onto the next so that my plot ends up with 4 increments on the x axis and 3 beanplots only for the increments where the vectors contain values >0? Many thanks for your help. All the best, Bex A: I'm guessing the problem is when the var of a category is 0. You could test for this case and set the values for that group to NA. That should work with beanplot. First, some test data dd<-data.frame( cat =sample(letters[1:5], 50, replace=T), val = runif(50) ) dd$val[dd$cat=="c"]<-0 And now the data fixing and plotting code library(beanplot) catvar <- with(dd, tapply(val, cat, var)) if(any(catvar==0)) { dd$val[dd$cat %in% names(catvar[catvar==0])] <- NA } beanplot(val~cat, dd) and that produces a plot such as
[ "stackoverflow", "0016417324.txt" ]
Q: Check if a value in a list is equal to some number I've got a list of data: [[0, 3], [1, 2], [2, 1], [3, 0]] And I'm trying to check if any of the individual numers is equal to 3, and if so return which element, so list[0],list[3] e.t.c within the original list contains this value 3. I've gotten as far as: for i in range(0, len(gcounter_selection)): for x in range(0,len(gcounter_selection)): if any(x) in gcounter_selection[i][x]==3: print(i) My list is called gcounter_selection by the way. But I'm getting a type error: TypeError: argument of type 'int' is not iterable I've tried using a generator expression but I couldnt get that to work either. A: If I understood correctly, you're looking for list comprehensions: value = 3 lst = [[0, 3], [1, 2], [2, 1], [3, 0]] items = [x for x in lst if value in x] print(items) #[[0, 3], [3, 0]] To get elements' positions instead of just elements, add enumerate: indexes = [n for n, x in enumerate(lst) if value in x]
[ "stackoverflow", "0027239222.txt" ]
Q: Jplayer does not start playing automatically on mobile device JPlayer does not start playing automatically after setMedia() followed by play() on mobile device (Android), but works fine on chrome for PC and even internet explorer, what should i do to get it playing. A: This is normal behaviour. On mobile devices playback must be initiated by user interaction. Take a look here for more details -> link
[ "stackoverflow", "0037314343.txt" ]
Q: How to check an array on runtime if contains certain value The code provided below do a task that it gets all the x and y or like strings, and adds it to array. I can add them all to array but what I want is to check that if the variable that I am about to insert into an array already exists then do not insert else insert. ArrayList vars = new ArrayList(); for(int i = 0; i < temp.length; i++) for(int j = 1; j < temp[0].length - 1; j++) { String text_to_parse = temp[i][j]; Pattern y = Pattern.compile("[?]\\w[,)]"); // find the values in pattern of ?x, or ?x) Matcher z = y.matcher(text_to_parse); while(z.find()) { String to_add = z.group(); to_add = to_add.replaceAll("[\\,\\) ]",""); // logic required here if to_add exist in vars then do no insert else insert } } I tried using vars.contain but it adds all the values that it finds. A: Try if vars does not contain. Like so using the ! operator if (!(vars.contains(item))) //add the item else //do nothing
[ "stackoverflow", "0007851741.txt" ]
Q: EventMachine, Redis & EM HTTP Request I try to read URLs from a Redis store and simply fetch the HTTP status of the URLs. All within EventMachine. I don't know what's wrong with my code, but it's not asynchronous like expected. All requests are fired from the first one to the last one and curiously I only get the first response (the HTTP header I want to check) after the last request. Does anyone have a hint what's going wrong there? require 'eventmachine' require 'em-hiredis' require 'em-http' EM.run do @redis = EM::Hiredis.connect @redis.errback do |code| puts "Error code: #{code}" end @redis.keys("domain:*") do |domains| domains.each do |domain| if domain http = EM::HttpRequest.new("http://www.#{domain}", :connect_timeout => 1).get http.callback do puts http.response_header.http_status end else EM.stop end end end end I'm running this script for a few thousand domains so I would expect to get the first responses before sending the last request. A: While EventMachine is async, the reactor itself is single threaded. So, while your loop is running and firing off those thousands of requests, none of them are being executed until the loop exits. Then, if you call EM.stop, you'll stop the reactor before they execute. You can use something like EM::iterator to break up the processing of domains into chunks that let the reactor execute. Then you'll need to do some magic if you really want to EM.stop by keeping a counter of the dispatched requests and the received responses before you stop the reactor.
[ "stackoverflow", "0043744763.txt" ]
Q: SQL Calculations using a percentage I have a table that holds a bunch of values for an order, I can do basic calculations on it until I get to a percentage. Right now I have my query as follows declare @MyNumber decimal set @MyNumber = (select SalesTax from [OrderHeader] where OrderHeaderID = 20) select sum(o.MaterialPrice) as "MatPrice", sum(o.LaborPrice) as "LaborPrice", sum(o.MaterialCost) as "MaterialCost", sum(isnull(o.MaterialPrice,0)) - sum(isnull(o.MaterialCost,0)) - sum(isnull(o.LaborPrice,0)) * @MyNumber as "RESULT" from [OrderDetail] o inner join [OrderHeader] oh on oh.OrderHeaderID = o.OrderHeaderID where o.OrderHeaderID = 20 @MyNumber is holding a SalesTax and this particular SalesTax is 7.00, I have no idea on how to convert the SalesTax to a percentage and do the calculation as shown above A: You need to specify precision and scale when declaring decimal, e.g. declare @mynumber decimal(9,6); rextester demo: http://rextester.com/YBFY72733 A simplified example: select convert(decimal,.07) as NotSpecified , convert(decimal(9,6),.07) as Specified returns: +--------------+-----------+ | NotSpecified | Specified | +--------------+-----------+ | 0 | 0,070000 | +--------------+-----------+ My best guess at what you want for your query: declare @MyNumber decimal(9,6); set @MyNumber = (select SalesTax from [OrderHeader] where OrderHeaderID = 20) /* we want the sales tax to be a percentage (less than 1), 0.0825 */ if @MyNumber >= 1 set @MyNumber = @MyNumber *.01; select MatPrice = sum(o.MaterialPrice) , LaborPrice = sum(o.LaborPrice) , MatieralCost = sum(o.MaterialCost) , SubTotal = ( sum(isnull(o.MaterialPrice,0)) + sum(isnull(o.MaterialCost,0)) + sum(isnull(o.LaborPrice,0)) ) , SalesTax = ( sum(isnull(o.MaterialPrice,0)) + sum(isnull(o.MaterialCost,0)) + sum(isnull(o.LaborPrice,0)) ) * @MyNumber , Total = ( sum(isnull(o.MaterialPrice,0)) + sum(isnull(o.MaterialCost,0)) + sum(isnull(o.LaborPrice,0)) ) * (@MyNumber+1) from [OrderDetail] o inner join [OrderHeader] oh on oh.OrderHeaderID = o.OrderHeaderID where o.OrderHeaderID = 20
[ "stackoverflow", "0059294792.txt" ]
Q: Changing a TextView in RecyclerView with if-else statement depending on a value from Firestore I am developing a game where the current user sees all his current games in a RecyclerView (see picture). For that I am using the Firestore UI, and I want to change a TextView to "Play" or "Wait" depending whether the current user has to play or the opponent has to play. For that I made a field "turn" in the document where the RecyclerViewAdapter retrieves its value and give it the value of the UID of the current player or the opponent (depends who has to play). So when the current user has to play he should see "Play" as TextView in the RecyclerView item and the opponent has to see "Wait" (see pictures). To get the desired result I wanted to implement an if-else statement, but unfortunately textViewTurn.getText().toString()in the if statement has no value but it has one when I am sending the value to the next Activity as intent, so my if else statement is not working. How do I get the value of this TextView within the CurrentGamesHolder? Should I use the if else statement somewhere else in the RecyclerAdapter? Edit: I now moved the if else statement into the onBindViewHolder where both mTurnand uidhave a value but the method is still not working. That means when I log in to the account of the Player 1 the textViewPlay shows "Wait" which is the same as the Player 2. The value of the uid is different in both accounts so I actually don't know how it is possible that the outcome in both accounts is the same, as according to the if else statement it shouldn't be. Any help is much appreciated! Here is my RecyclerViewAdapter: public class CurrentGameAdapter extends FirestoreRecyclerAdapter<CurrentGames, CurrentGameAdapter.CurrentGamesHolder> { private OnItemClickListener listener; public CurrentGameAdapter(@NonNull FirestoreRecyclerOptions<CurrentGames> options) { super(options); } @Override protected void onBindViewHolder(@NonNull CurrentGamesHolder holder, int position, @NonNull CurrentGames model) { holder.textViewTurn.setText(model.getTurn()); holder.textViewPlay.setText(""); ... mTurn = model.getTurn(); FirebaseUser currentUser = FirebaseAuth.getInstance().getCurrentUser(); String mCurrentUser =currentUser.getUid(); if (mTurn == mCurrentUser){ holder.textViewPlay.setText("Play"); }else if (mTurn != mCurrentUser){ holder.textViewPlay.setText("Wait"); } } @NonNull @Override public CurrentGamesHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.listitem_current_game,parent, false); return new CurrentGamesHolder(view); } class CurrentGamesHolder extends RecyclerView.ViewHolder { TextView textViewTurn, textViewPlay; ... public CurrentGamesHolder(@NonNull View itemView) { super(itemView); textViewPlay = itemView.findViewById(R.id.play_current_game); textViewTurn = itemView.findViewById(R.id.turn_current_game); textViewTurn.setVisibility(View.INVISIBLE); ... itemView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { int position = getAdapterPosition(); if (position != RecyclerView.NO_POSITION && listener != null){ listener.onItemClick(getSnapshots().getSnapshot(position),(position)); Intent i = new Intent (itemView.getContext(), PlayInterimResultMainActivity.class); i.putExtra("turn", textViewTurn.getText().toString()); itemView.getContext().startActivity(i); } } }); } } public interface OnItemClickListener{ void onItemClick (DocumentSnapshot documentSnapshot, int position); } public void setOnItemClickListener(OnItemClickListener listener){ this.listener = listener; } } The first picture is what the player sees in his RecyclerView when he has to play and the second is what the opponent sees: A: After long trying I found the solution. I used the == operator, which compares the two object's references, not the Strings. To compare Strings I have to use .equals(). I was surprised since Android Studio displayed me "Strings are compared using '==' not 'equals()', so maybe there is a bug in that. Here is the right if-else statement: if (mTurn.equals(uid)){ holder.textViewPlay.setText("Wait"); }else { holder.textViewPlay.setText("Play"); }
[ "stackoverflow", "0057251121.txt" ]
Q: Streetview placeholder is here, but Pegman is missing I've integrate the googlemaps api but Pegman is missing from the streetview little white square (bottom right) I've notice that some div that hold the pegman icon in googlemaps code have height and width equal at 0px what can I do to fix that ? Here's a sample of how I called and initiate my map <script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=API_KEY"></script> Here's my map component : <div class="map-box" id="map" #map></div> with css.js looking like .map-box { height: 100%; width: 100%; } and how I create it : var ownPos = {lat: -4.85, lng: 2.35}; this.mapDisplay = new google.maps.Map(document.getElementById('map'), {zoom: 4, center: ownPos, streetViewControl: true}); A: I had this same issue and solved it with some CSS: /* Force position to show pegman */ .gm-svpc div img { position: relative !important; } A: fixing of wrappers' height solved the same bug agm-map { height: 425px; & /deep/ .gm-svpc { //dispayed pegman's icon on map div { height: 40px; } } }
[ "stackoverflow", "0014343490.txt" ]
Q: Django DatabaseError - No such savepoint I have a function the a Celery task calls in my Django app that processes each row in a CSV file and tries to insert information from each row into the PostgreSQL database using a model, like so: reader = csv.DictReader(csvfile, dialect=csv.get_dialect('excel')) for row_number, row in enumerate(reader): try: ... customer, created = Customer.objects.get_or_create( first_name = row['First Name'], last_name = row['Last Name'], email = row['Email'], account_owner = account_owner ) ... except Exception, e: message = "%s: %s\n" % (type(e).__name__, e) sys.stderr.write("%s\n" % message) I'm getting the following error at Customer.objects.get_or_create on the first iteration of the loop: DatabaseError: no such savepoint And then I'm getting DatabaseError: current transaction is aborted, commands ignored until end of transaction block for each iteration thereafter. I have successfully inserted (manually with SQL) a record into this table with the same information the script would provide. I have also tried working with savepoints, with no luck: sid = transaction.savepoint() customer, created = Customer.objects.get_or_create( first_name = row['First Name'], last_name = row['Last Name'], email = row['Email'], account_owner = account_owner ) transaction.savepoint_commit(sid) This is happening on my dev machine with PostgreSQL 9.1 installed from Homebrew. Obviously the main goal is to fix this issue, but any helpful pointers for debugging the Celery task or locating my Postgres log files would be helpful also. A: After doing some more research, it looks like the underlying cause of this is in an IntegrityError which tries to force a savepoint rollback, which doesn't exist anymore. I fix the IntegrityError and I assume the no savepoint issue is fixed. Still would be great to see the IntegrityError immediately as I'm debugging... Enabled logging using these instructions and I'm seeing that the insert statement generated by the get_or_create violates a foreign key contraint.
[ "stackoverflow", "0050023051.txt" ]
Q: HTML input number type specify first value I have an HTML input that indicates a year as so: <input type="number" name="year" placeholder="Year" [max]="presentYear" min="1950"> The input is not required, so by default I simply want the placeholder "Year" to be present. However, as soon as the user clicks on the up or down arrows of the input field, I want the max value to be shown as default, in this case the present year (2018). However, the minimum number is shown instead. This makes no sense for this situation, since the user would have to scroll through 68 years to get to the most common use case. Is there any way to specify the default "first value" of a number type input field? If it helps answer the question, I'm using Angular 5 for this project. A: You can set min to the same value as max initially, and change it for 1950 after the input value has been changed, with the help of ngModel and ngModelChange. The first click on the spinner button will set the current year as the initial value, and the modified min value will allow to change it afterwards. <input type="number" name="year" placeholder="Year" [(ngModel)]="year" (ngModelChange)="setMinYear($event)" [max]="presentYear" [min]="minYear"> export class AppComponent { presentYear = this.getCurrentYear(); minYear = this.getCurrentYear(); year: number; private getCurrentYear(): number { return new Date().getUTCFullYear(); } public setMinYear(value: number) { const firstYear = 1950; if (value >= firstYear) { this.minYear = firstYear; } else { this.minYear = this.presentYear; } } } The code can be tested in this stackblitz.
[ "stackoverflow", "0008782287.txt" ]
Q: Using Java NIO with Unix Domain sockets in non-blocking mode with selectors Is there a way to use Unix Domain sockets with Java NIO? I want to use NIO so that I can use Selectors on it in a single thread. I had a look at junixsocket but it only seems to support normal Sockets not NIO channels that support selectors. A: You can use the project jnr-unixsocket,(https://github.com/jnr/jnr-unixsocket) which is the far most advanced implementation I've seen. It does exactely what you want : nio concepts Selectors, Channels etc Look @ https://github.com/jnr/jnr-unixsocket/tree/master/src/test/java/jnr/unixsocket/example
[ "apple.stackexchange", "0000397110.txt" ]
Q: Can MacOS Dictionary be invoked by a URI? I've seen links in web pages on MacOS and IOS that invoke other apps, notably App Store and iBooks. If I recall correctly, they usually have a protocol¹ that in some way identifies the app. I am using an HTML/PHP/MySQL app called Learning With Texts that allows it to create a URI to a web page with place holders to auto-insert a word to look up in an online dictionary. Now I know that ⌘⌃D can be used on MacOS to display all instances of a string that appear in any MacOS dictionary. I am wondering whether there is a URI syntax that will look it up in a specific dictionary. (And what is that syntax.) In Catalina, if that matters. ¹the first part of the URI—in a web link, the protocol is “http” or “https” A: Can MacOS Dictionary be invoked by a URI? Yes: dict:// Example HTML code: <a href="dict://foobar">Lookup 'foobar' in Dictionary</a> Tested with Safari under macOS Catalina using: <!DOCTYPE html> <html> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <title>Dictionary Lookup</title> </head> <body> <p><a href="dict://foobar">Lookup 'foobar' in Dictionary</a></p> </body> </html> When clicking the hyperlink, one is presented with: I am wondering whether there is a URI syntax that will look it up in a specific dictionary. (And what is that syntax.) If there is, I do not know it and I tried modifying dict:// adding the different tabs in the Dictionary app and none worked. The only thing that worked was dict:// and dict:// followed by the search word, e.g. dict://foobar and in the case of the later syntax it open to the last active tab of the app. For example, if Wikipedia was the active tab when the app was closed it opens e.g. foobar there.
[ "mythology.stackexchange", "0000002947.txt" ]
Q: What do we know about the pagan gods in the Apocalypse of Abraham? In the opening chapters of the Apocalypse of Abraham that discuss Abraham's conversion from idolatry, the pagan gods Merumath, Nakhin, Barisat, Zouchaios and Ioav are named. What do we know about these gods? Can they be traced to actual pagan traditions? A: G.H. Box, in his 1918 translation and commentary on the book, translates the gods names as Merumath, Barisat, Nahon, Zucheus, and Joavon. Notably, each of the idols is identified by the material it is made from, following the pattern established in the first chapter of the book (i.e. 'my father Terah to his gods of wood and stone, gold and silver, brass and iron', cf. Deuteronomy 4.28; Isaiah 60.17; Daniel 5.4). Merumath is 'hewn out of stone' Barisat 'is made of wood' Nahon is 'the iron god' Zucheus is 'made of gold' Joavon is 'forged of silver' Box comments in his introduction that Merumath and Barisat are 'sarcastic names' derived from Hebrew and Aramaic: Merumath = ʾeben Měrūmā, 'stone of deceit' (Hebrew) Barisat = bar ʾishtā, 'son of the fire' (Aramic) The names ridicule the idols: 'Merumath' because he is made of stone, but is no god worthy of worship, and 'Barisat' because he was built from wood which was burnt in the fire. If there is a meaning behind the names Nahon, Zucheus, and Joavon, we would expect it to follow this pattern, though I haven't found any scholars who offer suggestions. However, another theory proposed in more recent decades, is that the names are ciphers for the five prevailing empires that ruled over the Jewish people. Rubinkiewicz, 'Apocalypse of Abraham', The Old Testament Pseudepigrapha, p 682: The Slavonic text of the Apocalypse of Abraham contains several Hebrew names, words, and phrases. The most impressive examples are the following: Ioavan is a Slavonic deformation of the Hebrew ywn (Greece); Souzouch is probably a transcription of the name kwrwŝ (Cyrus); and Maroumat is an abbreviation of the Hebrew Martā Rômā. If this is the case, the choice of the materials may be influenced by Daniel 2.31-45 and 5.4. The former in particular identifies a series of kingdoms, which was commonly interpreted in the Second Temple period as referring to Babylon, Persia, Greece, and Rome.
[ "stackoverflow", "0013171602.txt" ]
Q: Display a tab on activating a menu item How can we display a JTabbedPane through clicking a menu item within a menu bar? A: Look into setSelectedIndex() and setSelectedComponent() in the javadocs. You can usually find methods similar to these in the docs. JTabbedPane#setSelectedComponent
[ "stackoverflow", "0031168135.txt" ]
Q: Call to implicitly-deleted default constructor I get the error message Call to implicitly-deleted default constructor of 'std::array' when I try to compile my C++ project. Header file cubic_patch.hpp #include <array> class Point3D{ public: Point3D(float, float, float); private: float x,y,z; }; class CubicPatch{ public: CubicPatch(std::array<Point3D, 16>); std::array<CubicPatch*, 2> LeftRightSplit(float, float); std::array<Point3D, 16> cp; CubicPatch *up, *right, *down, *left; }; Source file cubic_patch.cpp #include "cubic_patch.hpp" Point3D::Point3D(float x, float y, float z){ x = x; y = y; z = z; } CubicPatch::CubicPatch(std::array<Point3D, 16> CP){// **Call to implicitly-deleted default constructor of 'std::arraw<Point3D, 16>'** cp = CP; } std::array<CubicPatch*, 2> CubicPatch::LeftRightSplit(float tLeft, float tRight){ std::array<CubicPatch*, 2> newpatch; /* No code for now. */ return newpatch; } Could someone tell me what is the problem here, please ? I found similar topics but not really the same and I didn't understand the explanations given. Thanks. A: Two things. Class members are initialized before the body of the constructor, and a default constructor is a constructor with no arguments. Because you didn't tell the compiler how to initialize cp, it tries to call the default constructor for std::array<Point3D, 16>, and there is none, because there is no default constructor for Point3D. CubicPatch::CubicPatch(std::array<Point3D, 16> CP) // cp is attempted to be initialized here! { cp = CP; } You can get around this by simply providing an initializer list with your Constructor definition. CubicPatch::CubicPatch(std::array<Point3D, 16> CP) : cp(CP) {} Also, you might want to have a look at this code. Point3D::Point3D(float x, float y, float z){ x = x; y = y; z = z; } x = x, y = y, z = z doesn't make sense. You're assigning a variable to itself. this->x = x is one option to fix that, but a more c++ style option is to use initializer lists as with cp. They allow you to use the same name for a parameter and a member without the use of this->x = x Point3D::Point3D(float x, float y, float z) : x(x) , y(y) , z(z) {}
[ "stackoverflow", "0022660468.txt" ]
Q: Move a Bitmap image with mouse like drag & drop So that's what I wanna do. I load an Bitmap image like this on WM_CREATE g_hbmCar = LoadBitmap(GetModuleHandle(NULL), MAKEINTRESOURCE(IDB_CAR)); Next is to catch if the left mouse button is pressed and if the arrow is on the image & get coordinates like this(if I'm right ): case WM_LBUTTONDOWN: {RECT rcClient; // check if the cursor is within the image.x limits if(LOWORD(lParam)>=g_carInfo.x && LOWORD(lParam)<=g_carInfo.x+g_carInfo.width) { //check if the cursor is within the image.y limits if(HIWORD(lParam)<=g_carInfo.y && HIWORD(lParam) >= g_carInfo.y + g_carInfo.height) { case WM_MOUSEMOVE : { if (wParam & MK_LBUTTON ) { HDC hdc = GetDC (hwnd) ; g_carInfo.x +=LOWORD (lParam); g_carInfo.y += HIWORD(lParam); UpdateCar(&rcClient,&g_carInfo); DrawCar(hdc,&rcClient,hbr, g_hbmCar, g_hbmMask,g_carInfo); ReleaseDC (hwnd, hdc) ; } } break; } } } break; but this does not seems to work :( Any help would be appreciated. Thanks! A: case WM_MOUSEMOVE will not happen while your code is executing case WM_LBUTTONDOWN. You need to break the operation up into 3 steps. (1) If the click is within the image limits then call SetCapture. This makes sure you will get all subsequent WM_MOUSEMOVE messages, even if the mouse if moved outside your window. Return from the WM_LBUTTONDOWN handler. (2) In the WM_MOUSEMOVE handler, if GetCapture indicates you have the mouse captured, then do your painting. Or, it might be easier and better to simply InvalidateRect, and then let the subsequent WM_PAINT paint the object. (3) At WM_LBUTTONUP do ReleaseCapture.
[ "stackoverflow", "0043606686.txt" ]
Q: Android - Connect to socket in separate thread I am trying to create a very-very simple server-client application in Android. The server is running on my pc, it was written in python. (just a simple while (true) loop which receives a string and responses with an other string.) The problem is in the Android client. So i tried to create a singleton class in a separate thread, which: create the socket connect to the socket is reachable from other activites write to socket read from socket I try to write and read from an other asynctask. It is working until i try to write to the socket again. (1 write is ok, any other attempts are failed.) I do not get any exception, i checked if the socket closed or the writer null, etc. The message just not wrote to the socket. What's wrong with this solution? :/ Could you please help me? Here is the thread: public class ConnectThread extends Thread { // singleton Part private static class ThreadHolder { static final ConnectThread instance = new ConnectThread(); } public static synchronized ConnectThread getInstance(){ if(ThreadHolder.instance == null) Log.d("mytag", "NEW INSTANCE CREATED"); // return (ThreadHolder.instance == null) ? ThreadHolder.instance = new ConnectThread() : ThreadHolder.instance; return ThreadHolder.instance; } private ConnectThread(){ } // implementation part private Socket mSocket; private BufferedWriter socketWriter; private BufferedReader socketReader; public Socket getSocket() { return mSocket; } public void WriteToSocket(String msg) { try{ if(!(mSocket.isClosed())) { Log.d("mytag", "Writing to socket"); if(socketWriter == null) Log.d("mytag", "Writer closed - in write to socket"); socketWriter.write(msg); socketWriter.flush(); }else Log.d("mytag", "CANT write to socket"); }catch(IOException e) { e.printStackTrace(); Log.d("mytag", e.toString()); } } public String ReadFromSocket() { try { if(!(mSocket.isClosed())) { Log.d("mytag", "Reading from socket"); if(socketReader == null) { Log.d("mytag", "Reader closed - in read from socket"); } return socketReader.readLine(); }else { Log.d("mytag", "CANT from socket"); return null; } }catch (IOException e) { e.printStackTrace(); return null; } } @Override public void run() { try { mSocket = new Socket(); mSocket.setKeepAlive(true); try { mSocket.setTcpNoDelay(true); } catch (SocketException e) { } mSocket.connect(new InetSocketAddress("192.168.0.128", 8888), 2000); if(!(mSocket.isClosed())) { Log.d("mytag", "SOCKET IS RUNNING"); socketWriter = new BufferedWriter(new OutputStreamWriter(this.mSocket.getOutputStream())); socketReader = new BufferedReader(new InputStreamReader(this.mSocket.getInputStream())); if(socketWriter == null) { Log.d("mytag", "WRITER NOT CREATED"); }else Log.d("mytag", "WRITER READY"); if(socketReader == null) { Log.d("mytag", "READER NOT CREATED"); }else Log.d("mytag", "READER READY"); } }catch (IOException e) { e.printStackTrace(); } } } And here are the attempts to read, write: @Override protected Void doInBackground(Void... params) { PrintDebugMsg("do in background"); //-------------------------------------------------------------------------------------- changeProgressMsg(progressDialog, "Checking network availability..."); //progressDialog.setTitle("Checking network availability..."); //check network: ConnectivityManager cm = (ConnectivityManager) getApplicationContext().getSystemService(parentContext.CONNECTIVITY_SERVICE); NetworkInfo netInfo = cm.getActiveNetworkInfo(); if(netInfo != null && netInfo.isConnected()) { networkAvail = true; response += "| Network available |"; } PrintDebugMsg("do in background 2"); try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } changeStatusImg(imgvNetworkStatus, networkAvail?R.drawable.online:R.drawable.offline); //-------------------------------------------------------------------------------------- changeProgressMsg(progressDialog, "Pinging server"); //progressDialog.setTitle("Pinging server..."); //check server status try { PrintDebugMsg("do in background 3"); if(!(ConnectThread.getInstance().getSocket().isClosed())) { ConnectThread.getInstance().WriteToSocket(PING_FROM_DROID); String line = ""; line = ConnectThread.getInstance().ReadFromSocket(); if(line.equals(PING_ACK)) { serverAvail = true; response += " | pinged |"; PrintDebugMsg("do in background 4", true); } } else{ response += " | NOT pinged |"; PrintDebugMsg("do in background 5", true); throw new UnknownHostException(); } PrintDebugMsg("do in background 6", true); } catch (UnknownHostException e) { // TODO Auto-generated catch block e.printStackTrace(); response += " | UnknownHostException: " + e.toString() + " - during server check |"; PrintDebugMsg("do in background 7", true); } finally{ PrintDebugMsg("do in background 9", true); if(ConnectThread.getInstance().getSocket() != null){ } } PrintDebugMsg("do in background 10", true); if(serverAvail) { try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } } changeStatusImg(imgvServerStatus, serverAvail?R.drawable.online:R.drawable.offline); //-------------------------------------------------------------------------------------- changeProgressMsg(progressDialog, "Connectiong to server..."); //connect to server: try { PrintDebugMsg("do in background 11",true); //socket = new Socket(dstAddress, dstPort); //socket = ConnectThread.getInstance().getSocket(); PrintDebugMsg("do in background 12",true); if(!(ConnectThread.getInstance().getSocket().isClosed())) { PrintDebugMsg("do in background 13",true); PrintDebugMsg("do in background 14",true); PrintDebugMsg("do in background 15",true); ConnectThread.getInstance().WriteToSocket(CONN_REQ_FROM_DROID); String line = ""; line = ConnectThread.getInstance().ReadFromSocket(); PrintDebugMsg("conn line = " + line, true); if(line != null && line.equals(CONN_ACK)) { connected = true; response += "| connected |"; PrintDebugMsg("do in background 12"); } }else { response += "| NOT connected |"; PrintDebugMsg("do in background 13"); throw new UnknownHostException(); } } catch (UnknownHostException e) { // TODO Auto-generated catch block e.printStackTrace(); response += " | UnknownHostException: " + e.toString() + " - during connecting |"; }finally{ PrintDebugMsg("connection finished"); } if(connected) { try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } } changeStatusImg(imgvConnectionStatus, connected?R.drawable.online:R.drawable.offline); //-------------------------------------------------------------------------- ------------ return null; } The "util" functions: private void PrintDebugMsg(String msg, boolean b) { if(b) Log.d("mytag", msg); } private void changeProgressMsg(final ProgressDialog dialog,final String value){ runOnUiThread(new Runnable() { @Override public void run() { dialog.setMessage(value); } }); } private void changeStatusImg(final ImageView imgView, final int imgId){ runOnUiThread(new Runnable() { @Override public void run() { imgView.setImageResource(imgId); } }); } A: Sever.java public class Server { public static void main(String[] args) { new Server().startServer(); } public void startServer() { final ExecutorService clientProcessingPool = Executors.newFixedThreadPool(10); Runnable serverTask = new Runnable() { @Override public void run() { try { ServerSocket serverSocket = new ServerSocket(8000); System.out.println("Waiting for clients to connect..."); while (true) { Socket clientSocket = serverSocket.accept(); clientProcessingPool.submit(new ClientTask(clientSocket)); } } catch (IOException e) { System.err.println("Unable to process client request"); e.printStackTrace(); } } }; Thread serverThread = new Thread(serverTask); serverThread.start(); } private class ClientTask implements Runnable { private final Socket clientSocket; private ClientTask(Socket clientSocket) { this.clientSocket = clientSocket; } @Override public void run() { System.out.println("Got a client !"); // Do whatever required to process the client's request try { clientSocket.close(); } catch (IOException e) { e.printStackTrace(); } } } }
[ "softwarerecs.stackexchange", "0000035554.txt" ]
Q: C++ open source library for curve fitting I'm searching for the most minimalist C++ open source library that allows to obtain a curve parameters (e.g. Bezier) given a set of points. In my application the user gets some strokes by drawing on the screen. I have a track of all the points of each stroke, and would like to smooth out each stroke after it is drawn. I realized it can be achieved by curve fitting so that to turn polygon strokes into curvy strokes. I found some papers on how to implement curve fitting, e.g. this or this, but they are not C++. While I could implement a simple curve fitter, I thought to see if there is already a good C++-based library for it, so that I could use it right away. It needs to be open source. It would be nice if the library has no dependencies on other larger libraries. A: Four points are required to uniquely describe a cubic curve (the first article you've linked covers that case). You have more than four points so are unlikely to get a perfect fit - some kind of compromise or trade-off will be required. Welcome to the black art of numerical optimisation! The second article you've linked introduces this topic using C# and Math.NET. If you're happy to treat the general purpose optimiser as a black box, then I prefer the Excel Solver (and a good tutorial) for learning about what an optimiser can do. Basically we define a function, then the optimiser calls it repeatedly with different parameters attempting to get the lowest return value it can. I recommend dlib. Here I use dlib to fit a few points to a Bezier curve. I got it to compile fairly easily in Visual Studio 2013, but it will probably need tweaking to get it to work with a different compiler. The parts of dlib used here are all in headers, there's no .lib file you need to link to. #include <stdio.h> #include "../dlib/optimization.h" typedef dlib::matrix<double,0,1> column_vector; struct Point { double x; double y; }; static Point points[] = { { 254 , 102 }, { 226 , 63 }, { 185 , 49 }, { 146 , 74 }, { 142 , 119 }, { 117 , 169 }, { 86 , 214 }, { 40 , 200 }, }; // // cubicBezier // // p1 - start point // c1 - first control point // c2 - second control point // p2 - end point // double cubicBezier(double p1, double c1, double c2, double p2, double t) { double s = (1 - t); double v = 0; v = v + (1 * p1 * s * s * s); v = v + (3 * c1 * s * s * t); v = v + (3 * c2 * s * t * t); v = v + (1 * p2 * t * t * t); return v; }; Point cubicBezier(double p1x, double p1y, double c1x, double c1y, double c2x, double c2y, double p2x, double p2y, double t) { Point pt; pt.x = cubicBezier(p1x, c1x, c2x, p2x, t); pt.y = cubicBezier(p1y, c1y, c2y, p2y, t); return pt; } // Any distance function can be used for optimisation. This one, where we want // to find the least-squares is most common. double dist(double x1, double y1, double x2, double y2) { double x = x2 - x1; double y = y2 - y1; return (x * x) + (y * y); } // This is the function that the optimiser calls repeatedly with different // parameters, attempting to get the lowest return value it can. double rateCurve(const column_vector& params) { double p1x = points[0].x; double p1y = points[0].y; double c1x = params(0,0); double c1y = params(1,0); double c2x = params(2,0); double c2y = params(3,0); double p2x = points[7].x; double p2y = points[7].y; double distances = 0; for (Point target : points) { double distance = _DMAX; for (double t = 0; t <= 1; t += 0.02) { Point pt = cubicBezier( p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y, t); double dCandidate = dist(pt.x, pt.y, target.x, target.y); distance = std::min(distance, dCandidate); } distances += distance; } // Thats the curve-fitting done. Now incentivise slightly smoother curves. double p1c1 = dist(p1x, p1y, c1x, c1y); double p2c2 = dist(p2x, p2y, c2x, c2y); return distances + pow(p1c1, 0.6) + pow(p2c2, 0.6); } int main(int argc, char* argv[]) { column_vector params(4); params = points[7].x, points[7].y, points[0].x, points[0].y; dlib::find_min_using_approximate_derivatives( dlib::cg_search_strategy(), dlib::objective_delta_stop_strategy(1).be_verbose(), rateCurve, params, -1); printf("p1x = %f;\n", points[0].x); printf("p1y = %f;\n", points[0].y); printf("c1x = %f;\n", params(0,0)); printf("c1y = %f;\n", params(1,0)); printf("c2x = %f;\n", params(2,0)); printf("c2y = %f;\n", params(3,0)); printf("p2x = %f;\n", points[7].x); printf("p2y = %f;\n", points[7].y); return 0; } Here's the output: iteration: 0 objective: 9740.42 iteration: 1 objective: 4880.37 iteration: 2 objective: 2872.77 iteration: 3 objective: 2523.82 iteration: 4 objective: 2048.95 iteration: 5 objective: 1680.86 iteration: 6 objective: 1519.74 iteration: 7 objective: 1366.39 iteration: 8 objective: 1330.56 iteration: 9 objective: 1285.79 iteration: 10 objective: 1275.27 iteration: 11 objective: 1274.82 p1x = 254.000000; p1y = 102.000000; c1x = 127.524342; c1y = -86.849427; c2x = 146.034795; c2y = 283.099363; p2x = 40.000000; p2y = 200.000000; And here's a visualisation showing my points and the attempt to fit them:
[ "stackoverflow", "0004535760.txt" ]
Q: Function bounds in gnuplot I want to plot multiple bounded functions in gnuplot. I.e. plot x from 0 to 2 and x^2 from 1 to 3 and have them show up together. How do you plot functions with different bounds? I know how to do a piecewise function, like (x < 1 ? x : x**2). This is not what I want to do. A: plot 0 <= x && x <= 2 ? x : 1/0, \ 1 <= x && x <= 3 ? x**2 : 1/0 We need to define what to draw outside the desired range, so we just use an undefined function f(x)=1/0 so that nothing is graphed in these ranges.
[ "stats.stackexchange", "0000336358.txt" ]
Q: Turkish speech recognition (speech->text) in Google Speech API? Google's Speech API has audio speech to text capabilities in multiple languages. It supports Turkish too. That language is very interesting, it's so called agglutinative: you stick word parts one after another instead of prepositions and other parts in languages like English. This leads to pretty much unlimited size vocabulary. Do you know how Google implemented Turkish speech recognition for their API? I can't believe they used the same techniques as in English. UPDATE Here's an example transcript that Google API returned from the following clip on YouTube: you would have to ask him I have no clue Yahoo answers I was Adam Scott really in Jumanji in The Truman Show I looked him up on iTunes it said under movies her is in was Jumanji and The Truman Show I don't * * * * believe it will listen I'm not in either of those movies so yeah you really shouldn't * * * * I think it's excellent quality of transcription. I used my beautiful AudioEngine monitors and put a crappy 20 years old LabTec computer mic in front of it. A truly amateur setup, but that's how these things will be used in practice, i.e. in less than ideal situation. Here's an example from a Turkish movie scene: merhaba Temmuz Ben hoş geldin kardeş e nasılsınız keyifler iyidir inşallah İyi valla koşturuyoruz nasıl olsun Hem kardeş lafı uzatmadan konuya girsek anlattı bana ikinci el işçiliği Tabii sen güzel bir şey yapıyor Dernek falan da işte ilişkin bir delikanlı eve gelip gidiyor This one is basically incomprehensible. It picks up some words here and there, but it's hard to connect them unlike in English example. Does this mean that Google is not using a custom solution for Turkish? Maybe they want for repurposing their English language engines for Turkish ? Just for fun, I sent a clip from Azeri language speaker. He's speech is clearly enunciated but the API barely got a few words. I used Turkish setting, so it's not fair, really, but the languages are similar: o akşam Çağlayan Doruk sevgilin kim bu kim baktı Bülent Serttaş çok pis A: What is used in production is often not disclosed. I'm not aware of Google disclosing how the current automated speech recognition (ASR) system they using production works. One way to approximate it would be to scan ICASSP/Interspeech/etc. proceedings for Google publications. Anyway, putting Google aside: the question can be generalize as "How to perform ASR in languages with large or open ended dictionaries?". One way to do so is to use sub-word language modeling, e.g. from {1}: Abstract: In this study, some solutions for out of vocabulary (OOV) word problem of automatic speech recognition (ASR) systems which are developed for agglutinative languages like Turkish, are examined and an improvement to this problem is proposed. It has been shown that using sub-word language models outperforms word based models by reducing the OOV word ratio in languages with complex morphology. or from {2}: Abstract: Turkish speech recognition studies have been accelerated recently. With these efforts, not only available speech and text corpus which can be used in recognition experiments but also proposed new methods to improve accuracy has increased. Agglutinative nature of Turkish causes out of vocabulary (OOV) problem in Large Vocabulary Continuous Speech Recognition (LVCSR) tasks. In order to overcome OOV problem, usage of sub-word units has been proposed. In addition to LVCSR experiments, there have been some efforts to implement a speech recognizer in limited domains such as radiology. In this paper, we will present Turkish speech recognition software, which has been developed by utilizing recent studies. Both interface of software and recognition accuracies in two different test sets will be summarized. The performance of software has been evaluated using radiology and large vocabulary test sets. In order to solve OOV problem practically, we propose to adapt language models using frequent words or sentences. In recognition experiments, 90% and 44% word accuracies have been achieved in radiology and large vocabulary test sets respectively. References: {1} Akın, Ahmet Afşın, Cemil Demir, and Mehmet Uğur Doğan. "Improving sub-word language modeling for Turkish speech recognition." In Signal Processing and Communications Applications Conference (SIU), 2012 20th, pp. 1-4. IEEE, 2012. https://scholar.google.com/scholar?cluster=8818380122461969221&hl=en&as_sdt=0,5 ; http://ieeexplore.ieee.org/abstract/document/6204752/ {2} Buyuk, Osman, Ali Haznedaroglu, and Levent M. Arslan. "Turkish speech recognition software with adaptable language model." In Signal Processing and Communications Applications, 2007. SIU 2007. IEEE 15th, pp. 1-4. IEEE, 2007. https://scholar.google.com/scholar?cluster=17945910226656308345&hl=en&as_sdt=0,5 ; http://ieeexplore.ieee.org/abstract/document/4298561/
[ "math.stackexchange", "0003646037.txt" ]
Q: Check the continuity and analyticity of complex function $f(z)$ Given function $$\displaystyle f(z)=\left\{\begin{matrix} \frac{\bar{ z}^2}{z} & \text{if} \;\; z \neq 0\\ 0 & \text{otherwise} \end{matrix}\right.$$ I have to check its continuity and analyticity. solution i tried- i write the function as $$f(z)=\displaystyle \frac{r^2e^{-2i\theta}} {re^{i\theta}}$$ $$\lim_{r \to 0}f(z)=re^{-3i\theta}\to 0$$ so this is continuous on whole $\mathbb{C}$ For analyticity i solved this as $$\frac{(x-iy)^2}{(x+iy)}=\frac{x^2-y^2-2xiy}{x+iy}$$ after solving this i get $$u=\frac{x^3-xy^2-2xy^2}{x^2+y^2} ,\;\;v=\frac{-2x^2y-x^2y+y^3}{x^2+y^2}$$ now i have to fin the $u_x$ and $v_x$ $u_y$ and $v_y$ ,after doing this it seems very complicated to solve further ,can someone please provide a short method to solve this question,or is there any other method which can make it simple and more understandable. Please help Thank you A: It is clear that $f$ is continuous for $z \neq 0$ and since $|f(z)| \le |z|$ it is continuous at $z=0$. Suppose $f$ is analytic, then $g(z) = z^3f(z) = |z|^2 $ would be analytic, but since $g$ is real valued it must be a constant hence a contradiction. Hence $f$ is not analytic.
[ "stackoverflow", "0029652264.txt" ]
Q: Why is my python function not being executed? I have written a script that is pretty temperamental with indentation so I decided to make functions. I'm pretty new to python and now that I've created these functions nothing works! def main (): wiki_scrape() all_csv() wiki_set = scraped_set('locations.csv') country_set = all_set('all.csv') print wiki_set I'm just wondering if this is the correct way to call functions from the main() function? I've been debating if an indentation issue is occurring within the called functions, python seems to be very reliant on proper indentations even though it doesn't come up with an error! Full Code - http://pastebin.com/gJGdHLgr A: It sounds like you need to do this: def main(): wiki_scrape() all_csv() wiki_set = scraped_set('locations.csv') country_set = all_set('all.csv') print wiki_set main() # this calls your main function Even better: def main(): wiki_scrape() all_csv() wiki_set = scraped_set('locations.csv') country_set = all_set('all.csv') print wiki_set if __name__ == '__main__': main() # this calls your main function Then run it from the command line like this: python file_name.py The built-in variable __name__ is the current contextual namespace. If you run a script from the command line, it will be equivalent to '__main__'. If you run/import the .py file as a module from somewhere else, including from inside the interpreter, the namespace (inside of the context of the module) will be the .py file name, or the package name if it is part of a package. For example: ## my_file.py ## print('__name__ is {0}'.format(__name__)) if __name__ = '__main__': print("Hello World!") If you do this from command line: python my_file.py You will get: __name__ is __main__ Hello World! If you import it from the interpreter, however, you can see that __name__ is not __main__: >>> from my_file import * >>> __name__ is my_file A: Python doesn't call any functions on starting unless explicitly asked to (including main). Instead Python names the files being run, with the main file being run called __main__. If you want to simply call the main function you can use Rick's answer. However in Python best practice it is better to do the following: if __name__ == '__main__': wiki_scrape() all_csv() wiki_set = scraped_set('locations.csv') country_set = all_set('all.csv') print wiki_set This ensures that if you are running this python file as the main file (the file you click on, or run from the cmd) then these functions will be run. If this is instead used as an imported module, you can still use the functions in the script importing the module, but they will not be called automatically and thus won't interfere with the calling script.
[ "stackoverflow", "0022124049.txt" ]
Q: Uncapped vs SetInterval framerate for HTML5 canvas? Looking at this HTML5 game tutorial and it uses the following code to update the frame at 30 frames per second: var FPS = 30; setInterval(function() { update(); draw(); }, 1000/FPS); From the viewpoint of traditional videogames, it is bad practice to cap a game's framerate (and it's really annoying when games, usually bad console ports, do this). I am wondering if this is a necessity for an HTML5 canvas game. Would an unlimited framerate do something really bad like lock up the browser or use up all the computer's resources? I am thinking of code something like this: update(); function update() { // Move stuff around draw(); } function draw() { // Draw the changes update(); } Is there a better way to do this? A: Check out window.requestAnimationFrame (RAF). As its name implies, RAF has been created to do a decent job of managing animations. RAF tries to give you the best of capped and uncapped timers. RAF creates an animation loop that synchronizes well with the display refreshes. RAF waits asynchronously so your UI thread is not blocked while waiting for the next frame. RAF will automatically attempt to loop at about 60fps. Latest RAF gives you an elapsed timer that you can use to (1) skip this loop if you need fewer fps (2) catch-up your animation if the last frame was skipped--for example due to system garbage collection.
[ "stackoverflow", "0052011252.txt" ]
Q: Are completion handler closures always running in the background thread? Completion handler closures are common in iOS development, such as dataTask(with:completionHandler:) in the URLSession class. The UI engine is managed by the main thread, the API calls by URLSession are run under the background thread and must be dispatched to the main thread if a UI update is needed in the handler. Question 1: Do all completion handler closures from the iOS framework run in the background thread? Question 1.1: Do all escaping closures, for example, created by developers, run in the background thread? Question2: I've seen up to 8 threads in the iPhone X simulator. Which one is the main thread and which one is the background thread in ios? Do they have different priorities and computational power? A: Keep in mind that you are really asking about queues and threading more than completion handlers and closures. Code of any type is executed on a queue (which consists of one or more threads). There is nothing special about completion handler closures in this regard. Q1 - Most iOS SDK provided completion handlers are called on a background queue but don't make that assumption unless the documentation specifically states what queue it is called on. Even URLSession can be configured to run on a specific queue, including the main queue. Q1.1 - Closures that you write are run on whatever queue you call them from. There is no magic that makes them run on a background queue. Q2 - The first thread is always the only thread of the main queue. All other threads are from background queues. Each thread can have whatever priority is was given based on the properties of its queue. You should review the Dispatch documentation for further details, especially DispatchQueue.
[ "gis.stackexchange", "0000212821.txt" ]
Q: pyshp Create Multipatch cube I am trying to create a Multipatch Shapefile in the shape of a cube. I am using pyshp library and could create one face as a 3D Polygon as described in the wiki of pyshp (Creating 3D Polygons). However, I am not able to create a multipatch geometry, probably because I do not use the right order of coordinates or something like that. Here is my Code using the coordinate order described by esri (Link, doc Page 35): w = shapefile.Writer(shapeType=shapefile.MULTIPATCH) w.poly(parts=[[[0,0,0] , [0,0,1] , [0,1,1] , [0,0,0]] , [[0,0,0] , [1,0,0] , [1,1,0] , [0,0,0]], [[0,1,0] , [0,1,1] , [0,0,0] , [0,1,0]] , [[0,0,0] , [0,1,1] , [0,0,1] ,[0,0,0]], [[1,1,0] , [0,1,1] , [0,1,0] ,[1,1,0]], [[1,1,0] , [1,1,1] , [0,1,1]] , [[1,0,0] , [1,1,1] , [1,1,0] ,[1,0,0]], [[1,0,0] , [1,0,1] , [1,1,1]] , [[0,0,0] , [0,0,1] , [1,0,0] ,[0,0,0]], [[1,0,0] , [0,0,1] , [1,0,1]] , [[0,0,1] , [0,1,1] , [1,1,1] ,[0,0,1]], [[0,0,1] , [1,1,1] , [1,0,1]]], shapeType=31) w.field("NAME") w.record("PolyZTest") w.save("shapefiles/test/MyPolyS") What am I doing wrong? Is the usage of poly() wrong? A: You're close - just a few minor issues. Multipatch shapefiles need a specialized type for each part which can be: VALUE PART TYPE 0 Triangle Strip 1 Triangle Fan 2 Outer Ring 3 Inner Ring 4 First Ring 5 Ring In pyshp, this is defined in your parts array using the array "partTypes" All polygons must move in clockwise order which I didn't double-check in your example. I created my own coordinates to be sure and used the rest of your code verbatim to create a working cube: import shapefile w = shapefile.Writer(shapeType=shapefile.MULTIPATCH) w.poly(parts=[ [[0,0,0], [0,1,0], [0,1,1], [0,0,1], [0,0,0]], [[0,0,0], [0,0,1], [1,0,1], [1,0,0], [0,0,0]], [[1,1,0], [1,1,1], [0,1,1], [0,1,0], [1,1,0]], [[1,0,0], [1,0,1], [1,1,1], [1,1,0], [1,0,0]], [[0,0,1], [0,1,1], [1,1,1], [1,0,1], [0,0,1]], [[0,0,0], [0,1,0], [1,1,0], [1,0,0], [0,0,0]] ], partTypes=[5,5,5,5,5,5], shapeType=31) w.field("NAME") w.record("PolyZTest") w.save("MyPolyS") Here is what the above output looks like in Esri ArcScence:
[ "stackoverflow", "0003227314.txt" ]
Q: how to stop "cannot stop" builds on TeamCity I get "cannot stop" status once in a while after trying to stop builds on TeamCity. I would expect that killing my build process on build agent would do the trick, but it doesn't work. Stopping TeamCity agent process on the build machine doesn't help either. Restarting build agent (i.e. computer) does the trick, but it takes plus 2-3min after the machine has started. It looks like TeamCity server itself thinks that my build is still running. Is there a better way to stop those builds? Or maybe there is some info somewhere that could explain this logic? A: Please see/vote for http://youtrack.jetbrains.net/issue/TW-3154 and related requests
[ "serverfault", "0000086549.txt" ]
Q: Same or separate subnets when connecting two buildings via a wireless bridge We have two buildings about 200 feet apart connected via SMC's outdoor wireless bridge. Currently, both buildings are on the same subnet with one DHCP server in the main building. This seemed to be the easiest way to setup our network so that clients in either building could have access to the Samba drive in the main building. However, one problem with this configuration is that if the wireless bridge link goes down, then the remote building no longer has a DHCP server. So I'm wondering if it would be better to have the two buildings setup on separate subnets. If I were to convert the two buildings to separate subnets, what configuration changes would I need to make in order for the clients in the remote building be able to have access to the Samba drive in the main building? Other, Potentially Pertinent Configuration Details Linksys RV082 Wired Router in the main building provides DHCP as well as VPN access for remote clients Each building has a Linksys WRT54G Wireless Router with DHCP disabled to provide wireless Ethernet in each building Aside from the Ubuntu server providing the Samba drive, we also have two other servers in the main building both running Ubuntu The majority of clients are WinXP Pro laptops; however, we do have a few Ubuntu and a few Mac OS X clients All servers and network connected printers are configured with static IPs via the RV082. All clients are configured for DHCP. A: Personally, I'd set them up as separate, if only to keep the broadcast traffic from going over the wireless. I think that once you had set up the subnets, the only change required would be to make sure that the samba server accepted the other subnet as a valid client source. A: If you are only concerned about DHCP availability, then don't bother with a separate subnet. There shouldn't be any problem at all setting up 2 DHCP servers on the same subnet as long as they are handing out different ranges of IP addresses. It looks like your existing hardware should support it and it would solve the primary problem you mentioned. It also has the added benefit of some redundancy in case one of the routers stops handing out addresses, which seems common with little appliances like these. If you continue to run one subnet, remember that your machines will pick up addresses from either DHCP server. There are other benefits to separate subnets such as limiting your broadcast traffic and the ability to use a routing protocol to provide redundant links in the future. Before adding this complexity, I would figure out whether limiting broadcast traffic will provide a noticeable performance improvement, either now or as your network grows. If you are going to grow significantly in the future, it might be better to just break your subnet up now rather than having to readdress a huge chunk of your network down the road. If you do go with separate subnets, you will have a different gateway for the machines on the second subnet and obviously all of the routing to get between subnets. I also expect you would need to set up and use the WINS server that comes with SAMBA. (SMB doesn't play nice on separate subnets without WINS) And as a quick aside, I have Cisco and RAD bridges linking several fire stations up over distances of several miles, and I can't say enough about good antennas. You might find your bridges to be a lot more reliable if you can get some dish or yagi antennas.
[ "tex.stackexchange", "0000534495.txt" ]
Q: Buffer inside (b)Table \starttext \bTABLE \bTR \bTD% \startbuffer[mytest] \input knuth \stopbuffer[mytest] \eTD \eTR% \eTABLE% \stoptext tex error > tex error on line 10 in file ...tex: ! Undefined control sequence Why is this happening and how do I solve it? A: TL;DR You can't do it. Put the buffer outside the table. The reason is that \bTD...\eTD reads the content in between as an argument. You can easily reproduce the same error with this: \starttext \def\test#1\endtest{#1} \test \startbuffer[mytest] \input knuth \stopbuffer[mytest] \endtest \stoptext The actual problem is that by reading the content as an argument, catcodes are being fixed, in particular, line endings are converted to spaces, which results in \test \startbuffer[mytest] \input knuth \stopbuffer[mytest] \endtest but both \startbuffer and \stopbuffer have to appear on an individual line. Deeper down, \start...\stopbuffer uses the process_input_buffer callback to scan the buffer, but when you register the callback on the line where \startbuffer appears, it will only kick in on the next line, i.e. everything else on the same line as \startbuffer is still normally processed and expanded by TeX. The \stopbuffer command is not actually defined because it is only used as a marker for the callback to know when to stop scanning and is then discarded, but because it appears as regular TeX input here and it is not defined, you get the undefined control sequence error you are seeing. Since you keep insisting that for some unknown, ludicrous reason you have to do this, here is a poor workaround that is guaranteed to fail in other cases. I strongly believe that buffers are the wrong way to do whatever you want to do, but since you keep making up XY problems (which you have been repeatedly asked not to) there is really nothing further I can do. The real solution is to not use buffers in macros. Neither as an argument, nor in the replacement text. \starttext \def\test#1\endtest{#1} \test \ctxlua{buffers.assign( "mytest", "\luaescapestring{\normalunexpanded{\input knuth }}")}% \endtest \getbuffer[mytest] \stoptext
[ "stackoverflow", "0020397450.txt" ]
Q: Oracle SQL populating a Time Dimension I'm writing a block of code to populate a time dimension in Oracle 11gR2 using SQL Developer Table Structure KEY Number(8,0) HRS Varchar2 MINS Varchar2 SECS Varchar2 I'm new to PL/SQL - the way i would normally think of doing in pseudo-code would be but the for loops in PL/SQL don't seem to work this way: key = 1 for (hrs=0; hr<=23; hr++) { for (min=0; min<=59; min++) { for (sec=0; sec<=59; sec++) { insert (KEY, tochar(hrs:mins:secs), tochar(hr), tochar(min), tochar(sec)) SK=+1 } } } I've tried this from an answer i found: insert into Dim_TIME (Key, TIME_IN24_NAME, TIME_HOUR24, TIME_MINUTE, TIME_SECOND) select to_char(t, 'HH24:MI:SS'), to_number(to_char(t, 'HH24'), '00'), to_number(to_char(t, 'MI'), '00'), to_number(to_char(t, 'SS'), '00') from ( select trunc(sysdate) + (level - 1)/86400 as t from dual connect by level <= 86400 ); But not sure how i would increment the key (the column field is not auto-increment). Any ideas how i could achieve this? Thanks A: You can create a SEQUENCE to increment the field KEY. CREATE SEQUENCE dim_time_seq; And use it in your code like this, INSERT INTO dim_time (KEY, time_in24_name, time_hour24, time_minute, time_second) SELECT dim_time_seq.nextval, to_char(t, 'HH24:MI:SS'), to_number(to_char(t, 'HH24'), '00'), to_number(to_char(t, 'MI'), '00'), to_number(to_char(t, 'SS'), '00') FROM ( SELECT trunc(SYSDATE) + (LEVEL - 1)/86400 AS t FROM dual CONNECT BY LEVEL <= 86400 );
[ "math.stackexchange", "0000051053.txt" ]
Q: A matrix eigenvalue problem In my previous problem, I made a typo. Now I restate it as a new problem. Let $ \begin{bmatrix} A& B \\ B^* &C \end{bmatrix}$ be positive semidefinite, $A,C$ are of size $n\times n$. Is it true that $$\quad \sum\limits_{i=1}^k\lambda_i\begin{bmatrix} A& B \\ B^* &C \end{bmatrix}\le \sum\limits_{i=1}^k\left(\lambda_i(A)+\lambda_i(C)\right)\quad, $$ where $1\le k\le n$? Here, $\lambda_i(\cdot)$ means the $i$th largest eigenvalue of $\cdot\quad$ A: This question is answered by T. Ito at https://mathoverflow.net/questions/70689/ask-some-matrix-eigenvalue-inequalities
[ "stackoverflow", "0026252230.txt" ]
Q: MVC4 won't pass Model to Controller I'm trying to pass a C# object as a parameter back to the controller. It's done like this: @model Models.AdvancedSearchTerms @{ ViewBag.Title = "Loading"; } @Html.DisplayFor(Model => Model.Keyword) @using (Html.BeginForm("MetaSearch", "AdvancedSearch", new { term = Model }, FormMethod.Post)) { <input id="startGatheringData" type="Submit" name="Convert" /> } As you see I try to send the whole model back to controller if the button is pushed. But when the method in the controller gets the Model it is null. To ensure that the Model is not empty in the View, you can see that I've tried to print a variabel using the @Html.DisplayFor, and it works. So the Model is not empty in the View, but disappears when I pass it to the controller: public ActionResult MetaSearch(AdvancedSearchTerms term) { //Do stuff with the model retrived from the View() return View() } Anyone got any idea why this object is empty? I've done this a lot and have no idea why it is not working this time. I've also tried to only pass a single variabel, but this is also Null. In advance, thanks! A: You have to create input fields for this inside the form, if you don't want to show them to user use Hidden Fields: @using (Html.BeginForm("MetaSearch", "AdvancedSearch", FormMethod.Post)) { @Html.HiddenFor(x=>x.SomeProperty) @Html.HiddenFor(x=>x.SomeProperty) <input id="startGatheringData" type="Submit" name="Convert" /> }
[ "stackoverflow", "0003348566.txt" ]
Q: How to obtain bounding box of transformed text(java)? Currently I have a text object that I need to determine its bounds. I used to use the graphics object to obtain the font metrics of the text I am trying to draw, but since I added functionality to rotating the object(and possibly more) I need a better way to get the bounds of this object. I have looked multiple places and nothing has really worked for me as of yet. Here is my most current attempt: //This is the bounding box edges 0: left, 1: right 2: top 3: bottom int toReturn[] = new int[4]; //this.transform is the AffineTransform for the text Object(currently only //rotated) FontRenderContext frc = new FontRenderContext(this.transform,true,false); TextLayout tl = new TextLayout(this.typedText,this.font,frc); Rectangle2D bb = tl.getBounds(); toReturn[0] = (int)(bb.getX()); toReturn[1] = (int)(bb.getX()+bb.getWidth()); toReturn[2] = (int)(bb.getY()); toReturn[3] = (int)(bb.getY()+bb.getHeight()); Is this the proper way to get the bounding box for transformed text? A: No, the AffineTransform supplied to FontRenderContext "is used to scale typographical points to pixels in this FontRenderContext." You should be able to use createTransformedShape() on the boundary to get the result you want.
[ "stackoverflow", "0058393999.txt" ]
Q: Node.js best practice for being notified when batch processing is complete I have a batch of records to process which is read from a CSV file and then inserted into a database. Being new to Node, I am unsure the best practice to be notified when the final insert is complete. I have tried using the drain event of the async queue to try and track the completion. But, I am only notified that the inserts have been started since they are all running asynchronously. A: Since you haven't provided any code here's some generic solution var fs = require('file-system'); var readRecord01 = new Promise((resolve, reject) => { fs.readFile('./some/path/record01.csv', 'utf8', function read(err, csvData) { if (err) { reject(err); } else { /* INFO: Reading file successful */ resolve(csvData); } }); }); var readRecord02 = new Promise((resolve, reject) => { fs.readFile('./some/path/record02.csv', 'utf8', function read(err, csvData) { if (err) { reject(err); } else { /* INFO: Reading file successful */ resolve(csvData); } }); }); var readRecord03 = new Promise((resolve, reject) => { fs.readFile('./some/path/record03.csv', 'utf8', function read(err, csvData) { if (err) { reject(err); } else { /* INFO: Reading file successful */ resolve(csvData); } }); }); Promise.all([readRecord01, readRecord02, readRecord03]) .then(csvData => { // foo the bar or bar the foo when all promises are resolved }); You can obviously do that in a for-loop as well: var promises = []; for(i=0;i<5;i+){ promises.push(foobar()); } Promise.all(promises) .then(() => { for(i=0;i<5;i+){ // foo the bar or bar the foo when all promises are resolved } }) .catch((e) => { // handle errors here }); Here's a good read on Promise.all()
[ "stackoverflow", "0007057187.txt" ]
Q: DOMParser fails to parse certain nodes? I'm creating a plugin for Google Chrome. I try to parse the following xml: <?xml version="1.0" encoding="utf-8"?> <anime> <entry> <id>9938</id> <title>Ikoku Meiro no Crois&Atilde;&copy;e</title> <english>Crois&Atilde;&copy;e in a Foreign Labyrinth ~ The Animation</english> <synonyms>Ikoku Meiro no Crois&Atilde;&copy;e The Animation; Ikoku Meiro No Croisee The Animation; La crois&Atilde;&copy;e dans un labyrinthe &Atilde;&copy;tranger Special</synonyms> <episodes>12</episodes> <score>7.72</score> <type>TV</type> <status>Currently Airing</status> <start_date>2011-07-04</start_date> <end_date>0000-00-00</end_date> <synopsis>The story takes place in the second half of the 19th century, as Japanese culture gains popularity in the West. A young Japanese girl, Yune, accompanies a French traveller, Oscar, on his journey back to France, and offers to help at the family&amp;#039;s ironwork shop in Paris. Oscar&amp;#039;s nephew and shop-owner Claude reluctantly accepts to take care of Yune, and we learn how those two, who have so little in common, get to understand each other and live together in the Paris of the 1800s.</synopsis> <image>http://cdn.myanimelist.net/images/anime/8/29031.jpg</image> </entry> </anime> Using this code: var parser = new DOMParser(); var xmlText = response.value; var doc = parser.parseFromString(xmlText, "text/xml"); var entries = doc.getElementsByTagName("entry"); for (var i = 0; i < entries.length; ++i) { var node = entries[i]; var titles = node.getElementsByTagName("title"); console.log("titles.length: " + titles.length); if (titles.length > 0) { console.log("title: " + titles[0].childNodes[0].nodeValue); } var scores = node.getElementsByTagName("score"); console.log("scores.length: " + scores.length); if (scores.length > 0) { console.log("score: " + scores[0].childNodes[0].nodeValue); } var ids = node.getElementsByTagName("id"); console.log("ids.length: " + ids.length); if (ids.length > 0) { console.log("id: " + ids[0].childNodes[0].nodeValue); } } Looking at the output it seems that the title node was found but not its inner text. The score node wasn't found at all: titles.length: 1 title: scores.length: 0 ids.length: 1 id: 9938 Does anyone know why this happens and/or how fix it? Workaround I'm currently using a workaround based on the solution from this answer: function htmlDecode(input){ var e = document.createElement('div'); e.innerHTML = input; return e.childNodes.length === 0 ? "" : e.childNodes[0].nodeValue; } function xmlDecode(input){ var result = input; result = result.replace(/</g, "&lt;"); result = result.replace(/>/g, "&gt;"); result = result.replace(/\n/g, "&#10;"); return htmlDecode(result); } // Usage: var parser = new DOMParser(); var doc = parser.parseFromString(xmlDecode(xmlText), "text/xml"); I'm not sure if this is the best way to go, but at least it's getting me further. A: I'm not sure whether this is the cause of your problem, but XML documents have only five named entities defined: &amp;, &lt;, &gt;, &quot; and &apos;. Replace other entities with characters they're meant to represent (your document is in UTF-8, it is completely safe to use © or other such characters) or with number entities (like &#169;). Alternatively, you may define your own entities if it would be difficult to replace them in your document: <!DOCTYPE anime [ <!ENTITY copy "&#169;"> ]>
[ "stackoverflow", "0051573854.txt" ]
Q: Qt Quick Controls 2: Retrieve standard value of a component I am making a layout in QML and I want to give my Label the same padding as an ItemDelegate. How can I get the standard padding value of an ItemDelegate? Thank you in advance! A: Firstly, you'll need an instance of an ItemDelegate. If you don't have one, you can create one and set its visible property to false: ItemDelegate { id: itemDelegate visible: false } Some of the built-in styles change as the design guidelines they're based on change, so it's not a good idea to hard-code the padding based on a style's current padding values unless you have control over that style. In addition, each style sets a different default padding, and may also use different properties to do so. The following properties can be used to control padding, starting with the most general and ending with the most specific: padding horizontalPadding (available in Qt 5.12) verticalPadding (available in Qt 5.12) leftPadding rightPadding topPadding bottomPadding Because of this, the only way to guarantee that you'll get the correct padding for each side of the control is to use the most specific properties: Label { leftPadding: itemDelegate.leftPadding rightPadding: itemDelegate.rightPadding topPadding: itemDelegate.topPadding bottomPadding: itemDelegate.bottomPadding }
[ "stackoverflow", "0053558274.txt" ]
Q: summarizing a tab separated file in pandas I have big tab separated file like this: small example: CHTOP 237 122 CHTOP 64 53 CHTOP 64 122 RPS27 986 66 RPS27 986 50 RPS27 986 227 I want to group the rows according to the 1st column and sum all numbers in the 2nd column which belong the same group and do the same for the numbers in the 3rd column. for instance for the small example we have 2 groups the expected output would be: expected output: CHTOP 365 297 RPS27 2958 343 I used pandas in python but it does not return 3 columns file. import pandas as pd df = pd.read_csv('myfile.txt',sep=None) df = df.groupby(['ID']).cumcount() df.to_csv('result.txt', sep='\t', index=None) do you know how to fix it? A: Several observations: Since there is no header row in myfile.txt, we need to tell it to pandas, otherwise the first row will be treated as the header. Since the columns are unnamed, there is no such thing as the 'ID' column. To group rows by the ID, use the number of the column (0) instead. To sum the rows belonging to the same group, use sum(), not cumcount(). Also, it is better to explicitly state that myfile.txt is tab (not comma) separated because the C engine is unable to detect the separator automatically. Here is a proposed solution: import pandas as pd df = pd.read_csv('myfile.txt', sep='\t', header=None) df = df.groupby(0).sum() df.to_csv('result.txt', sep='\t', header=None)
[ "math.stackexchange", "0002314776.txt" ]
Q: Finding the minimizing diagonal matrix I try to minimise the following function, where $W$ is restricted to be a diagonal matrix: $$\dfrac{T}{2} \mathrm{log} |W^{-1}| - \dfrac{1}{2} \sum\limits_{t=1}^T (y_t - F'x)'W^{-1}(y_t-F'x)$$ I tried differentiating and made use of the fact that $X^{-1} = I/X$ and $$|X| = \sum\limits_{i=1}^k x_i$$ when $X$ is a diagonal matrix. However, I could not find a closed-form solution. Could anyone help me find a $W$ that minimises the given objective function? Many thanks. A: Since $W$ is a diagonal matrix we can do the following simplification: $$ \log(\det(W^{-1}))=\log(\prod_i w_i^{-1}) = -(\sum_i\log(w_i)) $$ Differentiating this with respect to $w_i$, yields $$ \frac{\partial(-(\sum_i\log(w_i)))}{\partial w_i}=-1/w_i $$ Let $a_t=(y_t-F^Hx)$, yielding $-1/2\sum_{t=1}^Ta_t^HW^{-1}a_t=-1/2\sum_{t=1}^T\sum_{i} \frac{a_t(i)^Ha_t(i)}{w_i}$ as the second term in the cost function (where $a_t(i)$ denotes the $i$:th index). Differentiating this with respect to w_i results in $$ \frac{\partial(-1/2\sum_{t=1}^T\sum_{i} \frac{a_t(i)^Ha_t(i)}{w_i})}{\partial w_i}= \frac{1}{2w_i^2}\sum_{t=1}^Ta_t(i)^Ha_t(i) $$ Thus, $$ -\frac{T}{2}1/w_i+\frac{1}{2w_i^2}\sum_{t=1}^Ta_t(i)^Ha_t(i)=0 $$ which has the solution $$ w_i = \frac{1}{T}\sum_{t=1}^Ta_t(i)^Ha_t(i) $$ EDIT: However, this is actually not a minimum, since the second derivative is negative for each $w_i$. Thus we can conclude that we found a maximum. The minimum can be found by, e.g., letting one of the $w_i$s tend to either $0$ or $\infty$, assuming that the other $w_i$s and $a_t$ are finite. Then we end up in $-\infty$. Sorry if my first answer was incomplete!
[ "computergraphics.stackexchange", "0000000138.txt" ]
Q: When should quaternions be used to represent rotation and scaling in 3D? Quaternions (a four-dimensional extension of complex numbers) can used to represent rotation and scaling of a 3D vector, and the application of a quaternion onto a 3D vector involves two quaternion multiplications, thus requiring fewer operations than multiplication by the corresponding transformation matrix. However, linear and affine transformation matrixes are often used instead, especially in shader code. When is it appropriate and preferable (due to speed, stability, etc.) to use a quaternion to represent scaling and rotation in three dimensions, instead of the corresponding transformation matrix? A: I want to start with misconceptions: Modern GPUs (NVIDIA for quite a while, and AMD since Southern Islands) do not meaningfully support vector/matrix operations natively in hardware. They are vector architectures in a different direction: each component of a vector (x, y, z) are generally 32- or 64-valued, containing values for each element in a lane. So a 3D dot product is not usually an instruction, it is a multiply and two multiply-adds. Additionally, counting primitive operations like multiply-add, transforming a vector by a quaternion is more expensive than transforming a vector by a matrix. Transforming a vector by a 3x3 matrix is 3 multiplies and 6 multiply-adds, and transforming a vector by a quaternion is two quaternion multiplies, each of which consist of 4 multiplies and 12 multiply-adds. (You can get less naïve than this—here's a writeup on a faster way—but it's still not as cheap as multiplying a vector by a matrix.) However, performance is not always determined simply by counting the number of ALU operations it performs. Quaternions require less space than the equivalent matrix (assuming you are only doing pure rotation/scale), and that means less storage space and less memory traffic. This is often important in animation (which is conveniently also often where the nice interpolation properties of quaternions show up). Other than that: Matrices use more space because they support more operations. A 3x3 matrix can contain nonuniform scale, skew, reflection, and orthogonal projection. Matrices can be naturally thought of as basis vectors, and easily constructed from those vectors. Multiplying one quaternion by another (composing two rotations) is less operations than multiplying one matrix by another. A: (A lot of information here I shamelessly borrowed from joojaa's and ratchet freak's answers, with some notes of my own.) Matrix Advantages Non uniform scaling and rotation, skewing, projection Translation (unless using dual quaternions) Native hardware support Quaternions often require transcendental functions to construct Easier to understand Quaternion Advantages Transforming a vector requires fewer operations (Or not - See John's answer) Transforming by another quat requires many fewer operations Quaternions occupy 4 floats, (8 if it's a dual) but Matrices occupy 9-16 floats If you know you're only going to be doing uniform rigid body transforms, a vector/quat pair is usually a solid win on a 3x4 matrix in terms of storage space (vector/quat: 7 or 8 floats vs mat3x4: 12 floats) and processing speed. If Quaternions are still mystical voodoo to you, try this web series on them. A: Matrices offer more possible transforms than quaternions, it is possible to skew, mirror and non uniformly scale the matrix. There is nothing that states you can not make your engine do just quaternion based transforms, if you have no need for the additional transform features. Matrices are just very convenient when you need to build spaces where you know the basis vectors. Such as when doing projections into orthographic. Also doing perspective transform in a matrix space is easy. Matrices are superior when it comes to projecting stuff. In a way matrices are usually used because they represent the most common denomination and aren't too complicated to master and understand. The benefits of standardization far outweighs the benefit you get form a custom workflow. Its well known how to do the matrix operations. Whereas quats are not something most get immediate introduction to in uni. Just ask around how many know how to invert a quaternion, whereas you dont find many students in higher education who dont know how to invert a matrix. Note that graphics cards also have dedicated pipes for matrix operations.
[ "stackoverflow", "0007383082.txt" ]
Q: javascript (jquery) not adding class if(hash=="ref=projects") { $("a#pj-title").addClass("selected-part"); $.ajax({url:"/project.html", dataType:"html", beforeSend:function(){ $(".loading").prepend('<div class="attention"><img src="ajax-loader.gif" /></div>') }, success:function(a) { $("#rv-container").html(a) } }) } Why doesn't the addClass method work? It doesn't seem to work within the if statement. A: If hash is from window.location.hash, then it will include a leading # so your code would need to be: if (hash == "#ref-projects") Also, $("a#pj-title") may be faster if it's $("#pj-title") since that lets jQuery use document.getElementById() as a shortcut and since there's only one object with a given ID anyway, you shouldn't need the a on the front anyway.
[ "stackoverflow", "0027779199.txt" ]
Q: Return from the function wasn't assigned to the $scope? Here is my controller: $scope.mainModel = getReviews({model:mainModelArr[1]}); $scope.compareModel = getReviews({model:compareModelArr[1]}); function getReviews(data) { $http.post(url, data) .success(function(res) { formatReviews(res) }) .error(function(err) { console.log("Something went wrong: "+err); }); } function formatReviews(data) { var review = data[0]; review.sumReviews = (review.sumReviews/review.ratingAvg).toFixed(0); review.sumRecommend = (review.sumRecommend/review.sumReviews*100).toFixed(1); review.ratingAvg = (review.ratingAvg).toFixed(1); console.log(review); // logs message fine return review; } These functions work fine, logs review var., but somehow it didn't assign review variable neither to $scope.mainModel nor to $scope.compareModel. NOTE: I know that it wasn't assigned, because it's never showed up in HTML: <p>{{mainModel}}</p> What did I do wrong and how can I fix that? A: Ajax requests works Async, angularjs use promises to handle this requests $scope.mainModel = undefined; $scope.compareModel = undefined; getReviews({model:mainModelArr[1]}).success(function(res){ $scope.mainModel = formatReviews(res); }); getReviews({model:compareModelArr[1]}).success(function(res){ $scope.compareModel = formatReviews(res); }); If you return post request, you can handle it anywhere, where you call getReviews method function getReviews(data) { return $http.post(url, data) .error(function(err) { console.log("Something went wrong:", err); }); } function formatReviews(data) { var review = data[0]; review.sumReviews = (review.sumReviews / review.ratingAvg).toFixed(0); review.sumRecommend = (review.sumRecommend / review.sumReviews * 100).toFixed(1); review.ratingAvg = (review.ratingAvg).toFixed(1); console.log(review); // logs message fine return review; }
[ "stackoverflow", "0005248278.txt" ]
Q: MySQL sum() on different group bys Ok, I have a query over two tables. I need to get two sums. I do a group by so the sum() works correctly. SELECT sum(a.x), sum(b.y) FROM a,b GROUP BY a.n where a.n=b.m So far this works well, but the problem is i need to group them differently for the second sum (sum(b.y)), than for the first sum (sum(a.x)). The real query is somewhat more complex but this is my main problem. This is what i actually try to select sum(stock.amount) - if( sold.amount IS NULL , 0, sum( sold.amount ) ) How can I solve that in one query? A: since you are not writing down the tables I am gonna make a wild guess and assume the tables are like : stock : id, item_id, amount sold : id, item_id, amount then again I assume that you need the stock_in_total, sold_total, left_total counts SELECT stock_sums.item_id, stock_sums.st_sum as stock_in_total, COALESCE(sold_sums.so_sum,0) as sold_total, (stock_sums.st_sum - COALESCE(sold_sums.so_sum,0)) as left_total FROM ( SELECT stock.item_id as item_id, SUM(stock.amount) as st_sum FROM stock GROUP BY item_id ) as stock_sums LEFT JOIN ( SELECT sold.item_id as item_id, SUM(sold.amount) as so_sum FROM sold GROUP by item_id ) as sold_sums ON stock_sums.item_id = sold_sums.item_id I hope this would help.
[ "monero.stackexchange", "0000007828.txt" ]
Q: Why does Monero use a 256 bit seed? Apparently, ECC 256 bit keys have a bit strength of 128 bits. See https://crypto.stackexchange.com/questions/26791/how-many-bits-of-entropy-does-an-elliptic-curve-key-of-length-n-provide And apparently, no one needs more than 128 bits of entropy https://security.stackexchange.com/questions/102157/do-you-need-more-then-128bit-entropy So if I'm correct in saying that it's pointless for the private spend key to be derived from a seed with more than 128 bits of entropy, and given that it is currently the case that the private view key is derived from a hash of the private spend key, why does Monero use a 256 bit seed? Perhaps the 'multi-target attack' mentioned here is relevant? https://crypto.stackexchange.com/questions/39991/can-i-use-128-bits-of-entropy-and-a-kdf-to-make-a-256-bit-ecc-key Update: Multi-target attacks do not appear to be an issue. See https://crypto.stackexchange.com/questions/56541/is-it-safe-to-generate-two-256-bit-ecc-keys-from-128-bits-of-entropy Update 2: It looks like BIP32 actually recommends that 256 bits of entropy are used to generate a Bitcoin wallet. See https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki#Master_key_generation This means that the 13 word, 128 bit seeds used in many Bitcoin wallets actually go against the recommendation in BIP32. Therefore Monero is actually following the recommendations of BIP32 by using 256 bits of entropy via a 25 word seed. Perhaps the real question should therefore be: Why do Bitcoin HD wallets use only 128 bit seeds, and ignore the BIP32 recommendation? I've asked that question here: https://bitcoin.stackexchange.com/questions/72612/bip32-recommends-a-256-bit-seed-why-do-most-bitcoin-wallets-only-use-a-128-bit A: BIP32 recommends that 256 bits of entropy are used to generate a Bitcoin wallet. See https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki#Master_key_generation This means that the 13 word, 128 bit seeds used in many Bitcoin wallets actually go against the recommendation in BIP32. Monero is following the recommendations of BIP32 by using 256 bits of entropy via a 25 word seed. I asked the author of BIP32, Pieter Wuille, why 256 bits were recommended instead of 128. He responded in the comments here: https://bitcoin.stackexchange.com/questions/72612/bip32-recommends-a-256-bit-seed-why-do-most-bitcoin-wallets-only-use-a-128-bit He said: Well, being able to break an EC key with just 2^128 steps is somewhat theoretical. In practice, these algorithms have significant memory/cpu tradeoffs, and in practice would still be much slower than a straight 2^128 exhaustive search on keys with just 128 bits of entropy. I guess the answer is defense in depth: less than 128 bits of entropy definitely hurts security. Less than 256 bits may hurt. We therefore have an answer. 256 bits gives us defense in depth, because fewer than 128 bits of entropy may hurt security.
[ "math.stackexchange", "0000876749.txt" ]
Q: CAT(0) space is geodesic Proving that being CAT(0) implies being geodesic, my professor used the following fact: If for every pair of points $x$ and $y$ in a complete metric space $X$ there exists a point $m \in X$ such that $d(x,m) = d(y,m) = d(x,y)/2$, then $X$ is a geodesic space. I don't get how to use that m in creating the geodesic Moreover, if such $m$ is unique, does it imply that the space is uniquely geodesic? I.e., does being CAT(0) implies being uniquely geodesic? Thanks for your help! A: If you are studying CAT(0) spaces, or geometry of metric spaces generally, the book A Course in Metric Geometry by Burago, Burago, and Ivanov should (ideally) always be in your vicinity. The statement is Theorem 2.4.16 there. Here is the proof. Given $a,b$ at distance $L=d(a,b)$, we want an isometry $\gamma:[0,L]\to X$ such that $\gamma(0)=a$ and $\gamma(b)$. Note that we already have defined $\gamma$ on the subset $[0,L]$. Expand the definition iteratively: $\gamma(L/2)$ is a midpoint between $\gamma(0)$ and $\gamma(L)$, and so forth. Observe that $\gamma$ is an isometry from its domain into $X$. (Use the triangle inequality). So far we have $\gamma$ defined at all numbers of the form $kL/2^m$ with $m=0,1,2,\dots$ and $0\le k\le 2^m$. Extend to all of $[0,L]$ by Lipschitz continuity. The isometric property is preserved. So, we have a geodesic. Also, uniqueness of midpoints implies the uniqueness of geodesics. Indeed, if midpoints are unique, then any other geodesic $\tilde \gamma$ would have to agree with our $\gamma$ at the points $kL/2^m$, and since they are dense, we have $\tilde \gamma\equiv \gamma$.
[ "stackoverflow", "0040813027.txt" ]
Q: Google app engine and axios post request I have app engine web service deployed. I have suddenly found, once clicked service name (default) link in services section of app engine, it redirects me from https://myapp-api.appspot.com/ to https://version-1-dot-myapp-api.appspot-preview.com/. Having client application using axios node js lib (running on http), i found it giving errors trying to do POST request from client (http) to myapp (https). My app does support accepting ajax calls setting Allow-Control-Allow-Origin header. GET requests work fine. POST request gives: UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 8): Error: Request failed with status code 400 If i replace API url from the original one to https://version-1-dot-myapp-api.appspot-preview.com/, it works. Any idea why? What am i doing wrong? Should i permanently replace URL to preview one? Why POST request for short URL throws an exception? A: Have this confirmed by Google support. Preview are the url`s of services running in a new - flex environment.
[ "stackoverflow", "0059125640.txt" ]
Q: How do I async on_status from tweepy? The error I'm getting is: RuntimeWarning: coroutine 'StdOutListener.on_status' was never awaited if self.on_status(status) is False: RuntimeWarning: Enable tracemalloc to get the object allocation traceback My stdOutListener looks like this: class StdOutListener(StreamListener): async def on_status(self, status): channel = await bot.get_channel(64970710814) await channel.send(status.text) I understand that I need to get on_status called async'd, but how do I do this? I've tried awaiting most of the things inside on_status A: Tweepy doesn't yet have asyncio support. For that, see https://github.com/tweepy/tweepy/issues/732. Instead, you can use the is_async parameter to run the stream in a separate thread. See https://tweepy.readthedocs.io/en/latest/streaming_how_to.html#async-streaming.
[ "stackoverflow", "0006400778.txt" ]
Q: How to convert mixed ascii and unicode to a string in javascript? I have a mixed source of unicode and ascii characters, for example: var source = "\u5c07\u63a2\u8a0e HTML5 \u53ca\u5176\u4ed6"; How do I convert it to a string by leveraging and extending the below uniCodeToString function written by myself in Javascript? This function can convert pure unicode to string. function uniCodeToString(source){ //for example, source = "\u5c07\u63a2\u8a0e" var escapedSource = escape(source); var codeArray = escapedSource.split("%u"); var str = ""; for(var i=1; i<codeArray.length; i++){ str += String.fromCharCode("0x"+codeArray[i]); } return str; } A: Use encodeURIComponent, escape was never meant for unicode. var source = "\u5c07\u63a2\u8a0e HTML5 \u53ca\u5176\u4ed6"; var enc=encodeURIComponent(source) //returned value: (String) %E5%B0%87%E6%8E%A2%E8%A8%8E%20HTML5%20%E5%8F%8A%E5%85%B6%E4%BB%96 decodeURIComponent(enc) //returned value: (String) 將探討 HTML5 及其他
[ "math.stackexchange", "0000342236.txt" ]
Q: why this is correct: $\det(C+Di)$ is not zero, then there exists some real number $a$ such that $\det(C + a D)$ is not zero I wonder why the following statement is correct: supposing $C$ and $D$ are two real matrix, if the determinant of the complex matrix $C + D i $ is not zero, then there exists some real number $a$ such that $\det(C + a D)$ is not zero? (where $i$ is the complex unit) Thanks a lot. A: Consider the complex polynomial $p(t)=\det(C+tD)$. If it vanishes on $\mathbb{R}$, then it has infinitely many roots, so it is constant equal to $0$. In particular $p(i)=0$. Note: there is no particular reason to assume $C,D$ to be real. They could be complex. But they need to be square, and of the same size. Application: I suspect this is why you asked the question. If two real square matrices $A,B$ are similar in $M_n(\mathbb{C})$, then they are similar in $M_n(\mathbb{R})$. Indeed, the assumption gives us $C,D$ in $M_n(\mathbb{R})$ such that $P=C+iD$ is invertible in $M_n(\mathbb{C})$ and $PA=BP$. This yields $CA=BC$, $DA=BD$, and $\det(C+iD)\neq 0$. By the above argument, there exists $t\in\mathbb{R}$ such that $Q=C+tD$ is invertible. And then $QA=BQ$ is the desired similarity in $M_n(\mathbb{R})$.
[ "stackoverflow", "0027245017.txt" ]
Q: LSH implementation for finding clusters Hie guys. I am very new to stack exchange and I am currently doing a research on graph theory. The set of questions I'm going to ask are very introductory since I'm a beginner level programmer (not acquainted with hashing, buckets, vectors etc data structure wise). My idea is to take in a dataset of the form (timestamp t, node i, node j) which says that there is an edge between i and j at time t. The idea is to search the neighborhood set of each nodes and hash them. If their "vectors" (I don't understand what that is) hash into the same bucket - they are candidates for cluster formation. But he problem is I want to do experiments and try to run it. But have no idea how do I implement a hash function, and then bucket them together. I'm not saying help me out with the code. But a pointer (pseudo code) would be very helpful. Like telling me to initialize a hash table etc etc A: A hash code is an integer which is calculated from the properties of whatever it is you want to hash. That number is then used as an index into an array. In this case it seems that you want to use the N dimensions of your vector to calculate this hash code. It's up to you to write a function that calculates that hash codes in a way that vectors that should be clustered all get the same hash code. Language specific details about hash tables in Java or Python is very easy to find with a web search.
[ "stackoverflow", "0015179311.txt" ]
Q: Apply a stylesheet for both print and screen How can I set a CSS file for print & screen? I tried to set both values on the tag (like for a class attribute) but it doesn't work: <link href="style.css" rel="stylesheet" media="screen print"> The question goes also for CSS in body. A: You need a comma: <link href="style.css" rel="stylesheet" media="screen, print"> The question goes also for CSS in body. If you're referring to the style attribute, this cannot be done because you can't embed media queries in inline styles.
[ "math.stackexchange", "0002984465.txt" ]
Q: Proving a series is convergent - $\sum _{n=1} ^\infty \frac{(-1)^n}{n}$ without using alternating series test $$\sum _{k=1} ^\infty \frac{(-1)^k}{k}$$ I know this question has been answered a few times but my professor has not taught alternating series test yet or anything other than ratio test, root test and comparison test where $a_i \geq 0$ for every $i \in \mathbb N$ and $\sum_{i=1} ^\infty a_i$ converges and if $|b_i| \leq a_i$ for every i then $\sum_{i=1} ^\infty b_i$ converges absolutely. So here's my attempt using Cauchy criterion. What we know: We say that the series $\sum _{i=1}^\infty a_i$ converges if the sequence of partial sums $(S_i)_i$$_\in$$_\mathbb N$ converges. From Cauchy criterion, $(S_i)_i$$_\in$$_\mathbb N$ converges if and only if it is a Cauchy sequence. It is quite obvious that $$\lim_{k\to\infty} S_k = \sum _{k=1}^\infty \frac{(-1)^k}{k}$$. I denote $\lim_{k\to\infty} S_k = S$ Suppose ($S_k$) is convergent. Then $\forall \epsilon \gt 0, \exists N \in \mathbb N$ such that $\forall n \geq N,$ $|S_n - S|$ = $\vert \sum_{k=n+1} ^\infty \vert$ $\lt \epsilon$ I am stuck here. Is it possible to find such N for all $\epsilon \gt 0$ to hold $\vert \sum_{k=n+1} ^\infty \vert$ $\lt \epsilon$ to be true? (If yes, then the sequence ($S_k$) is convergent so $\sum_{k=1} ^\infty \frac{(-1)^k}{k}$ is convergent by the definition but I don't quite understand if we can always find such N) edit: I don't think ratio test or root test are applicable to solve this and is the alternating series test the only way to solve this problem? A: Hint. Let $$ s_n=\sum_{k=1}^n\frac{(-1)^k}{k} $$ Then observe that $$ s_1<s_3<\cdots<s_{2n-1}<s_{2n+1}<s_{2n+2}<s_{2n}<s_{2n-2}<\cdots<s_4<s_2 $$ Hence $a_n=s_{2n-1}$ is increasing and upper bounded, by $s_2$, while $b_n=s_{2n}$ is decreasing and lower bounded by $s_1$. Hence both converge, and since $a_n<b_n$, then $$ \lim a_n\le \lim b_n $$ But $b_n-a_n=\frac{1}{2n}\to 0$, and hence $$ \lim a_n= \lim b_n $$ Note. Inevitably, the idea of the proof of Alternating series test is used in the above proof.
[ "stackoverflow", "0016693769.txt" ]
Q: Encoding german characters I need to import with load data some perl - generated files to oracle database. Perl-script get a webpage and write csv file. Here a simplified script: use File::Slurp; my $c= ( $user && $passwd ) ? get("$protocol://$user:$passwd\@$url") : get("$protocol://$url"); write_file("$VZ_GET/$FileTS.$typ.csv",$c); Here a sample line from the webpage: 5052;97;Jan;Ihrfelt 5053;97;Jari;Honko 5121;97;Katja;Keitaanniemi 5302;97;Ola;Södermark 5421;97;Sven;Sköld 5609;97;Peter;Näslund Content of the webpage is saved in var $c. Here a sample line of csv file: 5053;97;Jari;Honko Here a load command: LOAD DATA INTO TABLE LIQA TRUNCATE FIELDS TERMINATED BY ";" ( LIQA_ANALYST_ID, LIQA_FIRM_ID, LIQA_ANALYST_FIRST_NAME, LIQA_ANALYST_LAST_NAME, LIQA_TS_INSERT DATE 'YYYYMMDDHH24MISS' ) Command SELECT * FROM NLS_DATABASE_PARAMETERS WHERE PARAMETER = 'NLS_CHARACTERSET'; returns AL32UTF8. The generated csv file is recognized as UTF-8 Unicode text. Anyhow I cant import german characters. In the csv file they are still correct. But it is not the case in the database. I have also tried to convert $c like this: $c = encode("iso-8859-1", $c); The generated csv file is stll recognized as UTF-8 Unicode text. I have no clue how can I fix it. A: I have solved it: $c = decode( 'utf-8', $c ); $c = encode( 'iso-8859-1' , $c );
[ "stackoverflow", "0028916093.txt" ]
Q: Count occurrences of repeating elements in a vector> I have a vector<vector<Rect>>. Rect is a openCV rectangle object. I want to fill up a empty vector<pair<Rect,int>> with all the rectangles that are repeating (1 or more occurrences) in the vector and the number of found occurrences. My implementation below is not giving me the expected result. Here is what I tried: vector<vector<Rect>> vec; //...fill up vector vec... vector<pair<Rect,int>> constantsVec; bool found=false; for(int j=0;j<vec.size()-1;j++){ vector<Rect> temp1=vec[j]; vector<Rect> temp2=vec[j+1]; for(int x=0;x<temp1.size();x++){ for(int y=0;y<temp2.size();y++){ if(temp1[x]==temp2[y]){ for(int k=0;k<constantsVec.size();k++){ if(constantsVec[k].first==temp1[x]){ found=true; constantsVec[k]=make_pair(temp1[x],++constantsVec[k].second); } } if(!found){ constantsVec.push_back(make_pair(temp1[x],0)); } } } } } In an example with a rectangle that is repeating three times I end up with the correct rectangle in the constantsVec but with 1 as the number of found occurrences instead of 3. I should add that one element (vector<Rect>) of the vec vector itself has no repeating rectangles but between the elements of the vec vector there can be repeating rectangles. Those are the ones I am trying to find and count. A: An efficient and possibly the simplest way to do that in O(n · log n) is to use a map. First create a Rect comparator to allow indexation by Rect (put it somewhere accessible): // Needed for O(n · log n) complexity struct RectComparator { bool operator () (const Rect & a,const Rect & b) { if (a.x != b.x) return a.x < b.x; if (a.y != b.y) return a.y < b.y; if (a.width != b.width) return a.width < b.width; return a.height < b.height; } }; To count how many Rect r you have in vec here's the code: vector<vector<Rect> > vec; //...fill up vector vec... map<Rect, int, RectComparator> counts; for (int i = 0; i < vec.size(); i++) { for (int j = 0; j < vec[i].size(); j++) { counts[vec[i][j]]++; } } I didn't check if vec[i][j] exists on counts as if it does not, it's initialized to zero by default. At the end, counts[r] will have the amount of Rect r in vec. The complexity is O(n · log n) with n the amount of Rect in vec vs. O(n^2) (yours). To iterate over the counts map here's the code (adapted to build the constantsVec if you need it, with Rects that appear more than once): vector<pair<Rect, int> > constantsVec; map<Rect, int>::iterator iter; for (iter = counts.begin(); iter != counts.end(); ++iter) { // iter->first is the Rect // iter->second is the count of the Rect iter->first in vec if (iter->second > 1) constantsVec.push_back(make_pair(iter->first, iter->second)); } Take into account that it makes sense to build and use constantsVec only if you will use it many times and at the same time the difference between rectangles that appear once and those that appear more than once is significantly big. In other case, using the counts map should be as good as using the constantsVec.
[ "stackoverflow", "0032140478.txt" ]
Q: Error when Parsing last position value from text file while streaming data in Julia I am streaming strings and parsing them into floats/ints from a .dat. Everything is going well until I work with the last item in the string, which returns an error. Example Data: x = "15505052|B|Other|2.22|250022|2776|09/2019|01/2004|" y = split(x, "|") # <-- one inner loop of the loop if isblank(y[9]) == false floater = parse(Float64, y[9]) end This is the error I receive: ArgumentError("float64(String): invalid number format") while loading In[42], in expression starting on line 56 in float64 at string.jl:1613 in parse at /Users/laptop/.julia/v0.3/Compat/src/Compat.jl:217 in loan_aqsn at In[42]:36 I have visually inspected the last column in the above data strings and determined that the data should be parseable into a Float64, and indeed every other column works just fine. What I have found is that I can individually parse lines from the .dat just fine (for testing purposes), but when I move to streaming the file Julia throws the error. The only thing I can figure out about this error is that it has to due with working with the final record in the string y[9], which makes no sense to me. Any help with this frustrating problem is much appreciated. A: You're testing whether y is blank, when it is in fact an empty string: x = "15505052|B|Other|2.22|250022|2776|09/2019|01/2004|" y = split(x) y[9] # "" isblank(y[9]) # false, since we have an empty string float(y[9]) # ERROR: ArgumentError("float64(String): invalid number format") You should modify your code to use isempty() instead using Compat # for parse(Float, String) if !isempty(y[9]) floater = parse(Float64, y[9]) end # do stuff Relevant manual section (for v0.3)
[ "math.stackexchange", "0000334597.txt" ]
Q: degree of a field extension Let $\alpha$ be a root of $x^3+3x-1$ and $\beta$ be a root of $x^3-x+2$. What is the degree of $\mathbb{Q}(\alpha^2+\beta)$ over $\mathbb{Q}$? My guess is 9, because i found a monic polynomial of degree 9 with integer coefficient, irreducible in $\mathbb{Q}[x]$ with $\alpha^2+\beta$ as a root. But i don't know if this suffices. Any help? A: If you are one of those people who have trouble proving that a nonic polynomial is irreducible, you can try the following sketch instead. This depends on a bit of algebraic number theory. Consider the prime ideal generated $p=2$. Because $x^3+3x-1$ is irreducible modulo $2$, this prime is inert in the field $K=\mathbb{Q}(\alpha)$. OTOH the polynomial $x^3+x-2$ factors modulo $2$ as $x(x+1)^2$. It is a bit tedious but straightforward to show that $1,\beta,\beta^2$ is an integral basis of $L=\mathbb{Q}(\beta)$. Therefore in its ring of integers two factors as $(2)={\frak{p}_1\frak{p}_2^2}$. In the compositum $F=LK=\mathbb{Q}(\alpha,\beta)$ all the prime ideals lying above two will have inertia degree at least three (because they lie above the inert prime of $K$), so the only possibility is that the prime ideals $\frak{p}_1,p_2$ are both totally inert in $F/L$, and we have $[F:L]=3$. Therefore $[F:\mathbb{Q}]=[F:L]\cdot [L:\mathbb{Q}]=9$ and $L$ and $K$ are linearly disjoint. The discriminants of the two cubic polynomials are $-135$ and $-104$ respectively. Neither of these is a square in the rationals, so the Galois groups of both of them are $S_3$. Furthermore, the discriminants are coprime, so even the splitting fields of the two cubics intersect trivially, and as Galois extensions are thus linearly disjoint. So if we let $M$ to be the splitting field of $(x^3+3x-1)(x^3+x-2)$, then we can identify the Galois group $$G=\operatorname{Gal}(M/\mathbb{Q})=\operatorname{Sym}(\{1,2,3\})\times \operatorname{Sym}(\{4,5,6\})\simeq S_3\times S_3\le S_6$$ as permutations on the six roots - each copy of $S_3$ acting on the roots of its factor and keeping the roots of the other factor fixed. If we let $\alpha$ and $\beta$ be the roots number 1 and 4 respectively, then $F$ will be the fixed field of $H=\langle (23)\rangle \times \langle (56)\rangle$. It is easy to convince yourself that the only subgroups of $G$ strictly between $H$ and $G$ are $\langle(23)\rangle\times \operatorname{Sym}(\{4,5,6\})$ and $\operatorname{Sym}(\{1,2,3\})\times\langle(56)\rangle$. Clearly the Galois correspondence takes these subgroups to $K$ and $L$ respectively. So $K$ and $L$ are the only non-rational proper subfields of $F$. By linear disjointness the element $\alpha^2+\beta$ does not belong to either, so it must generate all of $F$. There may be some holes in the argument (a sketch only), but I think that this approach works. It is probably also overkill in its use of algebraic number theory. I am more than willing to be educated about a cleaner approach. A: If you have found such a polynomial, then this suffices. The reason is that the degree $\lvert \mathbb{Q}(\alpha^2+\beta):\mathbb{Q} \rvert$ equals the degree of the minimal polynomial $f \in \Bbb{Q}[x]$ of $\alpha^{2} + \beta$ over $\Bbb{Q}$. Now you have found a monic polynomial $g$ of degree $9$ in $\Bbb{Z}[x] \subseteq \Bbb{Q}[x]$ which is irreducible in $\Bbb{Q}[x]$ and has $\alpha^{2} + \beta$ as a root. Now the minimal polynomial $f$ must be a non-constant, monic divisor of $g$. Since $g$ is irreducible in $\Bbb{Q}[x]$, we obtain $f = g$.
[ "stackoverflow", "0005314589.txt" ]
Q: Delphi IDE locks because of a hidden modal window Has someone else experienced something like this with Delphi and if so is there a known workaround! I'm using the Delphi 2010 Rad Studio on Windows 7 64 bit. A few times when editing the IDE hangs and I can't do any action either by keyboard or mouse. But there is a error-beep sound from windows like there is a modal window open somewhere, but hidden behind the ide it self. Only by ending the ide via Task manager can I make this hidden modal window visible. A: I see this often with various other dialogs as well. Pressing "Alt-Tab" and reselecting Delphi you will cause the dialog to appear in the front again. Note: This happens with other versions of Delphi as well. A: I have the same problem with older versions of Delphi like D6. My solution is use another tool like WinExp –Windows Explorer– or WinResQ to explore the existing active windows on system and reactivate it (BringToTop). With this solution I get the Delphi IDE on Top and appears the window that cause the lock. This is the only option I have worked for me. Regards.
[ "stackoverflow", "0008694902.txt" ]
Q: How to map DTO from EF to Model I have the following model Person in my UI MVC layer: public class Person { [Required] public string FirstName { get; set; } [Required] public string LastName { get; set; } public int PersonTypeID { get; set; } [Required] public string Phone { get; set; } [Required] public string Email { get; set; } } In my data layer, I have a class with the same property names, but different meta (naturally): public partial class Person : EntityObject { ... } How can I return data from my data layer into my MVC UI layer without having the data layer know about the MVC UI layer? Note: I also have a simple IPerson interface with the same property names as well. A: You could use AutoMapper to map between the domain model and the view model. It is the MVC layer that knows about the data layer, but the data layer doesn't need to know about the MVC layer. Here's a common pattern: public ActionResult Foo() { var person = _repository.GetPerson(); var personViewModel = Mapper.Map<Person, PersonViewModel>(person); return View(personViewModel); } and the other way around: [HttpPost] public ActionResult Foo(PersonViewModel personViewModel) { if (!ModelState.IsValid) { return View(model); } var person = Mapper.Map<PersonViewModel, Person>(personViewModel); _repository.UpdatePerson(person); return RedirectToAction("Success"); } As you can see the data layer doesn't need to know anything about the MVC layer. It's the MVC layer that needs to know about the data layer.
[ "math.stackexchange", "0003383529.txt" ]
Q: integral expression involving $\Xi(t)$ I'm trying to prove that $$ \int_{0}^{\infty}\frac{\Xi(t)}{t^2+\frac{1}{4}}\cos(xt)dt=\frac{\pi}{2}\Big(e^{x/2}-2e^{-x/2}\psi(e^{-2x})\Big), $$ where $\Xi(t)=\xi(1/2+it)$ and $\psi(x)=\sum_{n=1}^{\infty}e^{-n^2\pi x}$. For this purpose I'm following the book "The Theory of the Riemann Zeta-function" by Titchmarsh and I got stuck in the following equality: $$ \frac{-1}{4\sqrt{y}i}\int_{\frac{1}{2}-i\infty}^{\frac{1}{2}+i\infty}\Gamma\Big(\frac{s}{2}\Big)\pi^{-s/2}\zeta(s)y^sds=-\frac{\pi}{\sqrt y}\psi\Big(\frac{1}{y^2}\Big)+\frac{\pi}{2}\sqrt y. $$ My attempt: By Mellin inversion we know that $$ \psi(x)=\frac{1}{2\pi i}\int_{\sigma-i\infty}^{\sigma+i\infty}\pi^{-s}\Gamma(s)\zeta(2s)x^{-s}ds \quad\quad (\sigma\gt 1/2). $$ Now to prove the equality, let $u=s/2$ so that $$ \frac{-1}{4\sqrt{y}i}\int_{\frac{1}{2}-i\infty}^{\frac{1}{2}+i\infty}\Gamma\Big(\frac{s}{2}\Big)\pi^{-s/2}\zeta(s)y^sds=\frac{-1}{2\sqrt{y}i}\int_{\frac{1}{4}-i\infty}^{\frac{1}{4}+i\infty}\Gamma(u)\pi^{-u}\zeta(2u)y^udu, $$ and then try to use Mellin inversion to obtain the desired the result. The problem is that I don't know how to change the interval of integration from $1/4-i\infty$ to $1/4+i\infty$, to something of the form $\sigma-i\infty$ to $\sigma + i\infty$ for some $\sigma\gt 1/2$. Also, if I apply Mellin inversion directly I only get the factor $-\frac{\pi}{\sqrt y}\psi(y^{-2})$, so I don't know where the factor $\frac{\pi}{2}\sqrt y$ comes from. A: The idea is to move the line of integration from $1/2-i\infty\to 1/2+i\infty$ to $2-i\infty\to 2+i\infty$ passing through the pole of $\zeta(s)$ at $s=1$. Considering the rectangular contour with vertices at $1/2-iR, 1/2+iR, 2-iR , 2-iR$ and letting $R\to\infty$, by the Residue Theorem it follows that $$ -\frac{1}{4 i \sqrt{y}} \int_{\frac{1}{2} - i\infty}^{\frac{1}{2} + i\infty} \Gamma(\frac{1}{2}s) \pi^{-\frac{1}{2}s} \zeta(s) y^s ds=-\frac{1}{4 i \sqrt{y}} \int_{2 - i\infty}^{2 + i\infty} \Gamma(\frac{1}{2}s) \pi^{-\frac{1}{2}s} \zeta(s) y^s ds + \frac{\pi}{2} \sqrt{y}, $$ where the $\pi/2 \sqrt{y}$ is the residue of the integrand at $s=1$ (The integral along the horizontal lines vanishes). Now use Mellin inversion to recover $\psi$ from $\Gamma$ and $\zeta$, namely $$ \psi(x)=\frac{1}{2\pi i}\int_{c-i\infty}^{c+i\infty}\pi^{-s}\Gamma(s)\zeta(2s)x^{-s}ds \quad\quad(c\gt \frac{1}{2}). $$
[ "sharepoint.stackexchange", "0000209853.txt" ]
Q: How to Update a List's Content Type after Adding a New Column In this question I asked something very similar, but it was particularly for Sharepoint 2010. We've since migrated to Sharepoint Online and I have a similar problem but with a different scope. I need different answers, so I am asking a new question. Steps: Create a custom Content Type using custom Site Columns in the root of the Site Collection Next, in one of the subsites, create 5 lists that use your custom Content Type. (later on you will have 100 of these) Then your boss comes and asks you to rename a few columns, so you edit the Content Type and rename the columns. When you push changes to the lists this adds the new columns to your lists. But it also removes the old columns from the list's derived Content Type - so you go back into those lists and manually delete them. Now the boss comes and asks you to add two or three columns. So you edi the Content Type and add the columns, being sure to check to the box to "Push changes to all lists". Here is the problem: the new columns do not show up in the lists. How do I solve this? In the "Edit 2" section of this answer, there is a powershell script to "Update Content Type", although it is written for Sharepoint 2010 on-prem. What do I need to do here? How do I get the new columns to show in the lists? (besides rebuilding the lists - which I don't want to do if I have 100 of them). I don't need to update the content type because I've already added the columns in the Content Type via the UI. Also, that script seems to add fields; I just want the list to refresh it's idea of the Content Type. A: So, this is the answer I've come up with so far (please comment below if any of this is incorrect). The Site Content Type is basically used as just a template for the List Content Type when applied to the list. True, edits made to Site Columns will push to the lists, but fields added to the CT after the list was created do not seem to push to the lists. That means that you have to use powershell to actually add the fields (and you can update the other fields whilst you are at it). Here is the order of the script: Get the id of the CT that needs to be pushed Loop through CTs in the subsite and compare their id to the original Site CT's id If they match, then For each field in the parent CT, loop through all the fields in the child CT and update them or add them if they don't exist in the parent. See this article on the CT Ids. [alternate understanding] Here are some words given to me by a Sharepoint Architect: The trouble is that once you have a list content type you are stuck with a list content type. There is no way to revert it back to relying on the Site collection level content type because it made a copy and changes were applied to the copy. Removing the changes still leaves it as a copy. If you had created another content type that inherited from the first and put your additional columns in that and then used that in the list then new columns added to the original content type would show up in the inherited content type in the list. But as soon as you make changes at the list level it makes a copy of the content type and uses that in the future. From then on it ignores the original content type because the list is working off a copy.
[ "vi.stackexchange", "0000009271.txt" ]
Q: Output Vim display to Text I wonder if there is any command similar to :TOhtml, but for plain text only and representing the whole Vim display. For example, given the display: It would create the following text file: 1 B 1 a ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ N <me] [+] 100% 1:1 ~ 1 a ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ N <me] [+] 100% 1:1 N <e] [+] 100% 1:1 (this has been done via copy/paste from the terminal and manually formatting the text) I did not found any option to do so, I think there is none. How, if possible, can Vim achieve this? A: Yes, there is a way to do this! You can use the screenchar() function. From :help screenchar() screenchar(row, col) *screenchar()* The result is a Number, which is the character at position [row, col] on the screen. This works for every possible screen position, also status lines, window separators and the command line. The top left position is row one, column one The character excludes composing characters. For double-byte encodings it may only be the first byte. This is mainly to be used for testing. Returns -1 when row or col is out of range. To use this in a script, you can do the following: fu! ScreenCapture() let array=[] for i in range(1,&lines) let row='' for j in range(1,&columns) let row.=nr2char(screenchar(i,j)) endfor call add(array, row) endfor tabnew call setline(1,array) endfu com! ScreenCapture :call ScreenCapture() This lovely piece of vimscript was written by Christian Brabandt, so if you find it useful go give him an upvote. Here's an example of it in action. When I ran this function on my vim window: I got this text: 1 | 1 ~ |~ ~ |~ ~ |~ ~ |~ ~ |~ ~ |~ ~ |~ ~ |~ ~ |~ ~ |~ [No Name] 0,0-1 All|~ 1 |~ ~ |~ ~ |~ ~ |~ ~ |~ ~ |~ ~ |~ ~ |~ ~ |~ ~ |~ ~ |~ [No Name] 0,0-1 All [No Name] 0,0-1 All :call ScreenCapture()
[ "drupal.stackexchange", "0000056940.txt" ]
Q: ReferenceError: Drupal is not defined I am working on a production site, moving settings from a development site for a mobile environment. However, I am receiving the above error. I can not figure out what is causing this error. It does not matter what theme I change my jquery mobile environment too. I've checked all the modules and they seem to be the same versions. The only thing I can see that is different is in the development site I can uncheck/check the block cache, on the production environment I can not do this. A: Sounds like an issue with the ordering of the javascript files. Drupal is defined in /misc/Drupal.js var Drupal = Drupal || { 'settings': {}, 'behaviors': {}, 'locale': {} }; Check Drupal.js is added to your HTML source, prior to when that variable is requested.
[ "math.stackexchange", "0000891469.txt" ]
Q: Variant of the Halting Problem S = {$<A, B, k>$ : there are less than k natural numbers n for which A(x), B(x) both halt} I have the following proof that S is undecidable. Suppose D($<A, B, k>$) is a decider for S. Define the following: halts(P, i) { $\quad$define A(x) { $\quad \quad$P(i) $\quad \quad$if x in (1, 2) then return else loop $\quad$} $\quad$define B(x) { $\quad \quad$P(i) $\quad \quad$if x in (1, 2) then return else loop $\quad$} $\quad$ if $\;D(<A,B,3>)\;\;$accepts then $\quad \quad$ halts $\quad$ else $\quad \quad$ loops } If D exists then we would be able to decide if P halts on i. Since the Halting Problem is undecidable, D cannot exist and hence S is undecidable. I believe that the same argument can be used to show that S is unrecognizable with D being a recognizer instead of a decider. Am I correct? Or is there a better way to show that S is unrecognizable? A: If the $n$ and $x$ in your definition of $S$ are supposed to be the same, and if I'm interpreting your program correctly, then your halts(P,i) will halt if and only if $P(i)$ doesn't. So you seem to be building into your construction part of the proof of the undecidability of the halting problem. In my opinion, it would be simpler (and would provide a complete proof) to observe that one standard version of the halting problem is Turing reducible to $S$ (in fact, many-one reducible to the complement of $S$) as follows. A Turing machine $A$ (with no input, or, if you prefer, with a dummy input $x$) halts if and only if there are not less than $1$ numbers $x$ for which $A$ and $A$ both halt.
[ "stackoverflow", "0012063840.txt" ]
Q: What are the sizes of tword, oword and yword operands? What are the sizes of tword, oword and yword operands, as used in the NASM/YASM manual? And on a related note, is there a trick or underlying idea to these names? Is there a way by which bigger word sizes are given logical names? I know that while word sizes may differ between systems, a NASM word is 2 bytes, dword is double that (4 bytes), qword is a quad word (8 bytes), but... is tword a triple word (6 bytes)? And for oword and yword I can't even think of a plausible meaning. Note that it is probably an easy question, but I couldn't find an answer. In the NASM and YASM manuals these sizes are not explained, not even at the DQ, DT, DY, RESQ, REST, RESY pseudo-instructions. I read somewhere that MASM uses a similar system, but could not find anything on that either. Edit: Based on the answers, this is the complete list: 1 byte (8 bit): byte, DB, RESB 2 bytes (16 bit): word, DW, RESW 4 bytes (32 bit): dword, DD, RESD 8 bytes (64 bit): qword, DQ, RESQ 10 bytes (80 bit): tword, DT, REST 16 bytes (128 bit): oword, DO, RESO, DDQ, RESDQ 32 bytes (256 bit): yword, DY, RESY 64 bytes (512 bit): zword, DZ, RESZ A: Looking at the nasm source, it looks like: 'oword'/'DO' is 8 times as big as "word" (O for "octoword"), synonymous with dqword ("double-quad"); that would be 128 bits, corresponding to the size of an SSE vector register. 'tword'/'DT' is 80 bits (T for "ten bytes"), the full size of an Intel x87 floating point register. 'yword'/'DY' is 256 bits, and the Y is presumably mnemonic for the YMM names of the 256-bit vector registers in the Intel AVX extensions. 'zword'/'DZ' is 512 bits, Z for the ZMM names of the 512-bit vector registers in the Intel AVX-512 extensions. So, it's not exactly a logical naming convention; "it just growed". A: I have checked it with two approaches for NASM: source code and empirical. Source code Source at: http://repo.or.cz/w/nasm.git Then: git grep -C2 tword And we fall upon: switch (size) { case 1: return "byte"; case 2: return "word"; case 4: return "dword"; case 8: return "qword"; case 10: return "tword"; case 16: return "oword"; case 32: return "yword"; case 64: return "zword"; default: return "???"; } Empirical git log -p and git tag --contains tell me that zword was added in 2.11, and since I'm on 2.10 and lazy, I'll omit that one. On our .asm file: section .bss resb1 resb 1 resw1 resw 1 resq1 resq 1 rest1 rest 1 reso1 reso 1 resy1 resy 1 ; Just to read the objdump better. resb2 resb 1 Then compile and: objdump -D -j .bss main.o gives: 00000000 <resb1>: ... 00000001 <resw1>: ... 00000003 <resd1>: 3: 00 00 add %al,(%eax) ... 00000007 <resq1>: ... 0000000f <rest1>: ... 00000019 <reso1>: ... 00000029 <resy1>: ... 00000049 <resb2>: ... If we take the differences between each position, we reach the same conclusion as before. zword menemonic For the ZMM registers added by AVX-512: https://en.wikipedia.org/wiki/AVX-512 I wonder what Intel will do when the letters of the alphabet end.
[ "math.stackexchange", "0002482575.txt" ]
Q: Prove that $\frac1{2^i}\sum\limits_{j=0}^i|2j-i| \binom{i}{j} \leq d\sqrt{i}$ for some constant $d$ I'm trying to give a bound on the following formula: $$\frac1{2^i}\sum_{j=0}^i|2j-i| \binom{i}{j} \leq d\sqrt{i}$$ for some constant $d$. This is how far I get: $$=\dfrac{\sum^{i/2}_{j=0} \ \binom{i}{j} (i - 2j) + \sum^{i}_{j=(i/2)+1} \ \binom{i}{j} (2j - i)}{2^i}$$ $$\leq \dfrac{2\sum^{i/2}_{j=0} \ \binom{i}{j} (i - 2j)}{2^i}$$ If I take the sum from j=0 to i instead of i/2, then the sum would be 0. So, I should use another way of upper bounding this formula. A: I try to go on with your approach. \begin{align} \sum_{j=0}^i|2j-i| \binom{i}{j} &=2\sum_{j=0}^{\lfloor i/2\rfloor}(i-2j) \binom{i}{j}\\ &=2i\sum_{j=0}^{\lfloor i/2\rfloor}\binom{i}{j}-4\sum_{j=0}^{\lfloor i/2\rfloor}j\binom{i}{j}\\ &=2i\sum_{j=0}^{\lfloor i/2\rfloor}\binom{i}{j}-4i\sum_{j=1}^{\lfloor i/2\rfloor}\binom{i-1}{j-1}\\ &=2i\sum_{j=0}^{\lfloor i/2\rfloor}\binom{i}{j}-4i\sum_{j=0}^{\lfloor i/2\rfloor-1}\binom{i-1}{j}\\ &=2i\binom{i}{\lfloor i/2\rfloor}+2i\sum_{j=0}^{\lfloor i/2\rfloor-1}\underbrace{\left(\binom{i-1}{j-1}-\binom{i-1}{j}\right)}_{\leq 0}\\ &\leq 2i\binom{i}{\lfloor i/2\rfloor}. \end{align} Now show that the inequality holds for $d=2$ (I am aware that the one-line proof in Did's comment show that $d=1$ suffices). It remains to show that for $i\geq 1$, $$2i\binom{i}{\lfloor i/2\rfloor}\leq 2 \cdot 2^i\sqrt{i}\quad\text{or}\quad \binom{i}{\lfloor i/2\rfloor}\leq \frac{2^i}{\sqrt{i}}.$$ P.S. Take a look here: Elementary central binomial coefficient estimates
[ "stackoverflow", "0034117460.txt" ]
Q: What's the difference between PEX and DHT in the BitTorrent protocol? If I understand correctly, the purpose of both PEX and DHT is to find other peers in the swarm. So why are both needed? Thank you A: Look at the PEX BEP, I think the opening paragraph explains the differences well enough.
[ "meta.stackexchange", "0000086938.txt" ]
Q: Code formatting - tag/block rather than indentation - code block more obvious One feature of SO that pains me every single time is having to manually indent all code four spaces, and usually copy four spaces to the clipboard so Ctrl+V acts as 'Tab'. Maybe it's on purpose to stop walls of code, but I want to discuss it anyway because everything else seems to go so smoothly and this annoys me and slows me down every day. .... And I JUST found the 'code block' feature after many months (having looked through a similar question or two). I guess then can I rephrase as, 'Please make the CODE BLOCK editor feature/button more obvious' ? A: The code block tool if very obvious if you are looking for it. It is in the toolbar and equally sized as other tools. Making it stand out more than the other tools would make the UI look poor. The tool is mentioned in formatting guides and other questions as you have found. I would suggest not to make any changes to the tool. A: Wait, what? Just press ctrl+k to indent code (or unindent code..) or of course click the {} toolbar button.
[ "stackoverflow", "0062461973.txt" ]
Q: Finding float average of random list in python I have looked on several websites, books, and in the documentation and I can't figure out what I am doing wrong. I try to ask for help as a last resort, so that I can learn on my own, but I have spent far too long trying to figure this out, and I am sure it is something really simple that I am doing wrong, but I am learning. The code produces a single different result every time it is ran. The code produces the following error: 26.8 Traceback (most recent call last): File "main.py", line 7, in tot = sum(rand)/len(rand) TypeError: 'float' object is not iterable import random for x in range (10000): rand = random.uniform(10, 100) print(round(rand, 1)) tot = sum(rand)/len(rand) print (round(tot, 1)) A: You're not actually generating a list, you're generating individual values. Do you really want to print out 10000 values along the way to your final result? If the answer is "no!", then your code can be reduced to: import random N = 10000 print(round(sum(random.uniform(10, 100) for _ in range(N)) / N, 1)) or, if you prefer to break it out a little bit more for readability: import random N = 10000 total = sum(random.uniform(10, 100) for _ in range(N)) average = total / N print(round(average, 1)) If this is beyond the scope of what you've learned, you can create total outside the loop initialized to zero, update it with each new value as you iterate through the loop, and then calculate the final answer: import random N = 10000 total = 0.0 for _ in range(N): # use '_' instead of x, since x was unused in your prog total += random.uniform(10, 100) average = total / N print(round(average, 1)) This avoids wasting storage for a list of 10000 values and avoids the append() you're not yet familiar with. Of course, if you need the 10000 values later for some other purpose, you'll need to tuck them away in a list: import random N = 10000 l = [random.uniform(10, 100) for _ in range(N)] total = sum(l) print(round(total / N, 1)) Addendum Just for jollies, you can also do this recursively: import random def sum_of_rands(n): if n > 1: half_n = n // 2 return sum_of_rands(half_n) + sum_of_rands(n - half_n) elif n == 1: return random.uniform(10, 100) N = 10000 print(round(sum_of_rands(N) / N, 1)) print(sum_of_rands(0)) # returns None because nothing is being summed Splitting the problem in half (on average) in each recursive call keeps the stack to O(log N). I'd actually advise you to stick with list comprehension or looping, but wanted to show you there are lots of different ways to get to the same result.
[ "stackoverflow", "0044692366.txt" ]
Q: activeSelf return true and gameobject is false So i have gameobject called menuView. I created script that toogleGameobject and it is simple - check if it is selfActive, if it is then set to false and if it false then set it to true. Problem is that for some reason it was not working. Then inside that function i set Debug.Log(selfActive) and in my console it returns that it is true but my gameobject is false. Here is image: I am calling script by button and script need parameter gameObject so I assign it through inspector. public void toogleGameObject(GameObject gameobject) { Debug.Log(gameobject + " " + gameObject.activeSelf); //In image above this down was under comment, so only Debug.Log was caled with function if(gameObject.activeSelf == true) { gameObject.SetActive(false); } else { gameObject.SetActive(true); } } Here i assign and call gameobject: A: Be careful how you name your variables. There is a local variable inherited from MonoBehaviour and Component named "gameObject". You use that gameObject to refer to the GameObject that this script is attached to. That GameObject the script is attached to is what you are currently toggling on/ff not the one that is passed to the toogleGameObject function. The GameObject that is passed to the toogleGameObject function is named gameobject not gameObject.The O is not capitalized. public void toogleGameObject(GameObject gameobject) { Debug.Log(gameobject + " " + gameobject.activeSelf); //In image above this down was under comment, so only Debug.Log was caled with function if(gameobject.activeSelf == true) { gameobject.SetActive(false); } else { gameobject.SetActive(true); } } You can also simplify this to: public void toogleGameObject(GameObject gameobject) { Debug.Log(gameobject + " " + gameobject.activeSelf); gameobject.SetActive(!gameobject.activeSelf); } Finally, I suggest you rename the parameter variable GameObject gameobject to GameObject objToToggle so that you won't make this mistake in the future again. public void toogleGameObject(GameObject objToToggle) { Debug.Log(objToToggle + " " + objToToggle.activeSelf); objToToggle.SetActive(!objToToggle.activeSelf); }
[ "stackoverflow", "0032094801.txt" ]
Q: Rails4 order by column alias in joins group I want to have the slugs of the categories in descendent order of number of products per category (the category slug for the category witht the most products is first and the ones without products are last) I Rails 3.2 the query Category. joins("LEFT OUTER JOIN products ON products.category_id = categories.id"). select('count("products"."id") as products_count'). group("categories.slug"). order("products_count desc"). select("categories.slug") worked. However after upgrading, I get an ActiveRecord::StatementInvalid: PG::UndefinedColumn error, saying that column products_count doesn't exist ...and_id = categories.id GROUP BY categories.slug ORDER BY products_c... How should I fix it? A: ORDER BY does not recognize aliases. Quick fix: Category. joins("LEFT OUTER JOIN products ON products.category_id = categories.id"). group("categories.slug"). order('count("products"."id") desc'). select("categories.slug") Why did it work before but not after upgrading? I'm not sure, but I guess that it has to do with optimizations (delayed execution) added to ActiveRecord.
[ "stackoverflow", "0002888404.txt" ]
Q: -Wextra how useful is it really? I'm reading the gcc manual at the moment, especially the part about warning/error flags. After reading the part about the -Wextra flag, I wonder if it is useful at all. It seems that it complains about things which seem to be rather subjective or a matter of taste. I'm not that experienced with gcc, I only use it from time to time for some small projects at university, so to all experienced C/C++ (or for whatever language you use gcc), what's the deal with -Wextra? A: -Wextra, among other stuff implies -Wtype-limits: Warn if a comparison is always true or always false due to the limited range of the data type, but do not warn for constant expressions. For example, warn if an unsigned variable is compared against zero with '<' or '>='. This warning is also enabled by -Wextra. I find this really useful. A: I usually add -Wno-sign-compare and -Wno-unused-parameter to remove noise. The implied -Wuninitialized (with the -O2 option) has been very helpful to me, but adding it initially to your code base can be a bit daunting. One way to deal with this is to add two macros (which look slightly strange: the equal sign is intentional): #define ELIMINATE_GCC_WARNING = 0 // used to remove nuisance warnings #define UNCHECKED_GCC_WARNING = 0 // not yet verified Then you can quickly eliminate the gcc warnings and get a clean compile by using e.g.: int foo UNCHECKED_GCC_WARNING; Then as an optional step go back and check these additions, and change them one-by-one to ELIMINATE_GCC_WARNING. This can be slow. But I would be surprised if you didn't find some existing bugs.
[ "stackoverflow", "0054372407.txt" ]
Q: Still confused on ConfigureAwait(false) used with GetAwaiter and GetResult in C#. Getting a deadlock or method not returning I have read: http://blog.stephencleary.com/2012/07/dont-block-on-async-code.html and the accepted answer at deadlock even after using ConfigureAwait(false) in Asp.Net flow but am just too dense to see what is going on. I have code: private void CancelCalibration() { // ... TaskResult closeDoorResult = CloseLoadDoor().ConfigureAwait(false).GetAwaiter().GetResult(); CalibrationState = CalibrationState.Idle; return; // ... } private async Task<TaskResult> CloseLoadDoor() { TaskResult result = await _model.CloseLoadDoor().ConfigureAwait(false); return result; } public async Task<TaskResult> CloseLoadDoor() { TaskResult result = new TaskResult() { Explanation = "", Success = true }; await _robotController.CloseLoadDoors().ConfigureAwait(false); return result; } public async Task CloseLoadDoors() { await Task.Run(() => _robot.CloseLoadDoors()); } public void CloseLoadDoors() { // syncronous code from here down _doorController.CloseLoadDoors(_operationsManager.GetLoadDoorCalibration()); } As you can see, CloseLoadDoor is declared async. I thought (especially from the first article above) that if I use ConfigureAwait(false) I could call an async method without a deadlock. But that is what I appear to get. The call to "CloseLoadDoor().ConfigureAwait(false).GetAwaiter().GetResult() never returns! I'm using the GetAwaiter.GetResult because CancelCalibration is NOT an async method. It's a button handler defined via an MVVM pattern: public ICommand CancelCalibrationCommand => _cancelCalibrationCommand ?? (_cancelCalibrationCommand = new DelegateCommand(CancelCalibration)); If someone is going to tell me that I can make CancelCalibration async, please tell me how. Can I just add async to the method declaration? HOWEVER, I'd still like to know why the ConfigureAwait.GetAwaiter.GetResult pattern is giving me trouble. My understanding was that GetAwaiter.GetResult was a way to call async method from syncronous methods when changing the signature is not an option. I'm guessing I'm not really freeing myself from using the original context, but what am I doing wrong and what is the pattern to fix it? Thanks, Dave A: I thought (especially from the first article above) that if I use ConfigureAwait(false) I could call an async method without a deadlock. There's an important note in that article: Using ConfigureAwait(false) to avoid deadlocks is a dangerous practice. You would have to use ConfigureAwait(false) for every await in the transitive closure of all methods called by the blocking code, including all third- and second-party code. Using ConfigureAwait(false) to avoid deadlock is at best just a hack). So, is ConfigureAwait(false) used for every await in the transitive closure? This means: Does CloseLoadDoor use ConfigureAwait(false) for every await? We can see from the code posted that it does. Does _model.CloseLoadDoor use ConfigureAwait(false) for every await? That we cannot see. Does every method called by _model.CloseLoadDoor use ConfigureAwait(false) for every await? Does every method called by every method called by _model.CloseLoadDoor use ConfigureAwait(false) for every await? etc. This is a severe maintenance burden at least. I suspect that somewhere down the call stack, there's a missing ConfigureAwait(false). As that note concludes: As the title of this post points out, the better solution is “Don’t block on async code”. In other words, the whole point of that article is "Don't Block on Async Code". It's not saying "Block on Async Code with This One Neat Trick". If you do want to have an API that supports both synchronous and asynchronous callers, I recommend using the bool argument hack in my article on brownfield async. On a side note, in the code CloseLoadDoor().ConfigureAwait(false).GetAwaiter().GetResult(), the ConfigureAwait doesn't do anything. It's "configure await", not "configure task". Since there's no await there, the ConfigureAwait(false) has no effect.
[ "stackoverflow", "0043525276.txt" ]
Q: Unexpected addition operator with my class I apologize if the question is Naive. I am trying to overload the addition operator for fractions. My intent was to add fractions but for some reason it is adding the integers. Can some one explain why is it performing the integer addition. Code is below. #include <iostream> #include <string> using namespace std; class Fraction{ long numerator; long denominator; long gcd(long num1, long num2); long lcm(long num1, long num2); public: void convert_int_to_fraction(int num); void reduce(); Fraction(int num); Fraction(){ numerator = 0; denominator = 0; } Fraction(long num, long den); Fraction operator+(Fraction fraction); friend ostream& operator<<(ostream& os, const Fraction& fracNumber); }; void Fraction::convert_int_to_fraction(int num){ denominator = 1; numerator = long(num); reduce(); } Fraction::Fraction(int num){ convert_int_to_fraction(num); } long Fraction::gcd(long num1, long num2){ if(num1 == 0) return num2; else return (gcd(num2 % num1, num1)); } //Math function to calculate LCM long Fraction::lcm(long num1, long num2){ long great_Divisor = gcd(num1, num2); return ((num1/great_Divisor) * num2); } //Reduce fraction to its minimal void Fraction::reduce(){ if(denominator!=0){ long great_Divisor = gcd(numerator, denominator); numerator /= great_Divisor; denominator /= great_Divisor; if(denominator < 0 && numerator > 0){ denominator = -denominator; numerator = -numerator; } } } Fraction::Fraction(long num, long den):numerator(num), denominator(den){ reduce(); } ostream& operator<<(ostream& os, const Fraction& fracNumber){ os << fracNumber.numerator << "/" << fracNumber.denominator ; return os; } Fraction Fraction::operator+(Fraction fraction){ Fraction result; long least_Multiple = lcm(denominator, fraction.denominator); result.denominator = (least_Multiple); long result_Numerator = ((numerator * (least_Multiple/denominator)) + (fraction.numerator * (least_Multiple/fraction.denominator))); result.numerator = (result_Numerator); result.reduce(); return result; } int main(){ Fraction frac1(2,4); cout << frac1 + 2 << endl; return 0; } The output is 5/2 So I tried to do it the other way round cout << 2 + frac1 << endl; This is giving me error. So now I tried to fix this by implementing these two functions. Fraction::operator int(){ return convert_fraction_to_int(); } int Fraction::convert_fraction_to_int(){ return ((int)(numerator/denominator)); } Now even the first operation cout doesnt work. But the best thing is everything works fine when I typecast the variables. Can anyone explain why it is working in the first case, why not in the second case and why broken in the third case. A: .My intent was to add fractions but for some reason it is adding the integers. Can some one explain why is it performing the integer addition. There is a converting constructor from int to Fraction. frac1 + 2 is being converted to frac1 + Fraction(2) by the compiler. Update If you want the compiler to be able support both frac1 + 2 and 2 + frac1, you can make the operator+ function a non-member function. friend Fraction operator+(Fraction const& lhs, Fraction const& rhs); and implement it as: Fraction operator+(Fraction const& lhs, Fraction const& rhs) { Fraction result; // Needed to make lcm and gcd static member functions since // they work independent of the member variables. long least_Multiple = Fraction::lcm(lhs.denominator, rhs.denominator); result.denominator = (least_Multiple); long result_Numerator = ((lhs.numerator * (least_Multiple/lhs.denominator)) + (rhs.numerator * (least_Multiple/rhs.denominator))); result.numerator = (result_Numerator); result.reduce(); return result; } Now, you can use Fraction frac1(2,4); Fraction frac2(3,7); cout << frac1 + 2 << endl; cout << 3 + frac1 << endl; cout << frac1 + frac2 << endl;
[ "stackoverflow", "0051231688.txt" ]
Q: Can't install l18n, UnicodeDecodeError: 'cp950' codec can't decode byte Error occurs when I run pip install l18n Traceback (most recent call last): File "<string>", line 1, in <module> File "C:\Users\X\AppData\Local\Temp\pip-install-8urtlamu\l18n\setup.py", line 99, in <module> long_description=open(os.path.join('README.rst')).read(), UnicodeDecodeError: 'cp950' codec can't decode byte 0xc3 in position 2135: illegal multibyte sequence Tried but didnt work: chcp 65001 Alternative concole: cmder Config: Windows 7 Python 3.6.4 Pip 10.0.1 Thanks! A: It is manifestly a bug inside l18n: in the setup.py, the long_description parameter is build by reading the README.rst file (this is a classic way to do that). The trace back says: 'cp950' codec can't decode byte 0xc3 in position 2135. This is a classic error with utf-8 encoded text which contains non-ascii characters. The source code is stored in Bitbucket: long_description=open(os.path.join('README.rst')).read(), The behavior of the open function changed in Python 3. You must set the file encoding which is utf-8 here: A portable way to solve that is to define a function: import io def read(path): with io.open(path, mode='r', encoding='utf-8') as f: return f.read() And to use it like this: long_description=read('README.rst') There is an issue about that.
[ "stackoverflow", "0048676352.txt" ]
Q: C# ffmpeg unable to load dll avcodec I downloaded project to controlling AR Drone from this site: https://github.com/Ruslan-B/AR.Drone This project is old. Then I downloaded ffmpeg.autogen library from this site https://sourceforge.net/projects/ffmpeg-autogen/?source=typ_redirect This is old version of ffmpeg because of old version AR.Drone. I has to be .NET Framework 4.0 version. Project has compiled, but when I run application I got an error: "Unable to load DLL 'avcodec': The specified module could not be found. (Exception from HRESULT: 0x8007007E)" The error occurs in this line: FFmpegInvoke.avcodec_register_all(); A: I would advice to clone the project including submodules. Here is the quote from README.md: git clone http://github.com/Ruslan-B/AR.Drone.git cd AR.Drone git submodule update --init It supposed download not only source code but compatible ffmpeg binaries as well. As a next step you need to build AR.Drone solution with VS2012+ it going to build all dependencies for you and then you will be able to start AR.Drone.WinApp project. It will auto pickup the ffmpeg binaries by convention.
[ "stackoverflow", "0048423504.txt" ]
Q: How to find a specific element with JS in the browser console? I want to search the DOM for a form with property name = "formName". i've tryed with document.querySelectorAll("[name = formName]") but it only works when I inspect the elemnt and then type it on the console. It looks like I have two IFrames on the page under the so-called "top". How can I search for the specific element regardless of the selected file? Or at least from "top". A: Try this - document.querySelectorAll('[role="contentinfo"]') it uses querySelectorAll to select using attribute (role="contentinfo")
[ "stackoverflow", "0039194227.txt" ]
Q: in C, trying to use a program that converts Fahrenheit to kelvin But the calculation doesn't work or change when I run it and plug in any random number...need some guidance. I'm a novice to C and programming in general so please include easy to understand help. #include <stdio.h> double const change_celcius = 32.0; double const change_kelvin = 273.15; void temperatures(double n); int main(void) { int q = 'q'; double user_number; printf("Enter the fahrenheit: \n"); scanf("%f", &user_number); while (user_number != q) { temperatures(user_number); printf("\n"); printf("Enter the fahrenheit: \n"); scanf("%f", &user_number); } } void temperatures(double n) { double celsius, kelvin; celsius = 5.0 / 9.0 * (n - change_celcius); kelvin = 5.0 / 9.0 * (n - change_celcius) + change_kelvin; printf("fahrenheit: %.2f - celsius is: %.2f - kelvin is: %.2f", n, celsius, kelvin); } A: I don't believe the all the use %lf instead of %f comments, by themselves, fix your program. The handling of q (for "quit") is also problematic so let's fix that too. First, we'll use POSIX function getline() to read it into a string and test if it's "q". If not, we'll sscanf it into a double and use it as our temperature: #include <stdio.h> #include <string.h> #include <stdlib.h> double const change_celsius = 32.0; double const change_kelvin = 273.15; void temperatures(double n) { double celsius = 5.0 / 9.0 * (n - change_celsius); double kelvin = 5.0 / 9.0 * (n - change_celsius) + change_kelvin; printf("fahrenheit: %.2f - celsius is: %.2f - kelvin is: %.2f\n", n, celsius, kelvin); } int main(void) { char *user_string = NULL; ssize_t user_string_length; size_t user_string_capacity = 0; while (1) { printf("Enter the fahrenheit: "); if ((user_string_length = getline(&user_string, &user_string_capacity, stdin)) < 1) break; if (strncmp(user_string, "q\n", (size_t) user_string_length) == 0) break; double user_number; if (sscanf(user_string, "%lf", &user_number) == 1) temperatures(user_number); } if (user_string != NULL) free(user_string); // free memory allocated by getline() if (user_string_length == -1) putchar('\n'); // output courtesy newline if user used ^D to exit return(0); } We check the return value of sscanf so that bad input won't cause the program to recalculate using the last good input. Instead, it will just prompt again for input.
[ "italian.stackexchange", "0000003640.txt" ]
Q: When to use what translation of the word “to throw” Gettare, lanciare, tirare, scagliare all mean “to throw”. Which word is used as to throwing a ball? What situations are the other words used in? A: This list is sorted by use frequency: tirare: this is classical "to throw", by hand or by foot lanciare: usually when the ball is thrown by hand scagliare: this is very uncommon, it's usually used when you throw the ball against someone, and that's usually specified. "Gli ha scagliato la palla contro" is an example. Since it represents an offensive act, intended to hurt someone, its use is very uncommon for a ball. Gettare (as buttare) isn't used with this meaning, it rather means "to throw away".
[ "meta.stackexchange", "0000111261.txt" ]
Q: Why does the nomination page ask me to nominate myself when I'm not eligible In what appears to be new to this election, there are a series of badges you need to be nominated as a stackoverflow moderator. Although I didn't intend to nominate myself, I did check (out of idle curiosity I suppose) if I had the set. I don't. I'm missing Pundit. No problem, but then why is there a link encouraging me to nominate myself? Update: when I posted (and I might still be within ninja-edit time now) the Pundit badge was listed, and the link was there. So if the link appears smartly, they were out of sync. But maybe it appears to everyone? A: The badge requirements were created because of the size and growth of Stack Overflow as a site, as well as the workload that moderators will have. We want moderators who will be active in handling this, and it was determined that the badges were strong requirements. A change has been pushed that will now require these badges to be in place, and will prohibit nominations from any who lack those badges yet still attempt to submit a nomination. Run on. This badge requirement is still specific to Stack Overflow, however, as explained above. A: The badge checking simply hasn't been written in the election page yet. After all it'd probably be inappropriate to require all six five four badges on all sites of the network indiscriminately.
[ "rpg.stackexchange", "0000154763.txt" ]
Q: How should Thaumaturgy's "three times as loud as normal" be interpreted? This may be a bit of a silly question, but it came up during playing and left me wondering. The spell description states that your voice booms "three times as loud as normal", but it leaves open how the volume of a voice is measured. Two common ways to measure the volume of sound is to measure the pressure difference the sound causes as it travels through air and optionally to transform this level on a logarithmic scale (the Decibel scale). This table lists several things to reference. For example the upper end of a normal conversation sits at 0.02Pa or 60Db. Now if we mean "three times as loud" on the linear pressure scale, that elevates a normal talking voice to the volume of a TV set. Not very impressive. If we mean "three times as loud" on the logarithmic scale, that comes out above the volume of a stun grenade. Very impressive, though probably a bit unbalanced for a cantrip. Obviously neither of these interpretations is what the spell creator had in mind. But, then what is? A: Our group has ruled similar spells and effects to mean that the sound could be heard 3x as far away. e.g. if a Shout can be heard reasonably clearly 100 yards away, then Thaumaturgy would make it clearly audible up to 300 yards. Anyone "close" (undefined) to the Caster would be wanting to cover their ears, and might have a slight ringing afterwards, but no game-mechanical effect. A: Ask your DM This is one of those "get creative" spells like Prestidigitation that is (I think) deliberately left fairly vague because it is meant to be an adaptable utility cantrip geared towards the narrative/problem solving aspect of the game. A voice can be a whisper, a conversational tone, or a full throated yell. Nevermind how to the amplification is calculated, even the starting sound is subject to a lot of variability. The point is that the voice is amplified. A player attempting to use Thaumaturgy should inform the DM what sort of effect/benefit they are aiming to achieve and work with the DM to figure out if/how that is achievable. As Black Spike points out in their good answer, one very easy solution to implement would be to simplify the question to how far the voice carries (since this is probably the more relevant question). If it's three times louder, it can be heard at three times the distance it normally could be heard. While the Sourcebooks don't seem to quantify this distance in any way, the (an) official DM screen does include this info about audibility: Audible Distance Trying to be quiet 2d6 x 5 feet Normal noise level 2d6 x 10 feet Very loud 2d6 x 50 feet A: It would be three times the volume on the linear scale. Even when things are measured on a logarithmic scale, we don't use "x times larger" to represent the values on the logarithmic scale itself. For example, an M8.0 earthquake is not twice as powerful as an M4.0 earthquake, but rather 10000x more powerful.
[ "tex.stackexchange", "0000208246.txt" ]
Q: Problem with 'shrink' I have a very basic problem. When I use shrink command I receive an error page as below. Here is my code % !TEX encoding = UTF-8 Unicode \documentclass{beamer} \mode<presentation> \usetheme{Madrid} \setbeamercovered{transparent} \usepackage{beamerthemesplit} \usepackage[utf8]{inputenc} \usepackage{graphics} \usepackage{graphicx} \usepackage{hyperref} \usepackage{booktabs} \usepackage{times} \usepackage[T1]{fontenc} \usepackage{natbib} \usepackage[turkish]{babel} \bibpunct[, ]{(}{)}{;}{a}{,}{,} \title{ İkili Değişken ve Lojistik Regresyon} \author[Günal]{Günal } \institute{ Y} \date{\today} \setcounter{page}{51} \begin{document} \begin{frame} \titlepage \end{frame} \begin{frame}[shrink=30] \frametitle{Giriş} \section{İkili Değişken Nedir?} \textbf{İkili Değişken Nedir?} İkili değişken sadece 2 muhtemel sonucu gösteren kesikli değişkendir. Örneğin: yazı-tura, doğum-ölüm, vb. \begin{equation} Z = \begin{cases} 1 & \text{Eğer sonuç başarı ise} \\ 0 & \text{Eğer sonuç başarısızlık ise} \end{cases} \end{equation} \begin{equation} P(Z=1)=\pi \end{equation} \begin{equation} P(Z=0)=1- \pi \end{equation} \end{frame} \end{document} and here is the error Hope that much info is enough for you to comment. I guess I need to add some particular package, but do not which one. A: The problem is not specific to shrink. The Turkish module of babel activates = and this causes problems for the interpretation of key-value syntax. If you have an up-to-date TeX system you can disable the = shorthand (that does nothing useful, in my opinion) maintaining the other two: \usepackage[turkish,shorthands=:!]{babel} With an older TeX system (with babel 3.8 or older), it's a bit more obscure: \usepackage[turkish]{babel} \AtBeginDocument{\catcode`==12 }
[ "stackoverflow", "0038410062.txt" ]
Q: How to find latitude and longitude lies within radius? I have latitude and longitude of place. How to find these latitude and longitude lies within some other locations radius? for example having (6.8914,79.8522) (lat,long) of location,and find within location (6.9584218,80.1783008) of radius 10. please help me. A: lat1 = 6.8914 # latitude of point 1 long1 = 79.8522 # longitude of point 1 lat2 = 6.9584218 # latitude of point 2 long2 = 80.1783008 # longitude of point 2 if distance between two geographical points < 10: point2 lies inside radius else: it doesn't You may seek idea how to calculate distance between two geographical points and the programmatical implementation by using Haversine Formula here.