text
stringlengths
64
81.1k
meta
dict
Q: Azure table storage performance - REST vs. StorageClient I am working with Azure Table Storage, and trying to figure out the best way to increase performance. The queries that I perform are very simple - either an exact select using partition key and row key, or a where clause with a list (e.g., WHERE x==1 or x==2 or x==3, etc). Once I get the data back, I don't track it in a data context (no need for change tracking, etc). Saving data is likewise, so I only add it to the context to enable the save. At the moment, I am using the .NET library (storage client). As I don't use the change tracking and other features of the TableServiceContext, I am thinking about using the HTTP API directly. Has anyone tried both options? If so, what kind of performance difference did you see? Thanks, Erick A: Table storage can be a bit of a fickle beast to optimize performance. There are a variety of factors that will impact it. Here are just a few off the top of my head: Using a Partition Key in every query is a must. If you are not doing this, you are doing it wrong. If you use single PK and single RK (and only those two), it is no longer a query, but a resource GET and should be relatively instantaneous. Do not use OR-based queries. This will cause a full table scan and your performance will be horrible. Instead, parallelize those queries within the OR statement. Partitioning strategy will have a major impact. How many partitions you have and how often you hit them (to warm them up and cause the underlying partition servers to load balance) will cause dramatic differences. The size of the partition makes a big impact here too. Sequential partition keys is often a bad idea. Small requests can benefit from turning off nagling (as previously mentioned). Turn off context tracking and 100 continue (see here) can help as well. There are many more I suppose that depend on your application. However, the ones I mention are generally the ones I start with.
{ "pile_set_name": "StackExchange" }
Q: Should querying for empty string match zero on a primary key column? I have this mysql query that has made me totally stumped all day: SELECT * FROM `table` WHERE id = ""; I am surprised that this query returns a row where id is "0". Is this the expected behaviour? And if yes, how should I go about excluding this row? I need this query to return no rows when I pass the empty string. Now id is a primary key column and auto_increment, if that's may help. EDIT It gets even more interesting. I have just run the query with an arbitrary string, like so: SELECT * FROM `table` WHERE id = "xyz"; It still returns the row with the id of zero. It looks like the query is somehow casting my query parameter to INTEGER. This is new to me! A: The problem with you query is that "" or "xyz" is implicitly converted to 0. Try this to see for yourself: SELECT CAST("" AS SIGNED), CAST("xyz" AS SIGNED) You can also have a look at the manual to better understand implicit type conversion. I would suggested checking the value of your parameter before issuing the query. If the user has given a non-numeric value as input then inform him/her accordingly. In MySQL you can use a method suggested in this post to check if the parameter value is numeric: SELECT * FROM `table` WHERE id = "" AND (CONCAT('', @param * 1) = @param); where @param = "" or "xyz" or "123".
{ "pile_set_name": "StackExchange" }
Q: Staggering Sidekiq Scheduled Jobs I tried using Sidekiq's perform_in call in (nextSend += 1).seconds while iterating through 30 times. But I found that each job was enqueued around the same time and executed almost immediately after each other. Why did this happen, and is there a better way to stagger calls without sleeping the application? Thanks. Some logs: 2015-06-30T21:30:12.216092+00:00 app[web.1]: SystemTime: 21:30 2015-06-30T21:30:12.216137+00:00 app[web.1]: 2015-06-30T21:30:12.216139+00:00 app[web.1]: Send story?: 2015-06-30T21:30:12.720780+00:00 app[web.1]: doing hard work!! 2015-06-30T21:30:12.720783+00:00 app[web.1]: 2015-06-30T21:30:12.722278+00:00 app[web.1]: 6 TID-oxrbofeo8 SomeWorker JID-1cb9f52c40ce3d76fb1df5c6 INFO: done: 0.508 sec 2015-06-30T21:30:30.581846+00:00 app[web.1]: 6 TID-oxrbozdlc DEBUG: enqueued schedule: {"class":"NewTextWorker","args":["StoryTime: Hi! You can now choose new stories. Do you want stories about Marley the puppy or about Bruce the moose?\n\nReply \"p\" for puppy or \"m\" for moose.","+12039095780"],"retry":false,"queue":"critical","jid":"ecda1711afd63dffced0cc30","created_at":1435699812.262315} 2015-06-30T21:30:30.625757+00:00 app[web.1]: 6 TID-oxrbofeo8 NewTextWorker JID-ecda1711afd63dffced0cc30 INFO: start 2015-06-30T21:30:30.640225+00:00 app[web.1]: 6 TID-oxrbo923c NewTextWorker JID-8bf1e1b26054e5b335232f27 INFO: start 2015-06-30T21:30:30.640229+00:00 app[web.1]: 6 TID-oxrbozdlc DEBUG: enqueued schedule: {"class":"NextMessageWorker","args":["StoryTime: Here's your new story... beware of hungry crocodiles!",["http://i.imgur.com/gNPKPSs.jpg","http://i.imgur.com/SRDF3II.jpg","http://i.imgur.com/iSVBGu4.jpg"],"+12034354841"],"retry":false,"queue":"critical","jid":"cb93b0d5469ae43b9c355fd4","created_at":1435699812.352102} 2015-06-30T21:30:30.640253+00:00 app[web.1]: 6 TID-oxrbvnftw NewTextWorker JID-145a78e8a781bdee9d364eaf INFO: start 2015-06-30T21:30:30.583719+00:00 app[web.1]: 6 TID-oxrbozdlc DEBUG: enqueued schedule: {"class":"NewTextWorker","args":["StoryTime: Hi! You can now choose new stories. Do you want stories about Marley the puppy or about Bruce the moose?\n\nReply \"p\" for puppy or \"m\" for moose.","+15615422026"],"retry":false,"queue":"critical","jid":"8bf1e1b26054e5b335232f27","created_at":1435699812.296749} 2015-06-30T21:30:30.626992+00:00 app[web.1]: 6 TID-oxrbozdlc DEBUG: enqueued schedule: {"class":"NewTextWorker","args":["StoryTime: Hi! You can now choose new stories. Do you want stories about Marley the puppy or about Bruce the moose?\n\nReply \"p\" for puppy or \"m\" for moose.","+12033615947"],"retry":false,"queue":"critical","jid":"145a78e8a781bdee9d364eaf","created_at":1435699812.3334303} 2015-06-30T21:30:30.668423+00:00 app[web.1]: 6 TID-oxrbozdlc DEBUG: enqueued schedule: {"class":"NewTextWorker","args":["StoryTime: Hi! You can now choose new stories. Do you want stories about Marley the puppy or about Bruce the moose?\n\nReply \"p\" for puppy or \"m\" for moose.","+16468878679"],"retry":false,"queue":"critical","jid":"4a7b6d697095ecd670a00078","created_at":1435699812.372093} 2015-06-30T21:30:30.769061+00:00 app[web.1]: 6 TID-oxrbozdlc DEBUG: enqueued schedule: {"class":"NewTextWorker","args":["StoryTime: Hi! You can now choose new stories. Do you want stories about Marley the puppy or about Bruce the moose?\n\nReply \"p\" for puppy or \"m\" for moose.","+15612125831"],"retry":false,"queue":"critical","jid":"29e7553ccab09cada3a0c919","created_at":1435699812.3837028} 2015-06-30T21:30:30.656838+00:00 app[web.1]: 6 TID-oxrbozdlc DEBUG: enqueued schedule: {"class":"NewTextWorker","args":["StoryTime: Hi! We noticed you didn't choose your last story. Do you want stories about Marley the puppy or about Bruce the moose?\n\nReply \"p\" for puppy or \"m\" for moose.","+15619008225"],"retry":false,"queue":"critical","jid":"85cb3b18503837dac61ace6b","created_at":1435699812.3557012} 2015-06-30T21:30:30.771557+00:00 app[web.1]: 6 TID-oxrbozdlc DEBUG: enqueued schedule: {"class":"NewTextWorker","args":["StoryTime: Hi! You can now choose new stories. Do you want stories about Marley the puppy or about Bruce the moose?\n\nReply \"p\" for puppy or \"m\" for moose.","+12392735883"],"retry":false,"queue":"critical","jid":"2f072b313a0fbe1b3413a466","created_at":1435699812.4306083} 2015-06-30T21:30:30.800228+00:00 app[web.1]: 6 TID-oxrbozdlc DEBUG: enqueued schedule: {"class":"NewTextWorker","args":["StoryTime: Hi! You can now choose new stories. Do you want stories about Marley the puppy or about Bruce the moose?\n\nReply \"p\" for puppy or \"m\" for moose.","+13522226913"],"retry":false,"queue":"critical","jid":"4dcd80cac50e8f19a2b6d867","created_at":1435699812.5680537} 2015-06-30T21:30:30.816201+00:00 app[web.1]: 6 TID-oxrbozdlc DEBUG: enqueued schedule: {"class":"NewTextWorker","args":["StoryTime: Hi! You can now choose new stories. Do you want stories about Marley the puppy or about Bruce the moose?\n\nReply \"p\" for puppy or \"m\" for moose.","+19417243442"],"retry":false,"queue":"critical","jid":"674e5f1aa017bd6b50140cb4","created_at":1435699812.5889344} 2015-06-30T21:30:30.749579+00:00 app[web.1]: 6 TID-oxrbvm37c NextMessageWorker JID-cb93b0d5469ae43b9c355fd4 INFO: start 2015-06-30T21:30:30.769567+00:00 app[web.1]: 6 TID-oxrbvkjm8 NewTextWorker JID-85cb3b18503837dac61ace6b INFO: start 2015-06-30T21:30:30.786596+00:00 app[web.1]: 6 TID-oxrbozdlc DEBUG: enqueued schedule: {"class":"NewTextWorker","args":["StoryTime: Hi! You can now choose new stories. Do you want stories about Marley the puppy or about Bruce the moose?\n\nReply \"p\" for puppy or \"m\" for moose.","+17722330863"],"retry":false,"queue":"critical","jid":"fd1d1c029e836c12577fd7ca","created_at":1435699812.5403354} 2015-06-30T21:30:30.804066+00:00 app[web.1]: 6 TID-oxrbozdlc DEBUG: enqueued schedule: {"class":"NextMessageWorker","args":["StoryTime: Here's your new story... beware of hungry crocodiles!",["http://i.imgur.com/gNPKPSs.jpg","http://i.imgur.com/SRDF3II.jpg","http://i.imgur.com/iSVBGu4.jpg"],"+15615734535"],"retry":false,"queue":"critical","jid":"1e0fd68d4e0997ef0152a97d","created_at":1435699812.5728064} 2015-06-30T21:30:30.825363+00:00 app[web.1]: 6 TID-oxrbozdlc DEBUG: enqueued schedule: {"class":"NewTextWorker","args":["StoryTime: Hi! You can now choose new stories. Do you want stories about Marley the puppy or about Bruce the moose?\n\nReply \"p\" for puppy or \"m\" for moose.","+12022518772"],"retry":false,"queue":"critical","jid":"07e7dcf3ce90bc71d2107a11","created_at":1435699812.6284366} 2015-06-30T21:30:30.844143+00:00 app[web.1]: 6 TID-oxrbozdlc DEBUG: enqueued schedule: {"class":"NewTextWorker","args":["StoryTime: Hi! You can now choose new stories. Do you want stories about Marley the puppy or about Bruce the moose?\n\nReply \"p\" for puppy or \"m\" for moose.","+15614796303"],"retry":false,"queue":"critical","jid":"5a8db8568fc44faefbddc422","created_at":1435699812.6561987} 2015-06-30T21:30:30.871928+00:00 app[web.1]: 6 TID-oxrbozdlc DEBUG: enqueued schedule: {"class":"NewTextWorker","args":["StoryTime: Hi! You can now choose new stories. Do you want stories about Marley the puppy or about Bruce the moose?\n\nReply \"p\" for puppy or \"m\" for moose.","+15613056454"],"retry":false,"queue":"critical","jid":"b2e5d924c67443e1a6252a80","created_at":1435699812.6815143} 2015-06-30T21:30:30.850455+00:00 app[web.1]: 6 TID-oxrbozdlc DEBUG: enqueued schedule: {"class":"NewTextWorker","args":["StoryTime: Hi! You can now choose new stories. Do you want stories about Marley the puppy or about Bruce the moose?\n\nReply \"p\" for puppy or \"m\" for moose.","+18456711380"],"retry":false,"queue":"critical","jid":"486328d6fbc6f835f216186a","created_at":1435699812.6689503} 2015-06-30T21:30:30.877893+00:00 app[web.1]: 6 TID-oxrbozdlc DEBUG: enqueued schedule: {"class":"NewTextWorker","args":["StoryTime: Hi! You can now choose new stories. Do you want stories about Marley the puppy or about Bruce the moose?\n\nReply \"p\" for puppy or \"m\" for moose.","+15617893548"],"retry":false,"queue":"critical","jid":"4d5812202383601c879a9774","created_at":1435699812.693517} 2015-06-30T21:30:31.159120+00:00 app[web.1]: Sent sms to +12039095780: : Hi! You can now 2015-06-30T21:30:31.187398+00:00 app[web.1]: 6 TID-oxrbofeo8 NewTextWorker JID-4a7b6d697095ecd670a00078 INFO: start 2015-06-30T21:30:31.257215+00:00 app[web.1]: 6 TID-oxrbo923c NewTextWorker JID-8bf1e1b26054e5b335232f27 INFO: done: 0.621 sec 2015-06-30T21:30:31.321590+00:00 app[web.1]: Sent sms to +12033615947: : Hi! You can now 2015-06-30T21:30:31.337535+00:00 app[web.1]: 6 TID-oxrbvnftw NewTextWorker JID-2f072b313a0fbe1b3413a466 INFO: start 2015-06-30T21:30:31.183538+00:00 app[web.1]: 6 TID-oxrbofeo8 NewTextWorker JID-ecda1711afd63dffced0cc30 INFO: done: 0.558 sec 2015-06-30T21:30:31.245844+00:00 app[web.1]: Sent sms to +15615422026: : Hi! You can now 2015-06-30T21:30:31.274294+00:00 app[web.1]: 6 TID-oxrbo923c NewTextWorker JID-29e7553ccab09cada3a0c919 INFO: start 2015-06-30T21:30:31.333168+00:00 app[web.1]: 6 TID-oxrbvnftw NewTextWorker JID-145a78e8a781bdee9d364eaf INFO: done: 0.693 sec 2015-06-30T21:30:31.523343+00:00 app[web.1]: Sent mms to +12034354841: /gNPKPSs.jpgSent sms to +16468878679: : Hi! You can now 2015-06-30T21:30:31.523387+00:00 app[web.1]: ` A: Sidekiq's scheduler is not that granular, it checks every 15 seconds by default. If you want it to be more precise, you need to lower the poll interval: Sidekiq.configure_server do |config| config.average_scheduled_poll_interval = 5 end This code goes in config/initializers/sidekiq.rb (see example).
{ "pile_set_name": "StackExchange" }
Q: Number of multisets with restrictions on specific element count I am looking to find the number of multisets with restrictions on the number of specific elements. This isn't for homework, it is a work related problem. My set of items is {A, a, B, b}. I want to get the number of multisets with at least 3 B/b, where there is at least one of each B/b. For multisets order does not matter, and duplicates are allowed. To get the total number of multisets with cardinality $k$, from my set of cardinality n = 4, I have been using, $$\frac{(n + k - 1)!}{(k!(n-1)!}$$However I want to count the number of multisets with at least 3 B or b, and a minimum of 1 each. For $k = 3$ there are two solutions, $\{B, B, b\}$ and $\{B, b, b\}$. These two sets represent the minimum requirements to pass. Then for any $k$, I was thinking the number of multisets to be $$2 * (\frac{(4 + (k-3) - 1)!}{((k-3)!(n-1)!})$$ My reasoning was that the possible valid sets are $\{B, B, b, x_3, x_4, ... x_k\}$ and $\{B, b, b, x_3, x_4, ... x_k\}$, where $\{x_3, x_4, ..., x_k\}$ is any multiset from {A, a, B, b} with cardinality $k - 3$. The problem I ran into is that this method counts some sets multiple times. For example, if k = 4, the valid sets are $\{B, B, b, x_3\}$ and $\{B, b, b, y_3\}$, where $x_3$ and $y_3$ are any item in $\{A, a, B, b\}$. For $x_3 = b$ and $y_3 = B$, I am counting the set $\{B, B, b, b\}$ twice. I tried predicting the number of duplicate counts and subtracting that, but could not find an answer. If I assign each element in my set $\{x_0 = A, x_1 = a, x_2 = B, x_3 = b\}$, another way to phrase the problem is to find the number of solutions to, $$ x_0 + x_1 + x_2 + x_3 = k $$ where, $$k >= x_0, x_1, x_2, x_3 >= 0$$ $$k >= x_2 + x_3 >= 3$$ $$x_2 >= 1$$ $$x_3 >= 1 $$ EDIT Thanks for the help guys. I have changed the requirement of 3 'B/b' elements to $minB$ 'B/b' elements. So for a multiset of size D with $minB$ required 'B\b' elements, $\{B, b, x_3, x_4, ... x_D\}$ is a valid multiset if $\{x_3, x_4, ... x_D\}$ has minB-2 'B/b' elements. Based off of these comments I came up with, $$ numValid(D, minB) = \sum_{nb = minB - 2}^{D-2} [(nb + 1) * (D - nb - 1)] $$ The first term inside the sum $(nb + 1)$ is the number of multisets of size $minB - 2$ chosen from $\{B, b\}$. The second term is the number of multisets of size $D - 2 - nb$ chosen from $\{A, a\}$. Then summing $nb$ from $ minB - 2$ to $D - 2$, we get the number of multisets of the form $\{B, b, x_3, x_4, ... x_D\}$, where $\{x_3, x_4, ... x_D\}$ has at least $(minB - 2)$ 'B/b' elements. Is this correct? Thanks again. :) A: First take one obligatory b and one B, and forget about them. They'll always be there. Then you're looking for multisets of size $k-2$ that contain at least one b or B. We can get those by counting all multisets of size $k-2$ and then subtract the $k-1$ ones that consist only of A and a. By stars-and-bars there are $\binom{k-2+3}{3}$ multisets with or without bees, so your final count is $$ \binom{k+1}{3} - (k-1) = \frac{k^3-k}6 - k + 1$$
{ "pile_set_name": "StackExchange" }
Q: CMS Breadcrumb, separate tables for breadcrumb and page I'm trying to build a breadcrumb navigation into a CMS. Currently, the database is set out that there is a table holding each page, in rows. I've created a table which holds: item id, item text and item URL for each item/category in the breadcrumb. I'm not entirely sure where to start with placing an additional column in the table which holds the pages, with a serialised array: [1,2,5] which is then joined to the other table, to extract the relevant information, by the id numbers. A: The first question you should be asking is how does the CMS natively correlate the records in the DB to the actual page hierarchy of the site... Once you have that figured out then you can decide if you even need to store the breadcrumb separately, or if there is a way you can access this same information with the existing data.
{ "pile_set_name": "StackExchange" }
Q: Remembered values, and scope gone from memory, in a Python Closure Below is a simple piece of code I found in this tutorial. Here's a nice definition of Closure I found here: "a function object that remembers values in enclosing scopes regardless of whether those scopes are still present in memory." I gather that rotate() below is a closure. Please help me understand what values is it remembering even after their scope is gone from memory (and why does their scope leave memory)? def make_rotater(seq): def rotate(): val = seq.pop(0) seq.append(val) return val return rotate r = make_rotater([1,2,3]) r() # 1 r() # 2 (Update) Part 2: Why does the (closure-less) code below not work? def make_rotater(seq): val = seq.pop(0) seq.append(val) return val r = make_rotater([1,2,3]) r() # File "<stdin>", line 1, in <module> # TypeError: 'int' object is not callable A: It remembers local values from make_rotator so if u do: def make_rotater(): seq=[1,2,3] def rotate(): val = seq.pop(0) seq.append(val) return val return rotate The seq is referenced by rotate, so it will remain in memory for when you will call rotate, even though it was defined in make_rotater (that is already done, and cleaned from memory) When you call make_rotater it creates a new seq and defines the rotate method that references seq, so one you leave make_rotater it's memory isn't needed except seq, (cause rotate still uses it). When you will no longer reference rotate, seq will also be cleaned part 2: your method now doesnt return another method it returns the number directly, so you dont need to do r() you can use it like this: seq = [1,2,3] def make_rotater(seq): val = seq.pop(0) seq.append(val) return val r = make_rotater(seq) print r # prints 1, note there is no r() just r r = make_rotater(seq) print r # prints 2 r = make_rotater(seq) print r # prints 3
{ "pile_set_name": "StackExchange" }
Q: Pointer Member Variable Initialisation in C++ Classes, with non-Pointer Values Before I start, I'd just like to point out I've Googled this question for a while now and haven't found a satisfactory answer. I'm also aware of a very similar question on Stack Overflow, but it doesn't help me entirely with my situation. Here's my code: class A { private: int x; int y; public: A( int x, int y ); // other member functions }; class B { private: int score; A* a; public: B( int x, int y ); // Regular constructor // other member functions }; Implementation: // Default constructor with member initialisation A::A( int x, int y ) : x( x ), y( y ) {} // Default constructor with member initialisation B::B( int x, int y ) : score( 0 ), a( x, y ) {} The problem I have is with initialising the pointer member variable *a in class B. We are required to pass the x, y coordinates to the class B constructor, but I cannot get g++ to compile this as it is expecting a pointer instead of two integers. I'm having trouble wrapping my head around how to call an initialisation to the *a pointer with x, y as my parameters. In the assignment question, we aren't asked to initiate the *a pointer member variable to a null pointer, nor are we given a pointer with which to initialise it. We are only given x & y coordinates. The error I receive when compiling with g++ is: error: expression list treated as compound expression in mem-initializer [-fpermissive] : score( 0 ), a( x, y ) I'd appreciate any feedback, thanks in advance for your help! A: The way you have stated your question I have assumed that B is the creator and owner of A* a. With that requirement it is very odd to use a pointer. The natural and obvious solution to this is to use a regular member. Now the syntax problem you are having can be solved with B::B( int x, int y ) : score( 0 ), a( new A(x, y) ) {} This is a bad idea, because now you have to clean up a in your destructor. B::~B(){ delete a; }
{ "pile_set_name": "StackExchange" }
Q: Using Try: and Finally: to delete an existing file and write the new output to the file I was trying to check and delete an existing output file, and write on a new file. However, my code didn't seem to work because it only captures the output from the last iteration. # delete inactive contracts from dict() for key, item in contracts.items(): if item['contract_status'] == 'Inactive': del contracts[key] else: if os.path.exists(main_path): try: os.remove(main_path) finally: outfile = open(main_path, 'a') outfile.write(item['name']) outfile.write('\n') outfile.close() A: Instead of removing the file, just open it for writing: else: with open(main_path, 'w') as outfile: outfile.write(item['name']) outfile.write('\n') Opening a file with w truncates the file first, so data written to it replaces the old contents. Note that you are writing the file for each iteration in the loop. By using the file as a context manager (with ..) it's closed automatically. If you want to write all entries to the file, open the file outside of the loop: with open(main_path, 'w') as outfile: for key, item in contracts.items(): if item['contract_status'] == 'Inactive': del contracts[key] else: outfile.write(item['name']) outfile.write('\n') If you need to re-write the file only if there are no inactive items in contracts, use: contracts = {k: v for k, v in contracts.iteritems() if v['contract_status'] != 'Inactive'} if contracts: with open(main_path, 'w') as outfile: for contract in contracts.values(): outfile.write(item['name']) outfile.write('\n') Now you first remove the inactive items, then if there are still contracts left, write those out to the file. If there are none left, the main_path file is left untouched.
{ "pile_set_name": "StackExchange" }
Q: Angular 8 Pagination: How can I translate 'of'? I would like to translate the Paginator provided by Angular Material. I know I can access all of the labels in the _intl property of the Paginator Object: _intl: MatPaginatorIntl changes: Subject {_isScalar: false, observers: Array(1), closed: false, isStopped: false, hasError: false, …} itemsPerPageLabel: "Kunden pro Seite" nextPageLabel: "Next page" previousPageLabel: "Previous page" firstPageLabel: "First page" lastPageLabel: "Last page" getRangeLabel: (page, pageSize, length) => {…} but how can I translate 'of'? A: That is what getRangeLabel does. You format the label based on the input. getRangeLabel: (page, pageSize, length) => {return 'your label here based on input'; }
{ "pile_set_name": "StackExchange" }
Q: "Array result was not expanded because it would overwrite data" I'm trying to use Google Spreadsheets but I get this error when an IMPORTXML would overwrite some rows of cells that already has something in them: Array result was not expanded because it would overwrite data In the old Google Spreadsheets we had the EXPAND function which took care of that, but now it's gone. Is there a way to force an overwrite? A: I have just met the same issue today. I have fixed it by using the UNIQUE function. Original formula: =IFERROR(FILTER(Septemeber!J:J,Septemeber!C:C=A398)) I had duplicated values in Septemeber!J:J. The formula returned this error: Error: Array result was not expanded because it would overwrite data in C394 Working formula using UNIQUE: =IFERROR(UNIQUE(FILTER(Septemeber!J:J,Septemeber!C:C=A398)))
{ "pile_set_name": "StackExchange" }
Q: Confusion about multithreading in Python and C AFAIK, Python, using import thread, (or C#) doesn't do "real" multithreading, meaning all threads run on 1 CPU core. But in C, using pthreads in linux, You get real multithreading. Is this true ? Assuming it is true, is there any difference between them when you have only 1 CPU core (I have it in a VM)? A: Python uses something called a Global Interpreter Lock which means multiple python threads can only run within one native Thread. There is more documentation in the official Docs here: https://wiki.python.org/moin/GlobalInterpreterLock There shouldn't be a real performance difference on single core systems. On multicore systems the difference will varie based on what you do. (I/O is for the most part not affected by the GIL).
{ "pile_set_name": "StackExchange" }
Q: how to break a block using commands So what I'm looking for is a command that makes a block look like it's being mined by a player. so not /setblock or /fill, which makes the block disappear instantly. for example, in Hypixel's Blocking Dead when you shoot a block with a gun, it looks like it's being broken. It could be that they use a texture pack for the blocks breaking, but it doesn't seem likely. I have not tried to do this myself, but have searched for awhile. If anyone knows the answer, or a way to help, please tell me. Edit: thank you guys for the responses, and thanks for confirming what I thought A: Here's the thing. Popular servers like Hypixel and Mineplex don't use Vanilla Minecraft commands. They actually use something called plugins which are actually programmed with Java. Unfortunately, I couldn't find anything on the internet where you can actually do this with commands, but Hypixel definitely used plugins for this game. If you're trying to emulate what Hypixel is doing, I'm afraid I have to break the news that you probably can't (or it would be really, really hard to) do what you're wanting to do. There may be a solution, but I am alerting you of what Hypixel does
{ "pile_set_name": "StackExchange" }
Q: Use rake namespace as configuration? I am trying to create a rake file with tasks for consuming my API. I want to be able and pass a lot of arguments to the task, depending on the call to be used. In an effort to make the tasks easier to use, I want the namespace to be part of the configuration. Is this possible? namespace :myAPI do SERVER = 'local' namespace :live do SERVER = 'live' end namespace :beta do SERVER = 'beta' end BASE_URI = { live: "https://myapi.com/do/v1", beta: "https://beta.myapi.com/do/v1", local: "http://127.0.0.1:4500/do/v1" } desc 'Get currently logged users' task :extract_logged_users => :environment do get("BASE_URI[SERVER]/users/current") end } And then I want to be able and run this against the live server for example: rake myAPI:live:extract_logged_users A: You can create the task in a mor dynamic way like this: require 'rake' BASE_URI = { live: "https://myapi.com/do/v1", beta: "https://beta.myapi.com/do/v1", local: "http://127.0.0.1:4500/do/v1" }.each do |server,url| namespace :myAPI do namespace server do |ns| desc 'Get currently logged users' task :extract_logged_users do puts 'get("%s/users/current", %s)' % [server,url] end end end end (I replaced your get command with puts to check what happens and added the url into the command). Now you can call: rake myAPI:live:extract_logged_users rake myAPI:beta:extract_logged_users rake myAPI:local:extract_logged_users The output: get("live/users/current", https://myapi.com/do/v1) get("beta/users/current", https://beta.myapi.com/do/v1) get("local/users/current", http://127.0.0.1:4500/do/v1) Alternative coding: namespace :myAPI do BASE_URI = { live: "https://myapi.com/do/v1", beta: "https://beta.myapi.com/do/v1", local: "http://127.0.0.1:4500/do/v1" } BASE_URI .keys.each do |key| namespace key do |ns| desc 'Get currently logged users' task :extract_logged_users do puts 'get("%s")' % BASE_URI[key] end end end end
{ "pile_set_name": "StackExchange" }
Q: what's the fanws cookie? I wrote a simple site using BedSheet to test adding cookies. When I ran the code and inspected the cookies using firebug, I found a extra cookie I didn't add named fanws (with value 06e3d816-7626-7b00-205a-0013e8a56e9d-dbc9c6c8fa03cfa4). Here is my code: class Site { @Inject HttpCookies? cookie @Contribute { serviceType=Routes# } static Void contributeRoutes(Configuration Conf) { Conf.add(Route(`/index.html`, Site#index)) } Text index() { cookie.add(Cookie("foo", "123")) return Text.fromHtml("<h1> Hello </h1>") } } What is this cookie? What is it used for? Where did this value come from? A: fanws stands for Fanton Web Session and is added by the wisp web server to manage sessions. The value is just a UUID that uniquely identifies the session. You can read more in the web pod's documentation on Web Sessions.
{ "pile_set_name": "StackExchange" }
Q: How can I get button text by knowing its id in javafx So i am a beginner programmer and what I'm trying to do is to get specific button's text by knowing its fx:id Is it possible? For example if button fx:id = "buttonOne" and text = "X" how can I get X? A: You can define your button in controller (fx:id should be equals name of the field): @FXML Button buttonOne; And just use getText(): buttonOne.getText();
{ "pile_set_name": "StackExchange" }
Q: Rolling minimum in R I have data with the following structure: data.frame(value = c(1, 2, 10), date = as.Date(c('2018-01-01', '2018-01-02', '2018-01-04'))) and I want to compute the rolling minimum of value per row with a window of the last two days. That is, the output of this computation should be data.frame(value = c(1, 2, 10), date = as.Date(c('2018-01-01', '2018-01-02', '2018-01-04')), minimum = c(1, 1, 10)) Is there an easy way to do this using the tidyverse? A: Could go for: library(dplyr) df %>% mutate( minimum = sapply(date, function(x) min(value[between(date, x - 1, x)])) ) Output: value date minimum 1 1 2018-01-01 1 2 2 2018-01-02 1 3 10 2018-01-04 10
{ "pile_set_name": "StackExchange" }
Q: A problem with Poisson equation I'm computing the Hartree potentials of atoms by solving the Poisson equation and I use hydrogen atom as a test case. The Poisson equation for hydrogen atom in atomic units is given by $$\nabla^2 V_H = -4 \exp(-2 r)$$ where $r = \sqrt{x^2+y^2+z^2}$. The numerical solution of $V_H(x,y,z)$ with $z=0$ is illustrated in the following figure: The numerical solution is computed with the Conjugate Gradient method so that the Laplacian is computed with stencil $$ \nabla^2 f(x,y,z) \approx \frac{a+b+c-6 f(x,y,z)}{h^2} $$ where $$a = f(x+h,y,z)+f(x-h,y,z),$$ $$b = f(x,y+h,z)+f(x,y-h,z),$$ and $$c = f(x,y,z+h)+f(x,y,z-h).$$ As the right-hand side of the Poisson equation is spherically symmetric the Poisson equation takes the form $$\frac{d^2 v_H}{dr^2} + \frac{2}{r} \frac{d v_H}{dr} = -4 \exp(-2 r)$$ where $v_H$ is the Hartree potential as a function of $r$. The solution of this equation is $$v_H(r) = - \frac{r + 1}{r} \exp(-2r),$$ which is illustrated in the following figure: (here $r=\sqrt{x^2+y^2+z^2}$ and $z=0$). The Octave code computing the Laplacian is here: function aLap = StencilLap3d( a, rStep ) rH2 = rStep * rStep; vSize = size( a ); nXSize = vSize( 1 ); nYSize = vSize( 2 ); nZSize = vSize( 3 ); nXDim = ( nXSize - 1 ) / 2; nYDim = ( nYSize - 1 ) / 2; nZDim = ( nZSize - 1 ) / 2; assert( nXDim == round( nXDim ) ); assert( nYDim == round( nYDim ) ); assert( nZDim == round( nZDim ) ); aLap = zeros( nXSize, nYSize, nZSize ); rXP = 0; rXM = 0; rYP = 0; rYM = 0; rZP = 0; rZM = 0; for nX = (-nXDim):nXDim for nY = (-nYDim):nYDim for nZ = (-nZDim):nZDim if ( nX < nXDim ) rXP = a( nXDim + 1 + nX + 1, nYDim + 1 + nY, nZDim + 1 + nZ ); else rXP = 0.0; endif if ( nX > -nXDim ) rXM = a( nXDim + 1 + nX - 1, nYDim + 1 + nY, nZDim + 1 + nZ ); else rXM = 0.0; endif if ( nY < nYDim ) rYP = a( nXDim + 1 + nX, nYDim + 1 + nY + 1, nZDim + 1 + nZ ); else rYP = 0.0; endif if ( nY > -nYDim ) rYM = a( nXDim + 1 + nX, nYDim + 1 + nY - 1, nZDim + 1 + nZ ); else rYM = 0.0; endif if ( nZ < nZDim ) rZP = a( nXDim + 1 + nX, nYDim + 1 + nY, nZDim + 1 + nZ + 1 ); else rZP = 0.0; endif if ( nZ > -nZDim ) rZM = a( nXDim + 1 + nX, nYDim + 1 + nY, nZDim + 1 + nZ - 1 ); else rZM = 0.0; endif n0 = a( nXDim + 1 + nX, nYDim + 1 + nY, nZDim + 1 + nZ ); aLap( nXDim + 1 + nX, nYDim + 1 + nY, nZDim + 1 + nZ ) = ... ( rXP + rXM + rYP + rYM + rZP + rZM - 6 * n0 ) / rH2; endfor endfor endfor endfunction Obviously the solution of the differential equation should be the same as the numerical solution, so there is something wrong here. Based on my previous computations I suspect that the error is in the differential equation. Can somebody tell what is wrong? A: Problem solved: I just have to include the solution of the homogeneous equation into the solution of the differential equation. The solution to the differential equation is $$V_H(r) = -\frac{K}{r} - \frac{r+1}{r} \exp(-2r).$$ By requiring that $\lim_{r \to 0} V_H(r)$ is real we get $K=-1$ and $$V_H(r) = \frac{1}{r} - \frac{r+1}{r} \exp(-2r).$$
{ "pile_set_name": "StackExchange" }
Q: link a bootstrap modal with javascript My background is in Java and object orientated programming and I'm just starting out in bootstrap. I want to load a modal into another page using javascript and then show it on a button click but I'm not sure of the process. Is this even the correct way to go about this or is html/javascript more procedural? I want to load the modal in createOrder.html into navbar.html and I have the following. Obviously this doesn't work as I only get a darkened screen when I click the button so what is the correct way to do this? navbar.html ... <script> $(function() { $("#createOrder").load("createOrder.html"); }); </script> <button type="button" id="createOrderButton" class="btn btn-default navbar-btn" data-toggle="modal" data-target="#createOrder">Create</button> ... createOrder.html <!-- Modal --> <div class="modal fade" id="createOrder" tabindex="-1" role="dialog" aria-labelledby="createOrderLabel"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button> <h4 class="modal-title" id="myModalLabel">Create Order</h4> </div> <div class="modal-body"> ... </div> <div class="modal-footer"> <button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button> <button type="button" class="btn btn-primary">Create</button> </div> </div> </div> </div> As a side note I understand bootstrap allows you to do $('#myModal').modal(show) but how would I call that modal if the code for it resides on a different page? and if I want to stick to an MVC architecture wouldn't it make more sense to call it via data attributes? A: It looks like you have 2 div tags with the same ID. You are loading a div#createOrder inserting it to div#createOrder in your navbar.html The modal data-target is pointing at #createOrder but the javascript is not functioning correctly because of the 2 ID's and is not unhiding the modal content. The below should fix it. navbar.html <div id="createOrderHolder"></div> <button type="button" id="createOrderButton" class="btn btn-default navbar-btn" data-toggle="modal" data-target="#createOrder">Create</button> <script> $(function() { $("#createOrderHolder").load("createOrder.html"); }); </script>
{ "pile_set_name": "StackExchange" }
Q: What is the max Excel File Size(in MBs) which can be imported by SSIS I want to know the max Excel File size which we can load into db using a Simple ETL SSIS package. If file size depends upon system configs or resources, Then how can we calculate it? In my case I am trying to load an excel file of 500+Mbs. My Package gets hanged even while trying to map columns. Thanks. A: The only real limitation is the size of the machine's memory (RAM) where the package is running on, as SSIS loads the data into memory. Thus, if you only have 2GB of RAM, I wouldn't try to load files bigger than 1 GB. (you must have RAM left for SQL Server to operate, and don't forget about all your other applications) Also remember if you're not pipelining your data flows properly, and you have blocking parts like Aggregate or SQL Command objects, then you are going to be loading way more into memory than you should be. The file size is not as important if you have no blocking parts. SSIS won't load the entire object into memory, and you can specify how much it uses. But if there are blocking parts, then it will need the entire object in memory. Note that another big memory hog could be Lookup tasks with Full Caching - these can take large amounts of memory up if you are loading big tables. Hope this helps.
{ "pile_set_name": "StackExchange" }
Q: Replace class new[] variables with vectors - move, copy operators I made a sparse matrix class for some work I am doing. For the sparse structures, I used pointers, e.g. int* rowInd = new int[numNonZero]. For the class I wrote copy and move assignment operators and all works fine. Reading about the move and copy semantics online, I have tangentially found an overwhelming opinion that in modern C++ I should probably not be using raw pointers. If this is the case, then I would like to modify my code to use vectors for good coding practice. I mostly have read vectors over raw pointers. Is there any reason not to change to vectors? If I change the data to be stored in vectors instead of new[] arrays, do I still need to manually write copy/move assignment and constructor operators for classes? Are there any important differences between vector and new[] move/copy operators? Suppose I have a class called Levels, which contains several sparse matrix variables. I would like a function to create a vector of Levels, and return it: vector<Levels> GetGridLevels(int &n, ... ) { vector<Levels> grids(n); \\ ... Define matrix variables for each Level object in grids ... return grids; } Will move semantics prevent this from being an expensive copy? I would think so, but it's a vector of objects containing objects containing member vector variables, which seems like a lot... A: Yes, use std::vector<T> instead of raw T *. Also yes, the compiler will generate copy and move assignment operators for you and those will very likely have optimal performance, so don't write your own. If you want to be explicit, you can say that you want the generated defaults: struct S { std::vector<int> numbers {}; // I want a default copy constructor S(const S&) = default; // I want a default move constructor S(S &&) noexcept = default; // I want a default copy-assignment operator S& operator=(const S&) = default; // I want a default move-assignment operator S& operator=(S&&) noexcept = default; }; Regarding your last question, if I understand correctly, you mean whether returning a move-aware type by-value will be efficient. Yes, it will. To get the most out of your compiler's optimizations, follow these rules: Return by-value (not by const value, this will inhibit moving). Don't return std::move(x), just return x (at least if your return type is decltype(x)) so not to inhibit copy elision. If you have more than one return statement, return the same object on every path to facilitate named return value optimization (NRVO). std::string good(const int a) { std::string answer {}; if (a % 7 > 3) answer = "The argument modulo seven is greater than three."; else answer = "The argument modulo seven is less than or equal to three."; return answer; } std::string not_so_good(const int a) { std::string answer {"The argument modulo seven is less than or equal to three."}; if (a % 7 > 3) return "The argument modulo seven is greater than three."; return answer; } For those types where you write move constructors and assignment operators, make sure to declare them noexcept or some standard library containers (notably std::vector) will refuse to use them.
{ "pile_set_name": "StackExchange" }
Q: My OLED 128x64 0.96 inch(with SSD1306 driver) doesn't work! I'm working to use of this OLED but I don't know why doesn't it work!? the Schematic of adaptor is this: and this is assembeled project on breadboard: when I check out the pins of SPI of microcontroller(by Logic Analyzer - saleae), I see these: and my Codes is this: /***************************************************** Project : OLED Date : 03/14/2014 Author : Roh Chip type : ATmega32A Program type : Application AVR Core Clock frequency: 16.000000 MHz Memory model : Small External RAM size : 0 Data Stack size : 512 *****************************************************/ #include <mega32a.h> #include <delay.h> // SPI functions #include <spi.h> #define Brightness 0xCF #define DC PORTA.0 #define RST PORTA.1 // Declare your global variables here void OLED_Init_I(); void Fill_RAM(unsigned char Data); void main(void) { // Port A initialization // Func7=In Func6=In Func5=In Func4=In Func3=In Func2=Out Func1=Out Func0=Out // State7=T State6=T State5=T State4=T State3=T State2=0 State1=0 State0=0 PORTA=0x00; DDRA=0x07; // Port B initialization // Func7=Out Func6=Out Func5=Out Func4=Out Func3=In Func2=In Func1=In Func0=In // State7=0 State6=0 State5=0 State4=0 State3=T State2=T State1=T State0=T PORTB=0x00; DDRB=0xF0; PORTC=0x00; DDRC=0x00; PORTD=0x00; DDRD=0x00; // SPI initialization // SPI Type: Master // SPI Clock Rate: 4000.000 kHz // SPI Clock Phase: Cycle Start // SPI Clock Polarity: Low // SPI Data Order: MSB First SPCR=0x50; SPSR=0x00; OLED_Init_I(); while (1) { Fill_RAM(0xFF); delay_ms(1000); Fill_RAM(0x00); delay_ms(1000); // Place your code here } } void spi_transfer_nr(unsigned char data) { DC=0; SPDR = data; while(!(SPSR & (1<<SPIF))); } void spi_transfer_nr1(unsigned char data) { DC=1; SPDR = data; while(!(SPSR & (1<<SPIF))); } void Set_Display_On_Off(unsigned char d) { spi_transfer_nr(0xAE|d); // Set Display On/Off // Default => 0xAE // 0xAE (0x00) => Display Off // 0xAF (0x01) => Display On } void Set_Display_Clock(unsigned char d) { spi_transfer_nr(0xD5); // Set Display Clock Divide Ratio / Oscillator Frequency spi_transfer_nr(d); // Default => 0x80 // D[3:0] => Display Clock Divider // D[7:4] => Oscillator Frequency } void Set_Multiplex_Ratio(unsigned char d) { spi_transfer_nr(0xA8); // Set Multiplex Ratio spi_transfer_nr(d); // Default => 0x3F (1/64 Duty) } void Set_Display_Offset(unsigned char d) { spi_transfer_nr(0xD3); // Set Display Offset spi_transfer_nr(d); // Default => 0x00 } void Set_Start_Line(unsigned char d) { spi_transfer_nr(0x40|d); // Set Display Start Line // Default => 0x40 (0x00) } void Set_Charge_Pump(unsigned char d) { spi_transfer_nr(0x8D); // Set Charge Pump spi_transfer_nr(0x10|d); // Default => 0x10 // 0x10 (0x00) => Disable Charge Pump // 0x14 (0x04) => Enable Charge Pump } void Set_Addressing_Mode(unsigned char d) { spi_transfer_nr(0x20); // Set Memory Addressing Mode spi_transfer_nr(d); // Default => 0x02 // 0x00 => Horizontal Addressing Mode // 0x01 => Vertical Addressing Mode // 0x02 => Page Addressing Mode } void Set_Segment_Remap(unsigned char d) { spi_transfer_nr(0xA0|d); // Set Segment Re-Map // Default => 0xA0 // 0xA0 (0x00) => Column Address 0 Mapped to SEG0 // 0xA1 (0x01) => Column Address 0 Mapped to SEG127 } void Set_Common_Remap(unsigned char d) { spi_transfer_nr(0xC0|d); // Set COM Output Scan Direction // Default => 0xC0 // 0xC0 (0x00) => Scan from COM0 to 63 // 0xC8 (0x08) => Scan from COM63 to 0 } void Set_Common_Config(unsigned char d) { spi_transfer_nr(0xDA); // Set COM Pins Hardware Configuration spi_transfer_nr(0x02|d); // Default => 0x12 (0x10) // Alternative COM Pin Configuration // Disable COM Left/Right Re-Map } void Set_Contrast_Control(unsigned char d) { spi_transfer_nr(0x81); // Set Contrast Control spi_transfer_nr(d); // Default => 0x7F } void Set_Precharge_Period(unsigned char d) { spi_transfer_nr(0xD9); // Set Pre-Charge Period spi_transfer_nr(d); // Default => 0x22 (2 Display Clocks [Phase 2] / 2 Display Clocks [Phase 1]) // D[3:0] => Phase 1 Period in 1~15 Display Clocks // D[7:4] => Phase 2 Period in 1~15 Display Clocks } void Set_VCOMH(unsigned char d) { spi_transfer_nr(0xDB); // Set VCOMH Deselect Level spi_transfer_nr(d); // Default => 0x20 (0.77*VCC) } void Set_Entire_Display(unsigned char d) { spi_transfer_nr(0xA4|d); // Set Entire Display On / Off // Default => 0xA4 // 0xA4 (0x00) => Normal Display // 0xA5 (0x01) => Entire Display On } void Set_Inverse_Display(unsigned char d) { spi_transfer_nr(0xA6|d); // Set Inverse Display On/Off // Default => 0xA6 // 0xA6 (0x00) => Normal Display // 0xA7 (0x01) => Inverse Display On } void Set_Start_Column(unsigned char d) { spi_transfer_nr(0x00+d%16); // Set Lower Column Start Address for Page Addressing Mode // Default => 0x00 spi_transfer_nr(0x10+d/16); // Set Higher Column Start Address for Page Addressing Mode // Default => 0x10 } void Set_Start_Page(unsigned char d) { spi_transfer_nr(0xB0|d); // Set Page Start Address for Page Addressing Mode // Default => 0xB0 (0x00) } void Fill_RAM(unsigned char Data) { unsigned char i,j; for(i=0;i<8;i++) { Set_Start_Page(i); Set_Start_Column(0x00); for(j=0;j<128;j++) { spi_transfer_nr1(Data); } } } void OLED_Init_I() // VCC Generated by Internal DC/DC Circuit { unsigned char i; RST=0; for(i=0;i<200;i++) { delay_us(200); //uDelay(200); } RST=1; Set_Display_On_Off(0x00); // Display Off (0x00/0x01) Set_Display_Clock(0x80); // Set Clock as 100 Frames/Sec Set_Multiplex_Ratio(0x3F); // 1/64 Duty (0x0F~0x3F) Set_Display_Offset(0x00); // Shift Mapping RAM Counter (0x00~0x3F) Set_Start_Line(0x00); // Set Mapping RAM Display Start Line (0x00~0x3F) Set_Charge_Pump(0x04); // Enable Embedded DC/DC Converter (0x00/0x04) Set_Addressing_Mode(0x02); // Set Page Addressing Mode (0x00/0x01/0x02) Set_Segment_Remap(0x01); // Set SEG/Column Mapping (0x00/0x01) Set_Common_Remap(0x08); // Set COM/Row Scan Direction (0x00/0x08) Set_Common_Config(0x10); // Set Sequential Configuration (0x00/0x10) Set_Contrast_Control(Brightness); // Set SEG Output Current Set_Precharge_Period(0xF1); // Set Pre-Charge as 15 Clocks & Discharge as 1 Clock Set_VCOMH(0x40); // Set VCOM Deselect Level Set_Entire_Display(0x00); // Disable Entire Display On (0x00/0x01) Set_Inverse_Display(0x00); // Disable Inverse Display On (0x00/0x01) Fill_RAM(0x00); // Clear Screen Set_Display_On_Off(0x01); // Display On (0x00/0x01) } I used the charge-pump. then the power of OLED is: 4volt to Vbat 3volt to Vdd I have used the SPI(4 wire mode. for more information you can see the datasheet and command files) SAS1-9046-B UG-2864HSWEG01-Univision.pdf UG-2864HSWEG01 Drawing - 090120B.pdf UG-2864HSWEG01 user guide.pdf in your opinion, what's the problem? A: Interfacing to displays is hard work. Without spending hours looking at your list I won't figure it out from here. In order of importance Double check voltages. Quadruple check the schematic and connections. Use known good code when possible. If code can't be found, Do one step and a time. Either way (#3 or #4) Start with reading a value from the display, then proceed to the next step, set bias, etc. Once every i is dotted, and every t crossed, they usually work.
{ "pile_set_name": "StackExchange" }
Q: Python and Selenium - get text excluding child node's text Using Python 3. Supposing: <whatever> text <subchild> other </subchild> </whatever> If I do: elem = driver.find_element_by_xpath("//whatever") elem.text contains "text other" If I do: elem = driver.find_element_by_xpath("//whatever/text()[normalize-space()]") elem is not Webelement. How my I proceed to grab only "text" (and not "other")? Id est: grab only text in direct node, not the child nodes. UPDATE: Original HTML is: <div class="border-ashes the-code text-center"> VIVEGRPN <span class="cursor"></span> <button class="btn btn-ashes zclip" data-clipboard-target=".the-code" data-coupon-code="VklWRUdSUE4="> <span class="r">Hen, la.</span> </div> A: You can remove the child node text from the all text all_text = driver.find_element_by_xpath("//whatever").text child_text = driver.find_element_by_xpath("//subchild").text parent_text = all_text.replace(child_text, '') A: I had similar problem recently, where selenium always gave me all the text inside the element including the spans. I ended up splitting the string with newline "\n". for e.g. all_text = driver.find_element_by_xpath(xpath).text req_text = str.split(str(all_text ), "\n")[0] A: Bear in mind that the replacement approach mentioned by @Guy doesn't work for many structures. For instance, having this structure: <div> Hello World <b>e</b> </div> The parent text would be Hello World e, the child text would be e, and the replacement would result in Hllo World instead of Hello World. A safe solution To get the own text of an element in a safe manner, you have to iterate over the children of the node, and concat the text nodes. Since you can't do that in pure Selenium, you have to execute JS code. OWN_TEXT_SCRIPT = "var r='';var C=arguments[0].childNodes;for(var n=0;n<C.length;n++){if(C[n].nodeType==Node.TEXT_NODE){r+=' '+C[n].nodeValue}}return r.trim()" parent_text = driver.execute_script(OWN_TEXT_SCRIPT, elem) The script is a minified version of this simple function: var res = ''; var children = arguments[0].childNodes; for (var n = 0; n < children.length; n++) { if (children[n].nodeType == Node.TEXT_NODE) { res += ' ' + children[n].nodeValue; } } return res.trim();
{ "pile_set_name": "StackExchange" }
Q: I've deleted _viewstart file I've deleted my _viewstart file, but I'm worried because my application keeps running okay. I've noticed this problem when I tried to include a style sheet at my app. Then my questions are: 1 - I must to create a _viewstart file, or I have to recover my _viewstart deleted file? 2 - How can I add a css to my views? PS.: Please, if you need some code ask me in comments. A: Answering your questions: 1) If you didn't created your own custom _Layout.cshtml file then you can recover it or just add new file _ViewStart.cshtml with following code in it: @{ Layout = "~/Views/Shared/_Layout.cshtml"; } If you got your own _layout then you obviously have to create it again (if you want to): @{ Layout = "~/Views/Shared/_MyAwesomeLayout.cshtml"; } If you don't use a _ViewStart.cshtml file in your project then you have to specify in every View file the path of your _Layout.chtml file with Layout property: @{ Layout = "~/Views/Shared/_Layout.cshtml"; } But this will cause you a headache in the future. Imagine you have a 100 of View files (wich contains Layout = "~/Views/Shared/_MyAwesomeLayout.cshtml"; in it, and after a while you want to rename the name of your layout or change the location of your layout file...then you're going to find every View that refers to it...(that will be a mess :)). And here the _ViewStart.cshtml cames in..., where you can set your layout (in a single place). The ASP.NET MVC framework, when it renders a View will look for a file called _ViewStart.cshtml and the content of this file will be treated as though they were contained in the View file itself. 2) By default in MVC projects the CSS files are in Content file, so you can add your own CSS files by drag and drop in Content folder (or of course you can make your own folder structure in your project). The easy way to add a CSS file in your View is to drag and drop your CSS file from Solution Explorer in the View itself and the Visual Studio (automatically) will show the path of your CSS file (or you can add by yourself).
{ "pile_set_name": "StackExchange" }
Q: Quicksort not completely sorting provided array My Quicksort seems to stop before completely sorting the array, and I've stared myself blind on the code. I wrote the algorithm according to the related chapters in Java Software Structures - Designing and Using Data Structures (3rd Edition) Quick Sort: private static <T extends Comparable<T>> void quickSort(T[] array,int min, int max){ int pIndex; if (max-min > 0) { pIndex = partition(array, min, max); quickSort(array, min, pIndex-1); quickSort(array, pIndex+1, max); } } Partition: private static <T extends Comparable<T>> int partition(T[] array, int min, int max) { int left, right; T pivot, temp; int middle = (min+max)/2; left = min; right = max; pivot = array[middle]; while (left < right) { while (array[left].compareTo(pivot) <= 0 && left < right) left++; while (array[right].compareTo(pivot) > 0) right--; if (left<right) { temp = array[left]; array[left] = array[right]; array[right] = temp; } } temp = array[min]; array[min] = array[right]; array[right] = temp; return right; } The input: An int[10] array containing the values 0 through 9, shuffled. The quicksort-function is thus called like: quicksort(nums, 0, nums.length-1) The output (example): 0 2 1 3 7 4 5 6 8 9 As you can see, the end product seems to be somewhat on the way to a good end-product, but it's stopping prematurely somewhere. Update: None of the answers provided so far (the deleted ones included) worked. If nobody is able to spot the bug, would anyone kindly redirect me to a good source for generic algorithms in Java? I even shamefully attempted to do a pure copypaste of the Quicksort algorithm from the book mentioned above, and while it compiled and ran, it resulted in the same, "almost-correct" output as above. I then questioned whether or not it may be my input data, but nope. It is simply an Integer-array of integers, no duplicates. It's a valid candidate to my understanding. A: I was able to get quick sort to sort some test arrays with the following partition function. private static <T extends Comparable<T>> int partition(T[] array, int min, int max) { int left, right; T pivot, temp; int middle = (min+max)/2; left = min; right = max ; pivot = array[middle]; while (left < right) { while (array[left].compareTo(pivot) < 0 && left < right) left++; while (array[right].compareTo(pivot) > 0) right--; if (left<right) { temp = array[left]; array[left] = array[right]; array[right] = temp; } } return right; } All I changed was the first compareTo comparison to be less than instead of less than or equal to. This allows the pivot to move in the array. This however does mean that the array CANNOT contain duplicates. I also removed the last swap as I couldn't tell what it was doing. The problems stem from how you deal with the pivot. It doesn't actually partition the array properly. This also works and allows duplicates. private static <T extends Comparable<T>> int partition(T[] array, int min, int max) { int left, right; T pivot, temp; int middle = (min+max)/2; left = min + 1; right = max ; pivot = array[middle]; // move partition element to min index temp = array[min]; array[min] = array[middle]; array[middle] = temp; while (left < right) { while (array[left].compareTo(pivot) <= 0 && left < right) left++; while (array[right].compareTo(pivot) > 0) right--; if (left<right) { temp = array[left]; array[left] = array[right]; array[right] = temp; } } // move partition element to partition index temp = array[min]; array[min] = array[right]; array[right] = temp; return right; } I looked up a copy of the book. The comment tells you what the last swap was trying to do. Which makes my fix of adding a swap at the begging to move the partition element to the min index the correct fix.
{ "pile_set_name": "StackExchange" }
Q: I need to make the difference between two timestamp fields, start and end I need to make the difference between two timestamp fields, start and end, for example: start_date: 2019-09-20 01:15:00 final_date: 2019-09-20 01:20:15 datediff (end_date, start_date) the return i get is 0. I think it's because the day is the same, but I would like to have the differences in minutes, where in this case would be 5 minutes. Has anyone had this difficulty? A: One method is to convert to Unix timestamps: select (unix_timestamp(final_date) - unix_timestamp(start_date)) / 60 as diff_minutes
{ "pile_set_name": "StackExchange" }
Q: Prove that two subspaces are not equal under a given condition Prove or give a counterexample: If $U_1, U_2, W$ are subspaces of $V$ such that $U_1 \bigoplus W = U_2 \bigoplus W$, then $U_1 = U_2$. Proof Let $u_1+w \in U_1 \bigoplus$ W. Since $U_1\bigoplus W= U_2\bigoplus W, u_1+w \in U_2\bigoplus W$. Since $w \in U_2 \bigoplus W, -w \in U_2 \bigoplus W$. Therefore $ u_1 \in U_2 \bigoplus W $.Since $U_1$ and $W$ have no elements in common,$u_1 \not\in W$ . Therefore $u_1 \in U_2$. Therefore$ U_1 \subseteq U_2.$ Similarly other side inclusion works. Therefore $U_1=U_2$. What is wrong with this proof? A: This is not true. The error is in this line: Since $U_1$ and $W$ have no elements in common, $u_1 \not\in W$. Therefore $u_1 \in U_2$. It is not true in general that if $x \in A \oplus B$ then $x \in A$ or $x \in B$. (Perhaps you are confusing the properties of the direct sum $U_2 \oplus W$, with the properties of the union $U_2 \cup W$, which in general is not a subspace.) An instructive example is taking $A$ to be the $x$-axis in $\Bbb R^2$ and $B$ the $y$-axis. Then, $\Bbb R = A \oplus B$ but, e.g., $(1, 1)$ is in neither $A$ nor $B$.
{ "pile_set_name": "StackExchange" }
Q: Issue with compiling HTML5 code in Web-Browser i'v created demo page of mobile jquery using TextEdit...which is, <!doctype html> <html> <head> <title>My Page</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.css"> <script src="http://code.jquery.com/jquery-1.8.2.min.js"></script> <script src="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.js"></script> </head> <body> <div data-role="page"> <div data-role="header"> <h1>My Title</h1> </div><!-- /header --> <div data-role="content"> <p>Hello world</p> </div><!-- /content --> <div data-role="footer"> <h4>My Footer</h4> </div><!-- /footer --> </div><!-- /page --> </body> </html> but, in my browser code is not getting compiled and it shows these texts as it is as plain text.. and i'v confirmed that my browser support HTML5 here: http://html5test.com/ what is missing!? A: sorry but issue was weird, actually i had created that page using textEdit which stored all text as rich text format which may not recognized to be compiled as html... so i converted that text to plain text and saved it again and that worked!! thanks all.
{ "pile_set_name": "StackExchange" }
Q: Match any repetitive pattern using tcl I have a binary file that I don't know what is inside. Then, I convert it to hex number using binary scan $bin_data "H*" hex_data. The problem is how to match for any repetitive pattern (byte). Example 1: In the file: 0cabab79 Expected Output: abab Example 2: In the file: 0c1f1f03035d Expected Output: 1f1f0303 Example 3: In the file: 0c678967895d13 Expected Output: 67896789 A: You can use a more flexible regexp to get all the repeated patterns (at least 2 characters): set inputs [list 0cabab79 0c1f1f03035d 0c678967895d13] foreach input $inputs { set out "" foreach {whole sub} [regexp -all -inline {(..+)\1} $input] { append out $whole } puts $out } # Output: # abab # 1f1f0303 # 67896789 If you want to make sure the pattern are in pairs of even number of characters (i.e. aaaaaa should give aaaa and not aaaaaa), then... set inputs [list 0cabab79 0c1f1f03035d 0c678967895d13 aaaaaa] foreach input $inputs { set out "" foreach {whole sub} [regexp -all -inline {((?:..)+)\1} $input] { append out $whole } puts $out } # Output: # abab # 1f1f0303 # 67896789 # aaaa
{ "pile_set_name": "StackExchange" }
Q: Invert signal from an on/off switch I have a circuit (below) where there's an IC responsible for battery charging, voltage boosting, power/regulation, etc. It has an "Enable" pin which is pulled up to VCC by default, and determines whether it supplies power or not. (High == ON, Low == OFF) I want to hook this up to a toggle switch so that when the toggle is "open", the "Enable" pin is pulled down to ground. Is there a simple/easy way to wire this? I'd like to avoid adding any additional components if possible. Right now I have the leads connected as below, which works but is confusing because it is the opposite of the switch's labeling. (Open-switch turns the system on and closed switch turns it off). Thanks! simulate this circuit – Schematic created using CircuitLab A: simulate this circuit – Schematic created using CircuitLab Figure 1. Inverting the enable logic. Connect a milliammeter across the switch on your existing circuit and note the current to ground. Calculate the value of the internal pull-up resistor: \$ R_{PU} = \frac {V_+}{I} \$. Add a pull-down resistor of about one tenth the value of the pull-up. (Note 1.) Rewire the switch to pull high. Note that in this circuit R2 will consume a little extra power when the switch is closed. Note 1. R2 will be fighting R1 in trying to pull the input low. Most digital logic families switching point is below half-supply. e.g., One would think that a 5 V logic input would read anything below 2.5 V as 'low'. This isn't the case and the thresholds are usually defined as a guaranteed low threshold and a guaranteed high threshold. A 10:1 pull-up / pull-down ratio should guarantee a zero when the switch is open.
{ "pile_set_name": "StackExchange" }
Q: gnuplot: How to plot each line of a data file as Y and incremental X I have a data file containing 30 columns and N rows. Each rows correspond to 30 values of function f(x) for x={1,...,30}. The data file has following pattern: #<index> f(1) f(2) ... f(30) 1 7.221 5.302 ... -1.031 2 4.527 3.193 ... 0.410 ... N 6.386 1.321 ... -0.386 gnuplot interprets first column as X and the second one as Y. But, what I want is to plot each line in a separated output file without transposing this data file. For example, for the first line, the desired output would be what gnuplot gets with this input file: # X Y 1 7.221 2 5.302 ... 30 -1.031 A: I found a solution: plot "data.dat" matrix every 1::1 with linespoint matix indicates data file type by which the input file interpreted as matrix. every 1::1 skip the first column A: UPDATED based on @Christoph's comment: plot for [i=2:30] 'data.dat' using (i-1):(column(i)) with linespoint
{ "pile_set_name": "StackExchange" }
Q: 2 classes implement same interface, duplicated code I have an interface: public interface IUser { } And then 2 classes that implement this interface: public class User : IUser { } public class AdminUser : IUser { } Now the problem I see is that there is duplicate code between User and AdminUser when implementing a method in the interface. Can I introduce an abstract class that would implement the common code between User and AdminUser somehow? I don't want AdminUser to inherit from User. A: Yes. You can. public abstract class BaseUser : IUser { } public class User : BaseUser { } public class AdminUser : BaseUser { } A: Sounds like you should introduce a UserBase class that both User and AdminUser could inherit from that has the shared code class UserBase : IUser { // Shared Code } class User : UserBase { } class AdminUser : UserBase { } A: Your class User should be base class for AdminUser From the name of the classes it appears that your class User should be base class and AdminUser should inherit from that class. If that is not the case then you can create a base class for both User and AdminUser implement your interface in the base class and inherit that in User and AdminUser. public interface IUser { void SomeMethod(); } public abstract class User : IUser { public abstract void SomeMethod(); } public class AdminUser : User { public override void SomeMethod() { throw new NotImplementedException(); } } public class NormalUser : User { public override void SomeMethod() { throw new NotImplementedException(); } }
{ "pile_set_name": "StackExchange" }
Q: Swift 2 RAC4 Merge UITextField Signal and UISwitch Signal I've written a reactive-imperative version of the code: widthTextField.rac_textSignal().subscribeNext { (val) in let multiplier = 0.2 if var v = Double(val as! String){ if(self.viewModel.proportionalBool.value){ v *= multiplier self.heightTextField.text = String(v) } } } What I have in my ViewModel are three MutableProperties: proportionalBool of type Bool, heightString and widthString of type String. I also have a corresponding UISwitch and two UITextFields in my ViewController. What I wish to learn is having the following scenario: 1. If bool/switch is false, then heightString should be untouched 2. If bool is true, then heightString should be a value of: widthString * multiplier I know I've written the code in a bad way. I think I should have used combineLatest but I have no idea how to merge two signals: UITextField and UISwitch into one producing signal. Could anyone give me any hint or a simple code example? let boolSignal = proportionalSwitch.rac_newOnChannel() let widthSignal = widthTextField.rac_textSignal() let heightSignal = heightTextField.rac_textSignal() ...? A: I'm going to assume that you want always want to have the MutableProperties in your ViewModel always have the correct values. Also I'm going to use REX (which will soon be a part of RAC anyway) for simpler UI Bindings. Lets say this is your viewModel: final class ViewModel { let on = MutableProperty<Bool>(false) let width = MutableProperty<Double>(0.0) let height = MutableProperty<Double>(0.0) } The first part is binding the switch and the textfields to the MutableProperties of your viewModel. The first two are relatively straight forward: viewModel.on <~ onSwitch.rex_on viewModel.width <~ widthTextField.rex_textSignal .map { Double($0) ?? 0 } Note: I've chosen to send 0 as width if the input of the width textfield is not a valid number. Depending on your needs, you might want to handle this case differently, e.g. by having the width and height properties have optional values... Now the height is almost the same, but we have to make sure its only processed while the switch is on. This is achieved by using combineLatest and filter: viewModel.height <~ combineLatest(viewModel.on.producer, viewModel.width.producer) // SignalProducer<(Bool, Double), NoError> .filter { on, text in return on } // Only send values when the switch is `on` .map { on, width in return width } // Now we dont care about the switch value anymore, extract just the width .map { width in return 0.5 * width }// Transform the width as you wish Now, all thats left is to bind the value of the height to the UI. Unless I'm missing something, theres no help from REX for that (at least not for UITextField), so we'll have to use a DynamicProperty: override func viewDidLoad() { super.viewDidLoad() // Previously mentioned binding to the viewModel DynamicProperty(object: heightTextField, keyPath: "text") <~ viewModel.height.producer.map { String($0) } }
{ "pile_set_name": "StackExchange" }
Q: Visual Studio extension custom command error: "Object does not match target type" I want to create a Visual Studio extension. More precisely an additional menu item. I used this tutorial as a guideline: Visual Studio Extensibility: Creating Visual Studio VSIX package extension The problem is after I created successfully a VSIX project, I tried to add a custom command. While the custom command is added to my project the following error occurs: After pressing "ok" a .cs file is added to my project. This file has few reference errors. I also tried to reference the source file by myself, but without success. It also gives the following output: Adding a new custom command 'Command1' to the project 'MockGenExtension': The custom command requires a VS package. No existing VS packages found in the project. A new VS package 'Command1Package' will be created for the custom command. I already reinstalled the Visual Studio and the SDK without any effect. A: An Upgrade to Visual Studio 2017 fixed the problem for me.
{ "pile_set_name": "StackExchange" }
Q: Vim inconsistently syntax highlighting bash files When I open some bash script files with vim it sometimes identifies them as conf files, that's okay, I can just correct that by setting the filetype to sh with :setf sh. That great, except I've noticed that this doesn't fix things entirely: Notice that shopt is properly highlighted on the left, but not on the right, where I manually set the filetype to sh. This means that when a file is identified as bash or sh by vim, it sets the filetype to sh but then does some extra steps that I'm not doing when I set the filetype manually. Any one know what that might be, and how I could fix it? A: vim already recognizes many file types by default. Most of them work by file extensions, but in a case like this, vim will also analyze the content of the file to guess the correct type. vim sets the filetype for specific file names like .bashrc, .tcshrc, etc. automatically. But a file with a .sh extension will be recognized as either csh, ksh or bash script. To determine what kind of script this is exactly, vim reads the first line of the file to look at the #! line. If the first line contains the word bash, the file is identified as a bash script. Usually you see #!/bin/bash if the script is meant to be executed directly, for some other shell configuration file you should use the file extensions .bash. The help in vim explains this as well at :help ft-bash-syntax. You can also use let g:is_bash=1 in your .vimrc to make bash syntax highlighting the default for all files with filetype=sh. If you want to look at the details, this is implemented in $VIMRUNTIME/filetype.vim. A: It turns out that syntax/sh.vim includes specific highlighting for Korn, Bash and sh, you just have to tell it which you're using. This is done with b:is_kornshell, b:is_bash and b:is_sh respectively. Depending on the situation I figure I'll use the following: ftdetect/bash.vim: au BufRead,BufNewFile *bash* let g:is_bash=1 au BufRead,BufNewFile *bash* setf sh Modeline: # vim:let g:is_bash=1:set filetype=sh: Key Mapping nmap <silent> <leader>b :let g:is_bash=1<cr> :setf sh<cr> A: Similar to Peter Coulton's solution and documented as well as an alternative in the section "new-filetype" of the "filetype" Vim help the ~/.vim/filetype.vim file could contain the following code: if exists("did_load_filetypes") finish endif augroup filetypedetect au! BufRead,BufNewFile *bash* let b:is_bash = 1 | setfiletype sh augroup END This approach has the following implications: There is one ~/.vim/filetype.vim file instead of one for each file type under the ~/.vim/ftdetect directory. The b:is_bash variable is set local to the buffer as opposed to global by referring to it as g:is_bash.
{ "pile_set_name": "StackExchange" }
Q: Do there exist any compilers with localized versions of programming languages? I have often wondered why it is that non-English speaking programmers are forced to use a different language when programming when it would seem to be so easy to offer an IDE that could replace keywords with localized versions. Why can't the Germans use a "während..macht" loop? Do programmers in Japan, Germany, France, Spain, Botswana just make extensive use of macros/define statements to make life more tolerable or do they just get used to the functional significance of print, if, then, while, do, begin, end, var, double, function, etc? Perhaps the increased use of frameworks (J2EE/.NET) makes this more complicated, but it still seems worthwhile. On the other hand, if Klingon became the de-facto programming language in the US I'd probably regret suggesting this. A: In most programming languages, keywords are reserved, so they can't be used for variable names etc. Now suppose the keywords changed every time you changed culture - code written in one culture couldn't be ported to another without changing identifiers. Ick. Furthermore, when anyone copied their code onto a question forum like this, we'd no longer be speaking the same language, as it were. There are distinct advantages to only having one culture in the programming language itself... A: This sort of thing isn't unique to computer languages. All the control words for music are in Italian (andante, allegro, crescendo, etc.). This has worked well for a long time. Besides, it allows programs to be shared more easily. Suppose you were trying to integrate a function from a Finnish programmer into a module in French, and wanted to send it for further integration to your Australian colleague. A: The French (and, IIRC, German and some other languages) version of Office once has a localized version of VBA. They pulled it off, because it was a very bad idea! It is OK for casual users, making occasional use of macros, but as soon as you start searching information on Internet, want to share your code, etc., it is a nightmare. Not to mention opening a French worksheet in a Spanish Excel... (although I suppose they saved bytecode, not literals - so say running a German macro copied somewhere on a French Excel). VB (and some other languages, like Lua) allows to use identifiers with accents, etc. I recall I used in intensively a long time ago. It looks odd now, and again, it makes very hard to share code. Similarly, I am uneasy when I see code with Spanish or Chinese comments... For the record, in the time of 8bit computers, a French computer (TO8) has a French version of Basic: instead of WHILE ... WEND, we had FAIRE ... JUSQUA (or something similar). Anyway, such localized computer languages are quite scarce now... For better or for worse, English is the lingua franca of computer science. At least it is not the hardest language to learn. And the vocabulary of most languages (at least the keyword set) is quite limited. The only problem is when we try to teach programming to young people not knowing English, but they learn fast.
{ "pile_set_name": "StackExchange" }
Q: Navigation in Wordpress Good afternoon, I'm creating an "Areas" page on my Wordpress website with a page structure like this; Home About Us Areas - Wiltshire -- Salisbury -- Wilton - Hampshire -- Andover -- Portsmouth I'm looking for a way to generate all the links on the areas page with the parent of the town being the Title! For example <h2>Wiltshire</h2> <ul> <li><a href>Salisbury</a></li> <li><a href>Wilton</a></li> </ul> What is the best way to generate these links within Wordpress? A: Create the pages and then create a custom menu. Once registered add the menu items. Most themes have a navigation menu up the top. You can find the code which registers it in functions.php of the theme directory. If your pages have different functionality to regular pages, consider registering a custom post type and adding those instead of regular pages.
{ "pile_set_name": "StackExchange" }
Q: Diffie Helman Key exchange with four parties I'm trying to modify an example Deffie Helman key exchange between three parties. Here is the Code. // Alice uses Carol's public key Key ac = aliceKeyAgree.doPhase(carolKpair.getPublic(), false); // Bob uses Alice's public key Key ba = bobKeyAgree.doPhase(aliceKpair.getPublic(), false); // Carol uses Bob's public key Key cb = carolKeyAgree.doPhase(bobKpair.getPublic(), false); Key sc = saraKeyAgree.doPhase(carolKpair.getPublic(), false); // Alice uses Carol's result from above aliceKeyAgree.doPhase(cb, true); // Bob uses Alice's result from above bobKeyAgree.doPhase(ac, true); // Carol uses Bob's result from above carolKeyAgree.doPhase(ba, true); saraKeyAgree.doPhase(sc,true); // Alice, Bob and Carol compute their secrets byte[] aliceSharedSecret = aliceKeyAgree.generateSecret(); System.out.println("Alice secret: " + toHexString(aliceSharedSecret)); byte[] bobSharedSecret = bobKeyAgree.generateSecret(); System.out.println("Bob secret: " + toHexString(bobSharedSecret)); byte[] carolSharedSecret = carolKeyAgree.generateSecret(); System.out.println("Carol secret: " + toHexString(carolSharedSecret)); byte[] saraSharedSecret = saraKeyAgree.generateSecret(); System.out.println("Sara secret: " + toHexString(saraSharedSecret)); // Compare Alice and Bob if (!java.util.Arrays.equals(aliceSharedSecret, bobSharedSecret)) throw new Exception("Alice and Bob differ"); System.out.println("Alice and Bob are the same"); // Compare Bob and Carol if (!java.util.Arrays.equals(bobSharedSecret, carolSharedSecret)) throw new Exception("Bob and Carol differ"); System.out.println("Bob and Carol are the same"); At the end of this, only 3 of the results match and the fourth one is different. What've I done wrong here? A: Updated Answer I'm still no cryptographer, so I've learnt a lot doing this, thank you! I've rewritten the logic, the entire example is posted below for anyone that stumbles across this later on. It's also been tested in the sandbox over at Compile Java I'll attempt to explain what's happening here, although if anyone reading this notices any gaping flaws in my implementation/explanation, please let me know. I can't say I entirely understand either it or the Java API used so I'd very much appreciate any clarification. Explanation This uses some clever maths, most of which is taken care of by the underlying APIs, we just need to tell it what to do, in the right order with the right values. A generator g and modulus p are chosen and shared between all participants. Alice, Bob, Carol and Sara choose private keys, (A, B, C and S) and compute their public keys (gA, gB, gC, gS). These are worked out from g raised to the power of their private keys, modulo p. Each party needs to send the result of their operation to the next party along, and each party needs to perform n-1 operations using a value passed from another party, where n is the number of parties. At the end of this, every party will have raised g by the power of everyone else's private key modulo p, without ever revealing to each other what their private keys are, using a process and pass method. On the first pass, each participant computes an intermediate value (gAB, gBC etc) by raising their public keys by the power of the public key of the participant to their left, modulo p. On passes 2+, they repeat this process, but using the result of the previous operation from the person on their left, raising that result to the power of their own private key, modulo p. This pass-and-compute process repeats until each person has computed gABCS, which becomes the shared secret. Due to the way maths works (The Law of Exponents if I'm not mistaken), gABCS = gBCSA = gCSAB = gSABC etc An evesdropper, Eve would be able to see the values of gA, gB, gC, gS, gAB, gBC, gCS, gSA, gABC, gBCS, gCSA, but cannot use any combination of these to efficiently reproduce gABCS, as they don't know the values of A, B, C or S, as these are the private keys that are never transmitted. This in theory could scale to more participants. By following the pattern in the code below. You'd add another participant, add them to the list of operations in each pass and add one more pass to ensure that everyone was doing the required number of operations. I've added example code for four and five participants below. Example with four participants import java.security.*; import java.security.spec.*; import javax.crypto.*; import javax.crypto.spec.*; import javax.crypto.interfaces.*; /* * This program executes the Diffie-Hellman key agreement protocol between * 4 parties: Alice, Bob, Carol and Sara using a shared 2048-bit DH parameter. */ public class DHKeyAgreement4 { private DHKeyAgreement4() {} public static void main(String argv[]) throws Exception { // Alice creates her own DH key pair with 2048-bit key size KeyPairGenerator aliceKpairGen = KeyPairGenerator.getInstance("DH"); aliceKpairGen.initialize(2048); KeyPair aliceKpair = aliceKpairGen.generateKeyPair(); // This DH parameters can also be constructed by creating a // DHParameterSpec object using agreed-upon values DHParameterSpec dhParamShared = ((DHPublicKey)aliceKpair.getPublic()).getParams(); // Bob creates his own DH key pair using the same params KeyPairGenerator bobKpairGen = KeyPairGenerator.getInstance("DH"); bobKpairGen.initialize(dhParamShared); KeyPair bobKpair = bobKpairGen.generateKeyPair(); // Carol creates her own DH key pair using the same params KeyPairGenerator carolKpairGen = KeyPairGenerator.getInstance("DH"); carolKpairGen.initialize(dhParamShared); KeyPair carolKpair = carolKpairGen.generateKeyPair(); // Carol creates her own DH key pair using the same params KeyPairGenerator saraKpairGen = KeyPairGenerator.getInstance("DH"); saraKpairGen.initialize(dhParamShared); KeyPair saraKpair = saraKpairGen.generateKeyPair(); //Alice initialize KeyAgreement aliceKeyAgree = KeyAgreement.getInstance("DH"); //Alice computes gA aliceKeyAgree.init(aliceKpair.getPrivate()); //Bob initialize KeyAgreement bobKeyAgree = KeyAgreement.getInstance("DH"); //Bob computes gB bobKeyAgree.init(bobKpair.getPrivate()); //Carol initialize KeyAgreement carolKeyAgree = KeyAgreement.getInstance("DH"); //Carol computes gC carolKeyAgree.init(carolKpair.getPrivate()); //Sara initialize KeyAgreement saraKeyAgree = KeyAgreement.getInstance("DH"); //Sara computes gS saraKeyAgree.init(saraKpair.getPrivate()); //First Pass //Alice computes gSA Key gSA = aliceKeyAgree.doPhase(saraKpair.getPublic(), false); //Bob computes gAB Key gAB = bobKeyAgree.doPhase(aliceKpair.getPublic(), false); //Carol computes gBC Key gBC = carolKeyAgree.doPhase(bobKpair.getPublic(), false); //Sara computes gCS Key gCS = saraKeyAgree.doPhase(carolKpair.getPublic(), false); //Second Pass //Alice computes gCSA Key gCSA = aliceKeyAgree.doPhase(gCS, false); //Bob computes gSAB Key gSAB = bobKeyAgree.doPhase(gSA, false); //Carol computes gABC Key gABC = carolKeyAgree.doPhase(gAB, false); //Sara computes gBCS Key gBCS = saraKeyAgree.doPhase(gBC, false); //Third Pass //Alice computes gBCSA Key gBCSA = aliceKeyAgree.doPhase(gBCS, true); //This is Alice's secret //Bob computes gCSAB Key gCSAB = bobKeyAgree.doPhase(gCSA, true); //This is Bob's secret //Sara Computes gABCS Key gABCS = saraKeyAgree.doPhase(gABC, true); //This is Sara's secret //Carol computes gSABC Key gSABC = carolKeyAgree.doPhase(gSAB, true); //This is Carol's secret // Alice, Bob, Carol and Sara compute their secrets byte[] aliceSharedSecret = aliceKeyAgree.generateSecret(); System.out.println("Alice secret: " + toHexString(aliceSharedSecret)); byte[] bobSharedSecret = bobKeyAgree.generateSecret(); System.out.println("Bob secret: " + toHexString(bobSharedSecret)); byte[] carolSharedSecret = carolKeyAgree.generateSecret(); System.out.println("Carol secret: " + toHexString(carolSharedSecret)); byte[] saraSharedSecret = saraKeyAgree.generateSecret(); System.out.println("Sara secret: " + toHexString(saraSharedSecret)); // Compare Alice and Bob if (!java.util.Arrays.equals(aliceSharedSecret, bobSharedSecret)) System.out.println("Alice and Bob differ");// throw new Exception("Alice and Bob differ"); else System.out.println("Alice and Bob are the same"); // Compare Bob and Carol if (!java.util.Arrays.equals(bobSharedSecret, carolSharedSecret)) System.out.println("Bob and Carol differ");//throw new Exception("Bob and Carol differ"); else System.out.println("Bob and Carol are the same"); //Compare Carol and Sara if (!java.util.Arrays.equals(carolSharedSecret, saraSharedSecret)) System.out.println("Carol and Sara differ");//throw new Exception("Carol and Sara differ"); else System.out.println("Carol and Sara are the same"); } /* * Converts a byte to hex digit and writes to the supplied buffer */ private static void byte2hex(byte b, StringBuffer buf) { char[] hexChars = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' }; int high = ((b & 0xf0) >> 4); int low = (b & 0x0f); buf.append(hexChars[high]); buf.append(hexChars[low]); } /* * Converts a byte array to hex string */ private static String toHexString(byte[] block) { StringBuffer buf = new StringBuffer(); int len = block.length; for (int i = 0; i < len; i++) { byte2hex(block[i], buf); if (i < len-1) { buf.append(":"); } } return buf.toString(); } } Example with five participants import java.security.*; import java.security.spec.*; import javax.crypto.*; import javax.crypto.spec.*; import javax.crypto.interfaces.*; /* * This program executes the Diffie-Hellman key agreement protocol between * 5 parties: Alice, Bob, Carol, Sara and Dave using a shared 2048-bit DH parameter. */ public class DHKeyAgreement5 { private DHKeyAgreement5() {} public static void main(String argv[]) throws Exception { // Alice creates her own DH key pair with 2048-bit key size KeyPairGenerator aliceKpairGen = KeyPairGenerator.getInstance("DH"); aliceKpairGen.initialize(2048); KeyPair aliceKpair = aliceKpairGen.generateKeyPair(); // This DH parameters can also be constructed by creating a // DHParameterSpec object using agreed-upon values DHParameterSpec dhParamShared = ((DHPublicKey)aliceKpair.getPublic()).getParams(); // Bob creates his own DH key pair using the same params KeyPairGenerator bobKpairGen = KeyPairGenerator.getInstance("DH"); bobKpairGen.initialize(dhParamShared); KeyPair bobKpair = bobKpairGen.generateKeyPair(); // Carol creates her own DH key pair using the same params KeyPairGenerator carolKpairGen = KeyPairGenerator.getInstance("DH"); carolKpairGen.initialize(dhParamShared); KeyPair carolKpair = carolKpairGen.generateKeyPair(); // Sara creates her own DH key pair using the same params KeyPairGenerator saraKpairGen = KeyPairGenerator.getInstance("DH"); saraKpairGen.initialize(dhParamShared); KeyPair saraKpair = saraKpairGen.generateKeyPair(); // Dave creates her own DH key pair using the same params KeyPairGenerator daveKpairGen = KeyPairGenerator.getInstance("DH"); daveKpairGen.initialize(dhParamShared); KeyPair daveKpair = daveKpairGen.generateKeyPair(); //Alice initialize KeyAgreement aliceKeyAgree = KeyAgreement.getInstance("DH"); //Alice computes gA aliceKeyAgree.init(aliceKpair.getPrivate()); //Bob initialize KeyAgreement bobKeyAgree = KeyAgreement.getInstance("DH"); //Bob computes gB bobKeyAgree.init(bobKpair.getPrivate()); //Carol initialize KeyAgreement carolKeyAgree = KeyAgreement.getInstance("DH"); //Carol computes gC carolKeyAgree.init(carolKpair.getPrivate()); //Sara initialize KeyAgreement saraKeyAgree = KeyAgreement.getInstance("DH"); //Sara computes gS saraKeyAgree.init(saraKpair.getPrivate()); //Dave initialize KeyAgreement daveKeyAgree = KeyAgreement.getInstance("DH"); //Sara computes gS daveKeyAgree.init(daveKpair.getPrivate()); //First Pass //Alice computes gDA Key gDA = aliceKeyAgree.doPhase(daveKpair.getPublic(), false); //Bob computes gAB Key gAB = bobKeyAgree.doPhase(aliceKpair.getPublic(), false); //Carol computes gBC Key gBC = carolKeyAgree.doPhase(bobKpair.getPublic(), false); //Sara computes gCS Key gCS = saraKeyAgree.doPhase(carolKpair.getPublic(), false); //Dave computed gSD Key gSD = daveKeyAgree.doPhase(saraKpair.getPublic(), false); //Second Pass //Alice computes gSDA Key gSDA = aliceKeyAgree.doPhase(gSD, false); //Bob computes gDAB Key gDAB = bobKeyAgree.doPhase(gDA, false); //Carol computes gABC Key gABC = carolKeyAgree.doPhase(gAB, false); //Sara computes gBCS Key gBCS = saraKeyAgree.doPhase(gBC, false); //Dave computes gCSD Key gCSD = daveKeyAgree.doPhase(gCS, false); //Third Pass //Alice computes gCSDA Key gCSDA = aliceKeyAgree.doPhase(gCSD, false); //Bob computes gSDAB Key gSDAB = bobKeyAgree.doPhase(gSDA, false); //Carol computes gDABC Key gDABC = carolKeyAgree.doPhase(gDAB, false); //Sara Computes gABCS Key gABCS = saraKeyAgree.doPhase(gABC, false); //Dave computes gBCSC Key gBCSD = daveKeyAgree.doPhase(gBCS, false); //Fourth Pass //Alice computes gBCSDA Key gBCSDA = aliceKeyAgree.doPhase(gBCSD, true); //This is Alice's secret //Bob computes gSDABC Key gCSDAB = bobKeyAgree.doPhase(gCSDA, true); //This is Bob's secret //Carol computes gSABC Key gSDABC = carolKeyAgree.doPhase(gSDAB, true); //This is Carol's secret //Sara Computes gABCS Key gDABCS = saraKeyAgree.doPhase(gDABC, true); //This is Sara's secret Key gABCSD = daveKeyAgree.doPhase(gABCS, true); //This is Dave's secret // Alice, Bob, Carol and Sara compute their secrets byte[] aliceSharedSecret = aliceKeyAgree.generateSecret(); System.out.println("Alice secret: " + toHexString(aliceSharedSecret)); byte[] bobSharedSecret = bobKeyAgree.generateSecret(); System.out.println("Bob secret: " + toHexString(bobSharedSecret)); byte[] carolSharedSecret = carolKeyAgree.generateSecret(); System.out.println("Carol secret: " + toHexString(carolSharedSecret)); byte[] saraSharedSecret = saraKeyAgree.generateSecret(); System.out.println("Sara secret: " + toHexString(saraSharedSecret)); byte[] daveSharedSecret = daveKeyAgree.generateSecret(); System.out.println("Dave secret: " + toHexString(daveSharedSecret)); // Compare Alice and Bob if (!java.util.Arrays.equals(aliceSharedSecret, bobSharedSecret)) System.out.println("Alice and Bob differ");// throw new Exception("Alice and Bob differ"); else System.out.println("Alice and Bob are the same"); // Compare Bob and Carol if (!java.util.Arrays.equals(bobSharedSecret, carolSharedSecret)) System.out.println("Bob and Carol differ");//throw new Exception("Bob and Carol differ"); else System.out.println("Bob and Carol are the same"); //Compare Carol and Sara if (!java.util.Arrays.equals(carolSharedSecret, saraSharedSecret)) System.out.println("Carol and Sara differ");//throw new Exception("Carol and Sara differ"); else System.out.println("Carol and Sara are the same"); //Compare Sara and Dave if (!java.util.Arrays.equals(saraSharedSecret, daveSharedSecret)) System.out.println("Sara and Dave differ");//throw new Exception("Carol and Sara differ"); else System.out.println("Sara and Dave are the same"); } /* * Converts a byte to hex digit and writes to the supplied buffer */ private static void byte2hex(byte b, StringBuffer buf) { char[] hexChars = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' }; int high = ((b & 0xf0) >> 4); int low = (b & 0x0f); buf.append(hexChars[high]); buf.append(hexChars[low]); } /* * Converts a byte array to hex string */ private static String toHexString(byte[] block) { StringBuffer buf = new StringBuffer(); int len = block.length; for (int i = 0; i < len; i++) { byte2hex(block[i], buf); if (i < len-1) { buf.append(":"); } } return buf.toString(); } }
{ "pile_set_name": "StackExchange" }
Q: Bug in parsing JSON I am trying to parse a json from a https request but there is a bug i can't find. Here is the code for the class that takes as input a json sting and return a list of objects. package com.example.ryzen.bakingapp; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.List; public class JSONconvert { private static final String RECIPE_ID = "id"; private static final String RECIPE_NAME = "name"; private static final String INGREDIENTS = "ingredients"; private static final String SERVINGS = "servings"; private static final String IMAGE = "image"; private static final String QUANTITY = "quantity"; private static final String MEASURE = "measure"; private static final String INGREDIENT = "ingredient"; private static final String STEP = "steps"; private static final String STEP_ID = "id"; private static final String SHORT_DESCRIPTION = "shortDescription"; private static final String DESCRIPTION = "description"; private static final String VIDEO_URL = "videoURL"; private static final String THUMBNAIL = "thumbnailURL"; public static List<Recipe> convert (String json) { List<Recipe> recipesList = new ArrayList<>(); int recipeId = 0; String name = ""; int servings = 0; String image = ""; List<Steps> steps = new ArrayList<>(); String thumbnailURL = ""; String videoURL = ""; String description = ""; String shortDescription = ""; int stepId = 0; List<Ingredients> ingredients = new ArrayList<>(); float quantity = 0; String measure = ""; String ingredient = ""; try { JSONArray baseJsonArray = new JSONArray(json); for (int i = 0; i < baseJsonArray.length(); i++) { ingredients.clear(); steps.clear(); JSONObject recipeObject = baseJsonArray.getJSONObject(i); recipeId = recipeObject.getInt(RECIPE_ID); name = recipeObject.getString(RECIPE_NAME); servings = recipeObject.getInt(SERVINGS); image = recipeObject.getString(IMAGE); JSONArray ingredientsArray = recipeObject.getJSONArray(INGREDIENTS); for (int j = 0; j < ingredientsArray.length(); j++) { JSONObject ingredientObject = ingredientsArray.getJSONObject(j); quantity = ingredientObject.getInt(QUANTITY); measure = ingredientObject.getString(MEASURE); ingredient = ingredientObject.getString(INGREDIENT); ingredients.add(new Ingredients(quantity,measure,ingredient)); } JSONArray stepArray = recipeObject.getJSONArray(STEP); for (int k = 0; k < stepArray.length(); k++) { JSONObject stepsObject = stepArray.getJSONObject(k); stepId = stepsObject.getInt(STEP_ID); shortDescription = stepsObject.getString(SHORT_DESCRIPTION); description = stepsObject.getString(DESCRIPTION); videoURL = stepsObject.getString(VIDEO_URL); thumbnailURL = stepsObject.getString(THUMBNAIL); steps.add(new Steps(stepId, shortDescription,description,videoURL,thumbnailURL)); } recipesList.add(new Recipe(recipeId, name, servings, image, ingredients, steps)); } } catch (JSONException e) { e.printStackTrace(); } return recipesList; } This is the json file i am trying to parse. So according to the above my Ingredients List should contain the following: Graham Cracker crumbs unsalted butter, melted granulated sugar salt vanilla Nutella or other chocolate-hazelnut spread Mascapone Cheese(room temperature) heavy cream(cold) cream cheese(softened) Bittersweet chocolate (60-70% cacao) unsalted butter granulated sugar light brown sugar large eggs vanilla extract all purpose flour cocoa powder salt semisweet chocolate chips sifted cake flour granulated sugar baking powder salt vanilla extract, divided egg yolks whole milk unsalted butter, softened and cut into 1 in. cubes egg whites melted and cooled bittersweet or semisweet chocolate Graham Cracker crumbs unsalted butter, melted granulated sugar salt vanilla,divided cream cheese, softened large whole eggs large egg yolks heavy cream But instead i get this list of ingredients Graham Cracker crumbs unsalted butter, melted granulated sugar salt vanilla,divided cream cheese, softened large whole eggs large egg yolks heavy cream Graham Cracker crumbs unsalted butter, melted granulated sugar salt vanilla,divided cream cheese, softened large whole eggs large egg yolks heavy cream Graham Cracker crumbs unsalted butter, melted granulated sugar salt vanilla,divided cream cheese, softened large whole eggs large egg yolks heavy cream Graham Cracker crumbs unsalted butter, melted granulated sugar salt vanilla,divided cream cheese, softened large whole eggs large egg yolks heavy cream It seems that the first Ingredients object is repeated and added everytime in the Ingredients list . But i can't understand why this is happening. Do you see anything that i am missing? Thank you for your time in advance. A: it seems you are using the same list to add your ingredients each time your parse a new recipe. Since you are using ingredients.clear(), that means the reference/pointer to the list "ingredients" remain the same each time you create a new Recipe object. When you are listing your ingredients from the different recipes after this parsing, they are all the same, since they all access the same list, which of course only contains the last ingredients you found. What you should do is create a new List for each recipe, and not re-use the same one :)
{ "pile_set_name": "StackExchange" }
Q: Silverlight serialize object with cycles in object graph I'm having an issue serializing objects when sending them to my WCF services. My classes look like this. public class Foo { public Bar Bar { get; set; } } public class Bar { public Foo Bar { get; set; } } This causes a cycle in my object graph. I've fixed this on the server end by using the PreserveReferencesOperationBehavior. However, I still get an error when I try to serialize the objects in Silverlight. While I can mark my objects with [DataContract(IsReference = true)], I'd prefer not to use this method because I have a large number of classes, many of which have over 100 properties and I don't want to have to add the [DataMember] attribute to each property. Is there any other way to tell Silverlight to preserve references? If it matters at all, I am using EntityFramework 4 with Code First. A: The infered DataContract behaviour of the serializer is present to assist in the simple DTO scenarios. If you want to do it "properly" you should be using the DataContract and DataMember attributes. When you find you have anything other than the most simple of scenarios you just need to do things properly. The correct and only way to handle circular references is with IsReference. Lesson here is that helpful magic pixie dust only goes so far after that you just need to put in the graft. Sorry its not the answer you were looking for.
{ "pile_set_name": "StackExchange" }
Q: Why don't solar cells produce visible light when supplied with electricity? ... A cursory Google search didn't reveal an answer... Is the energy conversion a one-way process? A: It's not that they don't, its just very inefficient in reverse bias. Non-visible and very weak, Heat buildup, fragile silicon crystal structure. Typical Solar PV cells are made using silicon crystals just like IC silicon wafers. It's the same reason that LEDs arn't made with silicon. "Digikey: Will Silicon Substrates Push LED Lighting Into the Mainstream?" The reason why LEDs are expensive is partly because the manufacturing process used to fabricate the wafers from which the individual chips are cut is difficult and employs exotic materials such as gallium nitride (GaN) deposited on sapphire or silicon-carbide (SiC) substrates. But recently, some manufacturers have proposed using silicon, the material routinely used to fabricate billions of integrated circuits (ICs) every year, as an LED substrate. Apart from potentially reducing the cost of LEDs, the use of mature complementary metal oxide semiconductor (CMOS) IC technology would allow fabrication in conventional wafer fabs that have spare capacity. However, the idea is not new. Silicon has been tried before, but large mismatches between its crystal structure and coefficient of thermal expansion, and those of the GaN used for the LED proper created faults that lowered the end product’s efficacy and dramatically shortened its life. Now new developments promise to overcome these drawbacks.
{ "pile_set_name": "StackExchange" }
Q: Getting value from Oracle database table to UNIX variable I am trying to create a simple script that connects to a oracle database, executes a select query and store the return value into a Unix variable. Below is the script I have created by following this post: #!/bin/sh VALUE=`sqlplus -silent $DB_USERNAME/"$PASSWORD"@"(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=$HOST_NAME)(PORT=$DB_PORT)))(CONNECT_DATA=(SID=$DB_SID)))" <<END set pagesize 0 feedback off verify off heading off echo off SELECT ID FROM TEST_USERS WHERE USER_NAME=$SAMPLE_USER; exit; END` if [ -z "$VALUE" ]; then echo "No rows returned from database" exit 0 else echo $VALUE fi Now when I run this script I am facing error as : ERROR: ORA-12533: TNS:illegal ADDRESS parameters SP2-0306: Invalid option. Usage: CONN[ECT] [{logon|/|proxy} [AS {SYSDBA|SYSOPER|SYSASM}] [edition=value]] where ::= [/][@] ::= [][/][@] SP2-0306: Invalid option. Usage: CONN[ECT] [{logon|/|proxy} [AS {SYSDBA|SYSOPER|SYSASM}] [edition=value]] where ::= [/][@] ::= [][/][@] SP2-0157: unable to CONNECT to ORACLE after 3 attempts, exiting SQL*Plus Please let me know where I am doing mistake? A: Try with this VALUE variable: VALUE=`sqlplus $DB_USERNAME/$PASSWORD@//$HOST_NAME:$DB_PORT/$DB_SID` And, of course, you need to define all variables, you use there before this line
{ "pile_set_name": "StackExchange" }
Q: WCF Service with wsHttpBinding, ssl and TransportWithMessageCredential I've got wcf service with ssl communication, wsHttpBinding and Transport security, but when I try to change it to: <security mode="TransportWithMessageCredential"> <transport clientCredentialType="None" /> <message clientCredentialType="UserName"/> </security> I'm getting error: An unsecured or incorrectly secured fault was received from the other party. See the inner FaultException for the fault code and detail. I change security mode on client side and server side and I have up to date contract. I can't find any solution to this problem. Will you help me? Client.config: <?xml version="1.0" encoding="utf-8"?> <configuration> <startup><supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" /></startup> <system.serviceModel> <bindings> <wsHttpBinding> <binding name="WSHttpBinding_IDatabaseService"> <security mode="TransportWithMessageCredential"> <transport clientCredentialType="None" /> <message clientCredentialType="UserName"/> </security> </binding> </wsHttpBinding> </bindings> <client> <endpoint address="https://dbservice:3915/DatabaseService.svc" binding="wsHttpBinding" bindingConfiguration="WSHttpBinding_IDatabaseService" contract="DBService.IDatabaseService" name="WSHttpBinding_IDatabaseService"> <identity> <dns value="dbservice" /> </identity> </endpoint> </client> </system.serviceModel> </configuration> Server.config: <?xml version="1.0" encoding="utf-8"?> <configuration> <configSections> <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 --> <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=5.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" /> </configSections> <appSettings> <add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" /> </appSettings> <system.web> <compilation debug="true" targetFramework="4.5" /> <httpRuntime targetFramework="4.5" /> <!--<roleManager defaultProvider="CustomRoleProvider" enabled="true"> <providers> <clear /> <add name="CustomRoleProvider" type="CustomRoleProvider" /> </providers> </roleManager>--> <!--<membership defaultProvider="CustomMembershipProvider"> <providers> <clear /> <add name="CustomMembershipProvider" type="CustomMembershipProvider" /> </providers> </membership>--> </system.web> <system.diagnostics> <trace autoflush="true" /> <sources> <source name="System.ServiceModel" switchValue="Information, ActivityTracing" propagateActivity="true"> <listeners> <add name="sdt" type="System.Diagnostics.XmlWriterTraceListener" initializeData="SdrConfigExample.e2e" /> </listeners> </source> </sources> </system.diagnostics> <system.serviceModel> <services> <service name="DBService.DatabaseService" behaviorConfiguration="ServiceBehavior"> <endpoint address="https://dbservice:3915/DatabaseService.svc" binding="wsHttpBinding" bindingConfiguration="WSHttpBinding_IDatabaseService" contract="DBService.IDatabaseService"> <identity> <dns value="dbservice" /> </identity> </endpoint> </service> </services> <behaviors> <serviceBehaviors> <behavior name="ServiceBehavior"> <!-- To avoid disclosing metadata information, set the values below to false before deployment --> <serviceMetadata httpGetEnabled="false" httpsGetEnabled="true" /> <!-- To receive exception details in faults for debugging purposes, set the value below to true. Set to false before deployment to avoid disclosing exception information --> <serviceDebug includeExceptionDetailInFaults="true" /> <!--<serviceAuthorization principalPermissionMode="UseAspNetRoles" roleProviderName="CustomRoleProvider" />--> <serviceCredentials> <!--<userNameAuthentication userNamePasswordValidationMode="MembershipProvider" membershipProviderName="CustomMembershipProvider" />--> <serviceCertificate findValue="dbservice" storeLocation="LocalMachine" storeName="My" x509FindType="FindBySubjectName" /> </serviceCredentials> </behavior> </serviceBehaviors> </behaviors> <bindings> <wsHttpBinding> <binding name="WSHttpBinding_IDatabaseService"> <security mode="TransportWithMessageCredential"> <transport clientCredentialType="None" /> <message clientCredentialType="UserName" /> </security> </binding> </wsHttpBinding> </bindings> <protocolMapping> <add binding="wsHttpBinding" scheme="https" /> </protocolMapping> <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" /> </system.serviceModel> <entityFramework> <defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" /> </entityFramework> <connectionStrings> <add name="WypozyczalniaDataContext" connectionString="metadata=res://*/Wypozyczalnia.csdl|res://*/Wypozyczalnia.ssdl|res://*/Wypozyczalnia.msl;provider=System.Data.SqlServerCe.4.0;provider connection string=&quot;data source=C:\Users\Wojciech\Desktop\Wypozyczalnia\Wypozyczalnia.sdf&quot;" providerName="System.Data.EntityClient" /> </connectionStrings> </configuration> A: After 8 hours, finally I've found the problem. I've been editing DBSerivce.config, but I've forgotten, that there is separate App.config for my self-hosting application... Be aware of that or you'll lose half a day :P.
{ "pile_set_name": "StackExchange" }
Q: Monitoring DOM Changes in JQuery Is there a way to detect when the disabled attribute of an input changes in JQuery. I want to toggle the style based on the value. I can copy/paste the same enable/disable code for each change event (as I did below) but I was looking for a more generic approach. Can I create a custom event that will monitor the disabled attribute of specified inputs? Example: <style type="text/css">.disabled{ background-color:#dcdcdc; }</style> <fieldset> <legend>Option 1</legend> <input type="radio" name="Group1" id="Radio1" value="Yes" />Yes <input type="radio" name="Group1" id="Radio2" value="No" checked="checked" />No <div id="Group1Fields" style="margin-left: 20px;"> Percentage 1: <input type="text" id="Percentage1" disabled="disabled" /><br /> Percentage 2: <input type="text" id="Percentage2" disabled="disabled" /><br /> </div> </fieldset> <fieldset> <legend>Option 2</legend> <input type="radio" name="Group2" id="Radio3" value="Yes" checked="checked" />Yes <input type="radio" name="Group2" id="Radio4" value="No" />No <div id="Group2Fields" style="margin-left: 20px;"> Percentage 1: <input type="text" id="Text1" /><br /> Percentage 2: <input type="text" id="Text2" /><br /> </div> </fieldset> <script type="text/javascript"> $(document).ready(function () { //apply disabled style to all disabled controls $("input:disabled").addClass("disabled"); $("input[name='Group1']").change(function () { var disabled = ($(this).val() == "No") ? "disabled" : ""; $("#Group1Fields input").attr("disabled", disabled); //apply disabled style to all disabled controls $("input:disabled").addClass("disabled"); //remove disabled style to all enabled controls $("input:not(:disabled)").removeClass("disabled"); }); $("input[name='Group2']").change(function () { var disabled = ($(this).val() == "No") ? "disabled" : ""; $("#Group2Fields input").attr("disabled", disabled); //apply disabled style to all disabled controls $("input:disabled").addClass("disabled"); //remove disabled style to all enabled controls $("input:not(:disabled)").removeClass("disabled"); }); }); </script> A: After further researching this issue, I stumbled upon a blog post by Rick Strahl in which we demonstrates a jQuery plug-in that allows for monitoring of CSS properties: jQuery CSS Property Monitoring Plug-in updated
{ "pile_set_name": "StackExchange" }
Q: Make the option to register more explicit I'm going to ask/answer a question on a new site, guys! Let's just fill out this last form here. Well, I don't have an account, so to register I just fill in my name and email, right? Wrong. Kind of. It's very easy to assume the right form is for registration, rather than posting via a throwaway unregistered account. Making the fact that it's a throw away account here is a bit too complicated. Instead, why don't we draw more attention to that log in link? I avoided the word 'or' here because it's already used in the divider Technically you can sign up from that log in page too; and that makes a registered account, not a sad, what-if-my-cookie-is-deleted, unregistered account. By making it explicit you can register for realsies via that link too, hopefully we could get a few more registered users and a few less users confused as to why they keep losing their dang accounts. This also leaves the unregistered option totally intact. Unregistered accounts are sort of a confusing pain in the butt; worse, with 87 sites, a registered account lets you access them all with one account. But if you're unregistered you don't get that access, and you probably don't know it. Anything we can do to goad a few more people into registering as early as possible is a net gain for the user's experience and the site/network as a whole. A: We're on it. One of our focus areas right now is dealing with challenges to onboarding for new users, and this particular issue is high on my list of things we need to make more intuitive. Exact implementation is still in discussion, but both your point and the one made in @voretaq7’s answer are valid and in line with our plans: It should be much easier to sign up for real, and much harder to accidentally wind up with an unvalidated account There should be clarity, and maybe a little encouragement, around how to upgrade to a full account. (Status is listed as deferred due to lack of clarity on timing and specifics of implementation, but it's a live priority item right now.) A: When asking or answering a question before logging in, there are several options: Picking any of the options on the left will allow you to create an account or log in using an OpenID or Facebook. But filling in an email address (and optionally a name) will allow posting as an "unregistered account". After posting, the following banner will appear at the top of the page until dismissed: The email address you provide will also be sent an email: Recently, you asked a question on Mi Yodeya, but you haven't verified your email address yet. Click on the following link to verify your email and set a password so that you can log in. Set Your Password If you try to log out, you get this page: Following any of the set a password links: When you provide a password (twice), a Stack Exchange OpenID will automatically be created for you using the email you provided. You will later be able to log in again with your email and password: Note that if you actually do log out of an unregistered account, the only way to log in again is to create a password. The "account recovery process" sends the link to set a password. A: I would go a step further and add a "Register your account" link/button that shows up in some consistent location on the UI after you've made a post as an unregistered user. (I'm assuming we don't have one -- I never actually had an unregistered account on the Stack Exchange network...)
{ "pile_set_name": "StackExchange" }
Q: Combining arrays with common values I have an array of dates that looks like this: Array ( [0] => '2014-01-01' [1] => '2014-01-02' [2] => '2014-01-03' [3] => '2014-01-04' [4] => '2014-01-05' [5] => '2014-01-06' [6] => '2014-01-07' ) and I have another array of dates and counts that looks like this: [All] => Array ( [0] => Array ( [count] => 2 [date] => 2014-01-06 ) [1] => Array ( [count] => 1 [date] => 2014-01-03 ) [2] => Array ( [count] => 43 [date] => 2013-12-11 ) [3] => Array ( [count] => 103 [date] => 2013-12-10 ) [4] => Array ( [count] => 128 [date] => 2013-12-09 ) [5] => Array ( [count] => 75 [date] => 2013-12-08 ) [6] => Array ( [count] => 107 [date] => 2013-12-07 ) I want to make a new associative array where all the keys are the dates from the first array above and all of the values are either the count matched up with the corresponding date or "0". So for instance, the new array would look like this: Array ( [2014-01-01] => 0 [2014-01-02] => 0 [2014-01-03] => 1 [2014-01-04] => 0 [2014-01-05] => 0 [2014-01-06] => 2 [2014-01-07] => 0 ) Does that make sense? Please feel free to ask any questions you may have. Thank you! A: Try this code: $result = array(); foreach($firstArray as $f){ foreach($secondArray as $s){ if($s['date'] == $f) $result[$f] = $s['count']; } if(!array_key_exists($f, $result)) $result[$f] = 0; }
{ "pile_set_name": "StackExchange" }
Q: Java: Read certificates from windows store It is possible to write a Java program to read one certificate (getting private and public key) stored in windows certificate store ? Thanks A: If you are on Java 6, you can use the MSCAPI keystore to read it. Just open your keystore like this, KeyStore msCertStore = KeyStore.getInstance("Windows-MY", "SunMSCAPI");
{ "pile_set_name": "StackExchange" }
Q: Best way to reuse variables in Javascript? If I have an array in Javascript : var myArray = []; myArray.push({ id: 0, value: 1 }); myArray.push({ id: 2, value: 3 }); Is there a way I do not have to define the var { id: 2, value: 3 } again and again? Something which would allow me to create a variable and use it again like : var something = { id: tempId, value: tempVal } and then I can keep pushing new instances of something in the array? A: So as I can understand from your comment you want a function that pushes an object to an array. For javascript objects look here : http://www.w3schools.com/js/js_objects.asp Indeed, you have been creating classes all along. function Something(id, value) { this.id = id; this.value = value } now when you are pushing this to an array you need to create an instance(an object) such as var something1 = new Something(1,2) myArray.push(something1) And if you want to access a field you will do myArray[0]["id"] see this question What techniques can be used to define a class in JavaScript, and what are their trade-offs?
{ "pile_set_name": "StackExchange" }
Q: setting up a script to rotate scren Lenovo Yoga Thinkpad S1 I am trying to set up a Lenovo Yoga Thinkpad S1 to rotate the screen with the touch of a button but I am having a little trouble with the script that actually does the work. I have found the scripts that does everything I need here. The script that is giving me trouble is the first tone of post number 6. The script is as follows: #!/bin/bash # Script rotates screen 90deg on every run, and also rotates touchscreen and wacom input. # In modes other than normal, touchpad is deactivated. current_orientation(){ xrandr|grep " connected" |awk '{print $4}' } #orientation=`current_orientation` case $( current_orientation ) in "(normal" ) xrandr -o left xsetwacom set "Wacom ISDv4 EC Pen stylus" rotate ccw xsetwacom set "Wacom ISDv4 EC Pen eraser" rotate ccw synclient TouchpadOff=1 xinput set-prop --type=int --format=8 "ELAN Touchscreen" "Evdev Axes Swap" "1" xinput set-prop "ELAN Touchscreen" "Evdev Axis Inversion" 1 0 onboard & ;; "inverted" ) xrandr -o right xsetwacom set "Wacom ISDv4 EC Pen stylus" rotate cw xsetwacom set "Wacom ISDv4 EC Pen eraser" rotate cw xinput set-prop --type=int --format=8 "ELAN Touchscreen" "Evdev Axes Swap" "1" xinput set-prop "ELAN Touchscreen" "Evdev Axis Inversion" 0 1 ;; "right" ) xrandr -o normal xsetwacom set "Wacom ISDv4 EC Pen stylus" rotate none xsetwacom set "Wacom ISDv4 EC Pen eraser" rotate none synclient TouchpadOff=0 xinput set-prop --type=int --format=8 "ELAN Touchscreen" "Evdev Axes Swap" "0" xinput set-prop "ELAN Touchscreen" "Evdev Axis Inversion" 0 0 killall onboard ;; "left" ) xrandr -o inverted xsetwacom set "Wacom ISDv4 EC Pen stylus" rotate half xsetwacom set "Wacom ISDv4 EC Pen eraser" rotate half xinput set-prop --type=int --format=8 "ELAN Touchscreen" "Evdev Axes Swap" "0" xinput set-prop "ELAN Touchscreen" "Evdev Axis Inversion" 1 1 ;; * ) synclient TouchpadOff=0 echo "c est autre chose" current_orientation #echo $orientation ;; esac When I run the script from the button nothing happens. (button is configured to call the script from keyboard shortcuts). I have set the script to execute with chmod +x. However, when I run the script from the command line I get "c est autre chose". As this is is in the script I can see that the script is working?? - I guess. But it does not rotate the screen at all. Or turn off touchpad. This script works for others with the same model of computer using different flavors of Ubuntu. I am running Ubuntu Gnome 14.04. I have already set up the palm rejection script also found in post number 6 and it is working fine. I would ask on the forum where I found the script but registration is temporarily closed. A: Change the script to xrandr|grep " connected" |awk '{print $5}' as Charles suggested.
{ "pile_set_name": "StackExchange" }
Q: Convert Lab color to RGB I am trying to convert a Lab color into RGB. As an example for this conversion, Photoshop converts L= 100, a = 0, b = 127 into R=255, G=252, B=0. This color is bright yellow. I have written the following conversion routine (C/Objective C). However, something is not right. The code will output XYZ = 100.000000 100.000000 4.862713 RGB = 163.908401 90.755638 -13.093634 Here the mismatch between the the RGB-result and Photoshop's RGB seems to be quite large. The negative blue component is also a problem. Any ideas on how to correct the below code would be greatly appreciated? Or, any other algorithms/formulas/pseudocode for converting Lab into RGB? Thank you. The code: /* * See Wikipedia artice on Lab color space * * http://en.wikipedia.org/wiki/Lab_color_space * */ CGFloat fInv (CGFloat t) { CGFloat T0 = (CGFloat) 6.0f/29.0f; if (t > T0) { return t*t*t; } return 3.0 * T0 * T0 * (t - 4.0f/29.0f); } int test() { // // Bright yellow test // CGFloat Ls = 100.0f; CGFloat as = 0.0f; CGFloat bs = 127.0f; // // Reference white point (ad hoc) // CGFloat Xn = 100; CGFloat Yn = 100; CGFloat Zn = 100; // // Taken Wikipedia (see above) // CGFloat X = Xn * fInv(1/116.0f * (Ls + 16.0f) + 1/500.0f * as); CGFloat Y = Yn * fInv(1/116.0f * (Ls + 16.0f)); CGFloat Z = Zn * fInv(1/116.0f * (Ls + 16.0f) - 1/200.0f * bs); NSLog(@" XYZ = %f %f %f", X, Y, Z); // // // XYZ to RGB transfomration using AppleRGB. Taken from // // http://brucelindbloom.com/index.html?Eqn_RGB_XYZ_Matrix.html // // CGFloat r = 2.9515373 * X - 1.2894116 * Y - 0.4738445 * Z; CGFloat g = -1.0851093 * X + 1.9908566 * Y + 0.0372026 * Z; CGFloat b = 0.0854934 * X - 0.2694964 * Y + 1.0912975 * Z; NSLog(@" RGB = %f %f %f", r, g, b); } A: Try implementing formulas from this site. I just implemented RGB->Lab(through XYZ) and it works fine. C++ code: // using http://www.easyrgb.com/index.php?X=MATH&H=01#text1 void rgb2lab( float R, float G, float B, float & l_s, float &a_s, float &b_s ) { float var_R = R/255.0; float var_G = G/255.0; float var_B = B/255.0; if ( var_R > 0.04045 ) var_R = pow( (( var_R + 0.055 ) / 1.055 ), 2.4 ); else var_R = var_R / 12.92; if ( var_G > 0.04045 ) var_G = pow( ( ( var_G + 0.055 ) / 1.055 ), 2.4); else var_G = var_G / 12.92; if ( var_B > 0.04045 ) var_B = pow( ( ( var_B + 0.055 ) / 1.055 ), 2.4); else var_B = var_B / 12.92; var_R = var_R * 100.; var_G = var_G * 100.; var_B = var_B * 100.; //Observer. = 2°, Illuminant = D65 float X = var_R * 0.4124 + var_G * 0.3576 + var_B * 0.1805; float Y = var_R * 0.2126 + var_G * 0.7152 + var_B * 0.0722; float Z = var_R * 0.0193 + var_G * 0.1192 + var_B * 0.9505; float var_X = X / 95.047 ; //ref_X = 95.047 Observer= 2°, Illuminant= D65 float var_Y = Y / 100.000; //ref_Y = 100.000 float var_Z = Z / 108.883; //ref_Z = 108.883 if ( var_X > 0.008856 ) var_X = pow(var_X , ( 1./3. ) ); else var_X = ( 7.787 * var_X ) + ( 16. / 116. ); if ( var_Y > 0.008856 ) var_Y = pow(var_Y , ( 1./3. )); else var_Y = ( 7.787 * var_Y ) + ( 16. / 116. ); if ( var_Z > 0.008856 ) var_Z = pow(var_Z , ( 1./3. )); else var_Z = ( 7.787 * var_Z ) + ( 16. / 116. ); l_s = ( 116. * var_Y ) - 16.; a_s = 500. * ( var_X - var_Y ); b_s = 200. * ( var_Y - var_Z ); } //http://www.easyrgb.com/index.php?X=MATH&H=01#text1 void lab2rgb( float l_s, float a_s, float b_s, float& R, float& G, float& B ) { float var_Y = ( l_s + 16. ) / 116.; float var_X = a_s / 500. + var_Y; float var_Z = var_Y - b_s / 200.; if ( pow(var_Y,3) > 0.008856 ) var_Y = pow(var_Y,3); else var_Y = ( var_Y - 16. / 116. ) / 7.787; if ( pow(var_X,3) > 0.008856 ) var_X = pow(var_X,3); else var_X = ( var_X - 16. / 116. ) / 7.787; if ( pow(var_Z,3) > 0.008856 ) var_Z = pow(var_Z,3); else var_Z = ( var_Z - 16. / 116. ) / 7.787; float X = 95.047 * var_X ; //ref_X = 95.047 Observer= 2°, Illuminant= D65 float Y = 100.000 * var_Y ; //ref_Y = 100.000 float Z = 108.883 * var_Z ; //ref_Z = 108.883 var_X = X / 100. ; //X from 0 to 95.047 (Observer = 2°, Illuminant = D65) var_Y = Y / 100. ; //Y from 0 to 100.000 var_Z = Z / 100. ; //Z from 0 to 108.883 float var_R = var_X * 3.2406 + var_Y * -1.5372 + var_Z * -0.4986; float var_G = var_X * -0.9689 + var_Y * 1.8758 + var_Z * 0.0415; float var_B = var_X * 0.0557 + var_Y * -0.2040 + var_Z * 1.0570; if ( var_R > 0.0031308 ) var_R = 1.055 * pow(var_R , ( 1 / 2.4 )) - 0.055; else var_R = 12.92 * var_R; if ( var_G > 0.0031308 ) var_G = 1.055 * pow(var_G , ( 1 / 2.4 ) ) - 0.055; else var_G = 12.92 * var_G; if ( var_B > 0.0031308 ) var_B = 1.055 * pow( var_B , ( 1 / 2.4 ) ) - 0.055; else var_B = 12.92 * var_B; R = var_R * 255.; G = var_G * 255.; B = var_B * 255.; }
{ "pile_set_name": "StackExchange" }
Q: Can netcat listen to a port of a remote computer? I am relaying the output of my script to a local port in my system viz - $python script.py | nc 127.0.0.1 8033 Let's assume that my computer has ip 10.0.0.3 Now, Is it possible that some other computer (say IP 10.0.0.4) can listen to this port via nc or anything else. Please suggest. A: Not directly. The program listening on the port must be on the local machine (meaning 10.0.0.3 in your example). You could arrange for a program on the local machine to listen and send the information to another machine, but the socket connection can only be established on the host.
{ "pile_set_name": "StackExchange" }
Q: Al parecer jtable (jquery) ya esta quedando en el pasado Que alternativa recomendarían que tenga la mismas funciones asíncronas de jtable? A: No se porque dices que esta quedando en el pasado, yo la veo bastante en uso todavía, pero si quieres explorar otras alternativas, DataTable la he usado en algún proyecto y me parece una buena alternativa.
{ "pile_set_name": "StackExchange" }
Q: Hibernate bug or incorrect mapping (this may indicate a bug in Hibernate- ERROR)? When I run the below program, I get the following exception: ERROR: HCANN000002: An assertion failure occurred (this may indicate a bug in Hibernate) org.hibernate.annotations.common.AssertionFailure: Declaring class is not found in the inheritance state hierarchy: com.online.tutorial.elementCollection.map.LanguageStatement5 I run the below JUnit: public class QuestionDataSetup5 { @Test public void testQuestionDataSetup(){ String hindiString = new String("Hindi"); String englishString = new String("English"); String chineseString = new String("chinese"); LanguageStatement5 hindiStatement = new LanguageStatement5("बिल गेट्स के जन्म की तारीख क्या है"); LanguageStatement5 englishStatement = new LanguageStatement5("What is the date of Birth of Bill Gates"); LanguageStatement5 ChineseStatement = new LanguageStatement5("什么是比尔·盖茨出生日期"); Map<String, LanguageStatement5> questionMap5 = prepareMap(hindiString, englishString, chineseString, hindiStatement, englishStatement, ChineseStatement); Question5 dateOfBirthQuestion5 = new Question5(10, questionMap5); EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("NewPersistenceUnit"); EntityManager entityManager = entityManagerFactory.createEntityManager(); entityManager.getTransaction().begin(); entityManager.persist(hindiStatement); entityManager.persist(englishStatement); entityManager.persist(ChineseStatement); entityManager.persist(dateOfBirthQuestion5); entityManager.getTransaction().commit(); } private Map<String, LanguageStatement5> prepareMap(String hindiString, String englishString, String chineseString, LanguageStatement5 hindiStatement, LanguageStatement5 englishStatement, LanguageStatement5 chineseStatement) { Map<String, LanguageStatement5> questionMap5 = new HashMap<String, LanguageStatement5>(); questionMap5.put(hindiString, hindiStatement); questionMap5.put(englishString, englishStatement); questionMap5.put(chineseString, chineseStatement); return questionMap5; } } POJO classes: package com.online.tutorial.elementCollection.map; import javax.persistence.*; import java.util.Map; import java.util.TreeMap; @Entity @Table(name = "Question5") public class Question5 { @Id @SequenceGenerator(name = "question_sequencer_generator", sequenceName = "question_sequencer" , initialValue = 10, allocationSize = 50) @GeneratedValue(generator = "question_sequencer_generator", strategy = GenerationType.SEQUENCE) @Column(name = "question_id") private Long questionId; @Column(name = "Max_Marks") private int maxMarks; @ElementCollection @CollectionTable(name = "IMAGE") @MapKeyJoinColumn(name = "LANGUAGE_REF_ID") /* @JoinTable(name = "QUESTION_STATEMENT_MAPPING", joinColumns = @JoinColumn(name = "QUESTION_REF_ID"), inverseJoinColumns = @JoinColumn(name = "STATEMENT_REF_ID")) */ private Map<String, LanguageStatement5> languageNameToQuestionMap = new TreeMap<String, LanguageStatement5>(); public Question5() { } public Question5(int maxMarks, Map<String, LanguageStatement5> languageNameToQuestionMap) { this.maxMarks = maxMarks; this.languageNameToQuestionMap = languageNameToQuestionMap; } public Long getQuestionId() { return questionId; } public void setQuestionId(Long questionId) { this.questionId = questionId; } public int getMaxMarks() { return maxMarks; } public void setMaxMarks(int maxMarks) { this.maxMarks = maxMarks; } public Map<String, LanguageStatement5> getLanguageNameToQuestionMap() { return languageNameToQuestionMap; } public void setLanguageNameToQuestionMap(Map<String, LanguageStatement5> languageNameToQuestionMap) { this.languageNameToQuestionMap = languageNameToQuestionMap; } } Another POJO class: package com.online.tutorial.elementCollection.map; import javax.persistence.*; @Embeddable public class LanguageStatement5 { @Id @SequenceGenerator(name = "statement_sequencer_generator", sequenceName = "statement_sequencer" , initialValue = 10, allocationSize = 50) @GeneratedValue(generator = "statement_sequencer_generator", strategy = GenerationType.SEQUENCE) @Column(name = "statement_id") private Long statementId; @Column(name = "statement") private String statement; public LanguageStatement5() { } public LanguageStatement5(String statement) { this.statement = statement; } public String getStatement() { return statement; } public void setStatement(String statement) { this.statement = statement; } } Pom.xml file: <dependencies> <dependency> <groupId>com.oracle</groupId> <artifactId>ojdbc14</artifactId> <version>14</version> </dependency> <!-- http://mvnrepository.com/artifact/org.hibernate.javax.persistence/hibernate-jpa-2.1-api --> <dependency> <groupId>org.hibernate.javax.persistence</groupId> <artifactId>hibernate-jpa-2.1-api</artifactId> <version>1.0.0.Final</version> </dependency> <!-- http://mvnrepository.com/artifact/org.hibernate/hibernate-core --> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-core</artifactId> <version>4.3.2.Final</version> </dependency> <!-- http://mvnrepository.com/artifact/org.hibernate/hibernate-entitymanager --> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-entitymanager</artifactId> <version>4.3.2.Final</version> </dependency> <!-- http://mvnrepository.com/artifact/org.hibernate/hibernate-validator --> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-validator</artifactId> <version>4.3.2.Final</version> </dependency> <!-- http://mvnrepository.com/artifact/org.hibernate/hibernate-annotations --> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-annotations</artifactId> <version>3.5.6-Final</version> </dependency> <!-- http://mvnrepository.com/artifact/org.hibernate/hibernate --> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate</artifactId> <version>3.5.4-Final</version> <type>pom</type> </dependency> <!-- http://mvnrepository.com/artifact/org.hibernate/hibernate-ehcache --> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-ehcache</artifactId> <version>4.3.2.Final</version> </dependency> <!-- http://mvnrepository.com/artifact/org.hibernate/hibernate-c3p0 --> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-c3p0</artifactId> <version>4.3.2.Final</version> </dependency> <!-- http://mvnrepository.com/artifact/junit/junit --> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> </dependency> A: If LanguageStatement5 is an entity type - as suggested by @Id and the fact that you are trying to persist its instances directly with the entity manager - it should be declared as such: You should annotate it with @Entity and not with @Embeddable. The later is used to persist classes which are "owned" by other entities and don't have their own lifecycle and identity (@Id). This also means you will have to the change the mapping of languageNameToQuestionMap property of Question5 from @ElementCollection to @OneToMany. Alternatively, if LanguageStatement5 is indeed conceptually an embedded entity, you shouldn't try to persist those there instances. Just call entityManager.persist(dateOfBirthQuestion5); and JPA will take care for persisting the language statement objects. This should be the only call to persist in your code. You should also remove @SequenceGenerator and @Id from LanguageStatement5 in that case.
{ "pile_set_name": "StackExchange" }
Q: How to use hook_init in a custom module? I am trying to use a hook_init within my custom module to add a js file. The problem is I do not see where the script is being called or executed on the front-page. /* Implements hook_init. */ function hook_init() { if (drupal_is_front_page()) { drupal_add_js(drupal_get_path('modules', 'myInfo') . '/myScript.js'); } } name = My Info description = My Info Evaluation. core = 7.x version = 7.x-0.1-dev I even tried to remove the hook_init and referenced the JS within the module info, but no luck. What am I missing here? A: Some suggestions: Is the module enabled? Silly question, but I've forgotten to do that before. hook_init implementations won't get called until you clear the cache. Did you clear the cache? I will sometimes put a drupal_set_message('this line'); in various parts of the code to see if that's getting called. In situations where a drupal_set_message isn't helping, I sometimes will put a asdf() so I can get a "fatal error, call to undefined function" message. Then it's really clear whether or not the code is getting called. If the hook_init is not being called and the module is enabled and cache was cleared, then it's probably mis-spelled. The function should be named based on the name of your module: If your module is mymodule.module then the function name is mymodule_init(). It's possible that the path you are using isn't quite right. Does the file really exist there? I would try: drupal_set_message(drupal_get_path('modules', 'myInfo') . '/myScript.js'); so you can see the path and confirm that it's right. There's some good documentation on Managing JavaScript in Drupal 7 though perhaps you've already read that page. Good luck! A: In your module, did you replace 'hook' with your module name? Assuming you have myinfo.info and myinfo.module, the function should be myinfo_init() in order to be called when your module is active.
{ "pile_set_name": "StackExchange" }
Q: Change View Title when Navigating Back from a (Sub) View I have a RootView with 5 buttons. When a button is pressed, I change the title of the current view (so the Back Button is brief) before displaying the selected view. When transitioning to the new (sub) view, I send the pushViewController message to the NavigationController through the AppDelegate. When the Back Button is selected in the sub-view, I would like to change the title back to the verbose title. Could anyone point out how I would accomplish the title change of the RootView when leaving a sub view? A: Set the title in viewWillAppear of you RootView: - (void)viewWillAppear:(BOOL)animated { self.title = @"RootView"; } If you use the back button on a sub-view, the root view will get the right title.
{ "pile_set_name": "StackExchange" }
Q: GPG Not Working I am using Ubuntu 18.04.1. I previously had GPG 2.1.15 (including dependencies) manually installed from gnupg.org. I wanted to install a ppa and after running sudo apt-key add Release.key I got the output: gpg: can't connect to the agent: IPC connect call failed I then went on a wild goose chase to fix that. The wild goose chase ended poorly. I uninstalled GPG2 (and dependencies) using sudo make uninstall in the directory for GPG2 and each dependencies. I then installed GPG2 and its dependencies via apt. I am now completely unable to use GPG. When I run gpg --clearsign I get the output gpg: can't connect to the agent: IPC connect call failed gpg: can't connect to the agent: IPC connect call failed gpg: keydb_search failed: No agent running gpg: no default secret key: No agent running gpg: [stdin]: clear-sign failed: No agent running When I run gpg-agent --daemon I get gpg-agent: relocation error: gpg-agent: symbol gcry_get_config version GCRYPT_1.6 not defined in file libgcrypt.so.20 with link time reference When I run gpg --version I get gpg (GnuPG) 2.2.4 libgcrypt 1.7.0 Copyright (C) 2017 Free Software Foundation, Inc. License GPLv3+: GNU GPL version 3 or later <https://gnu.org/licenses/gpl.html> This is free software: you are free to change and redistribute it. There is NO WARRANTY, to the extent permitted by law. Home: /home/michael/.gnupg Supported algorithms: Pubkey: RSA, ELG, DSA, ECDH, ECDSA, EDDSA Cipher: IDEA, 3DES, CAST5, BLOWFISH, AES, AES192, AES256, TWOFISH, CAMELLIA128, CAMELLIA192, CAMELLIA256 Hash: SHA1, RIPEMD160, SHA256, SHA384, SHA512, SHA224 Compression: Uncompressed, ZIP, ZLIB, BZIP2 A: I manually uninstalled, reinstalled and then again uninstalled libgcrypt 1.7.0 by going to the directory with the files I downloaded from gnupg.org and running sudo make uninstall sudo make install sudo make uninstall I then reinstalled libgcrypt through apt by running sudo apt install --reinstall libgcrypt20* I then went to the directory for libgpg-error 1.21 and did the same for libgpg-error 1.21. sudo make uninstall sudo make install sudo make uninstall sudo apt install --reinstall libgpg-error0 I then went to the directory for libassuan 2.4.2. I manually installed and then uninstalled libassuan 2.4.2 before reinstalling libassuan through apt. sudo make install sudo make uninstall sudo apt install --reinstall libassuan0
{ "pile_set_name": "StackExchange" }
Q: Converting Dataset[Array[String]] to Dataset[MyCaseClass] I am working with a csv file like below "age;""job"";""marital""" "58;""management"";""married""" "44;""technician"";""single""" Because of the extra quotes, spark.read.csv does not give clean columns. So I thought of using spark.read.textFile which gives Dataset[String]. I use below code to remove the quotes and split them. case class MyCaseClass(age: String, job: String, marital: String) val inputDS = spark.read.textFile(inpPath) val cleanDS = inputDS.map(_.replaceAll(""""""", "").split(";")) val seperatedDS = cleanDS.as[MyCaseClass] //fails Is there a way to achieve this sort of Dataset convertion or a better way to split out into multiple columns? For now I am using RDD to get the job done, but would like to know Dataset/Dataframe way of doing it. A: You can construct a record of MyCaseClass from each split line so that you have RDD[MyCaseClass], then you can directly convert it to data frame: val cleanDS = inputDS.map(line => { val fields = line.replaceAll("\"", "").split(";") MyCaseClass(fields(0), fields(1), fields(2)) }) cleanDS // res37: org.apache.spark.sql.Dataset[MyCaseClass] = [age: string, job: string ... 1 more field] cleanDS.toDF.show +---+----------+-------+ |age| job|marital| +---+----------+-------+ |age| job|marital| | 58|management|married| | 44|technician| single| +---+----------+-------+
{ "pile_set_name": "StackExchange" }
Q: A single function in the queue being called multiple times while it should be called once Recently I was developing a custom jQuery-based content slider, which unlike most other sliders wouldn't display multiple pictures flying by while transitioning between two items that are not adjacent to each other. It worked just fine, except that clicking on multiple selectors while the animation isn't yet completed screws everything up. I decided to implement a queueing mechanism that would delay the animations start until the other animation has finished. However, more problems awaited me. For some odd reason the queued function is called five times instead of one upon the dequeueuing. You can see this in action here : http://jsfiddle.net/QLLKt/embedded/result/. Click on any slide selector while animation is active. You should now see that the time on which the function was queued is being displayed five times even though it is supposed to be displayed only once. My question is: why it behaves like this and is there any cure for it? A: Turns out that the root of the problem was lying in these lines of code: $('.selector').queue('queue', function () { var d = new Date(); $('#result').append("<br/>" + "Queued at "+ d.getTime()); The query on "selector" class returns six elements. Therefore it puts a single function on the queue of eache elements, which leads to the function being called six times.
{ "pile_set_name": "StackExchange" }
Q: How can I use Akka Actors in a Java application? I would like to use Akka actors in Java. I downloaded the akka-1.0.zip and added akka-actor-1.0.jar to my "Build Path" in Eclipse. Then I wrote this Actor class: package com.example; import akka.actor.UntypedActor; public class MyActor extends UntypedActor { public void onReceive(Object message) throws IllegalArgumentException { if (message instanceof String) { System.out.println("Received: " + message); } else throw new IllegalArgumentException("Unknown message: " + message); } } But I get errors in Eclipse: The type scala.Option cannot be resolved. The type scala.Some cannot be resolved. The type scala.PartialFunction cannot be resolved. The type scala.ScalaObject cannot be resoled. Do I need to add any more files to my "Build Path" or what am I doing wrong? I don't find the documentation beeing that helpful. Update: I added scala-library.jar to my Build Path and the above erros disappeared. But I get an error when I compile and run the application: Exception in thread "main" java.lang.NoClassDefFoundError: net/lag/configgy/ConfigMap at akka.actor.Actors.actorOf(Actors.java:70) at com.example.ActorTest.main(ActorTest.java:9) Caused by: java.lang.ClassNotFoundException: net.lag.configgy.ConfigMap at java.net.URLClassLoader$1.run(Unknown Source) at java.security.AccessController.doPrivileged(Native Method) at java.net.URLClassLoader.findClass(Unknown Source) at java.lang.ClassLoader.loadClass(Unknown Source) at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source) at java.lang.ClassLoader.loadClass(Unknown Source) ... 2 more Here is the main class where I use my actor: package com.example; import akka.actor.ActorRef; import akka.actor.Actors; public class ActorTest { public static void main(String[] args) { ActorRef myActor = Actors.actorOf(MyActor.class); myActor.start(); System.out.println("My Actor started"); } } A: In your akka-1.0.zip file there is scala-library.jar. Try adding it to the build path. Also, there is a lib_managed directory inside the zip, which contains further library files. Possibly aslo some of them will be needed. To avoid this kind of situations you should try maven. There is a Akka repository: http://scalablesolutions.se/akka/repository/se/scalablesolutions/akka/
{ "pile_set_name": "StackExchange" }
Q: Import single csv file with one data field going to separate table I have a csv file containing a list of Products with the following 4 fields Product ID, Name, Alias, UOM I would like to import the file into a database that has 2 tables. The first is the Product table: Product ID, Name, UOM The second is the Product Alias table: Product ID, Alias Each Product ID may have 0 to many alias names. Is there any way I could treat the Alias column different by the fact it has a different separator between the commas, like ";" or a period "." to separate the 0 to many alias names for a given Product ID? Therefore during the csv import, when it gets the 3rd comma, it would import that data into the 2nd table but import a new record with repeating Product ID's for as many alias names are in that comma field. Hopefully I explained that well enough, let me if I didn't. I'm more interested in the possible processing of doing this regardless of what code that is being using but python would be the preferred route. Example data ProductID, Name, Alias, UOM 122, Widget1, W1; Wid1;Wt1, Each 123, Widget2, , Each 124, Widget3, W3; Wt3, Each A: This is pretty easy to do. First, you use csv as usual to get all the columns. One of those columns will itself be a semicolon-separated list of values. If you don't need to worry about quoting, etc., you can just use split. For example: with open('foo.csv') as f: for row in csv.DictReader(f): cursor.execute('''INSERT INTO Product (ProductID, Name, UOM) VALUES (:ProductID, :Name, :UOM)''', row) for alias in row['Alias'].split(';'): cursor.execute('''INSERT INTO ProductAlias (Name, Alias) VALUES (?, ?)''', row['Name'], alias) If you can have spaces within the aliases, you're going to need two kinds of quoting or escaping, alongside the two kinds of delimiters. Like this: 123,"Widget 1","Widget1;W1;Wid1;Wt1;'W 1'",Each And you'd want to parse it by using another csv.reader. Of course csv is intended to parse a sequence of lines into a sequence of rows, not a single line into a single row, but that's easy to deal with by just wrapping the single line in a list, and extracting the single row from the result. For example, instead of this: row['Alias'].split(';') … do this: next(csv.reader([row['Alias']], delimiter=";", quotechar="'")) (Although you'd probably want to split up the expression into multiple steps once it gets this complicated.)
{ "pile_set_name": "StackExchange" }
Q: Multi Docker Elastic Beanstalk: upload .ebextensions Is it possible to deploy .ebextensions to Multi-Docker Elastic Beanstalk? I use a Dockerrun.aws.json file to upload my App and everything works fine. I want to setup logs to stream to Cloudwatch. I should do that using .ebextensions. However, I don't know how to attach .ebextensions if I upload in web browser (AWS console) just only Dockerrun.aws.json (not .zip or .war). How can I deploy also .ebxetensions to Multi Docker Elastic Beanstalk? ... or is it any other way to setup what logs should be streamed to Cloudwatch Logs? A: You should create a zip archive that contains both Dockerrun.aws.json and .ebextensions directory with any configuration files that you require. Elastic Beanstalk will find Dockerrun.aws.json file from the archive. This is covered in AWS' Multicontainer Docker tutorial.
{ "pile_set_name": "StackExchange" }
Q: Angular ui grid, change behavior of "Export all data as csv" I have a uigrid that contains a large number of column definitions that aren't initially filled with data because the data set would be too large. Instead, I get the requested column data when the column visibility changes. This causes an issue with the built in csv exporter. When someone chooses to "Export all data as csv" they get numerous empty columns. What I would like to do it change the default behavior of the built in csv menu items to use uiGridExporterConstants.VISIBLE. I was going to roll my own menu items like so: $scope.gridOptions.exporterMenuCsv = false; //Rolling our own menu items to exclude invisible columns $scope.gridOptions.gridMenuCustomItems = [ { title: 'Export All to CSV', action: function ($event) { var myElement = angular.element(document.querySelectorAll(".custom-csv-link-location")); $scope.gridApi.exporter.csvExport( uiGridExporterConstants.ALL, uiGridExporterConstants.VISIBLE, myElement ); } },{ title: 'Export Selected to CSV', action: function ($event) { var myElement = angular.element(document.querySelectorAll(".custom-csv-link-location")); $scope.gridApi.exporter.csvExport( uiGridExporterConstants.SELECTED, uiGridExporterConstants.VISIBLE, myElement ); } },{ title: 'Export Visible to CSV', action: function ($event) { var myElement = angular.element(document.querySelectorAll(".custom-csv-link-location")); $scope.gridApi.exporter.csvExport( uiGridExporterConstants.VISIBLE, uiGridExporterConstants.VISIBLE, myElement ); } } ]; But only the first item appears. Maybe I have to use addToGridMenu, but I'm not sure. Ideally, I'd like to leave the default items in place, but just have "export all data as csv" only export the visible columns. A: I ended up having to use gridApi.core.addToGridMenu like so: $scope.gridOptions = { exporterCsvLinkElement: angular.element(document.querySelectorAll('.custom-csv-link-location')), onRegisterApi: function(gridApi){ $scope.gridApi = gridApi; $interval(function () { gridApi.core.addToGridMenu(gridApi.grid, [{ title: 'Export All to CSV', order: 1, action: function ($event) { var myElement = angular.element(document.querySelectorAll(".custom-csv-link-location")); $scope.gridApi.exporter.csvExport(uiGridExporterConstants.ALL, uiGridExporterConstants.VISIBLE, myElement); } }]); gridApi.core.addToGridMenu(gridApi.grid, [{ title: 'Export Visible to CSV', order: 2, action: function ($event) { var myElement = angular.element(document.querySelectorAll(".custom-csv-link-location")); $scope.gridApi.exporter.csvExport(uiGridExporterConstants.VISIBLE, uiGridExporterConstants.VISIBLE, myElement); } }]); }, 0, 1); $scope.gridApi.selection.on.rowSelectionChanged($scope, function () { //for single row selection if (gridApi.grid.selection.selectedCount > 0 && !selectionMenuAdded) { //only add menu item if something is selected and if the menu item doesn't already exist selectionMenuAdded = true; gridApi.core.addToGridMenu(gridApi.grid, [{ title: 'Export Selected to CSV', order: 3, id: 'uiSel', action: function ($event) { if (gridApi.grid.selection.selectedCount > 0) { var uiExporter = uiGridExporterService; var grid = $scope.gridApi.grid; uiExporter.loadAllDataIfNeeded(grid, uiGridExporterConstants.ALL, uiGridExporterConstants.VISIBLE).then(function () { var exportColumnHeaders = uiExporter.getColumnHeaders(grid, uiGridExporterConstants.VISIBLE); var selectionData = []; gridApi.selection.getSelectedRows().forEach(function (entry) { var innerData = []; for (var e in entry) { //create the inner data object array if (e !== '$$hashKey') { var selectObj = { value: entry[e] }; innerData.push(selectObj); } } selectionData.push(innerData); //push the inner object value array to the larger array as required by formatAsCsv }); var csvContent = uiExporter.formatAsCsv(exportColumnHeaders, selectionData, grid.options.exporterCsvColumnSeparator); uiExporter.downloadFile($scope.gridOptions.exporterCsvFilename, csvContent, grid.options.exporterOlderExcelCompatibility); }); } } }]); } else if (gridApi.grid.selection.selectedCount === 0 && selectionMenuAdded) { selectionMenuAdded = false; gridApi.core.removeFromGridMenu(gridApi.grid, 'uiSel'); } }); $scope.gridApi.selection.on.rowSelectionChangedBatch($scope, function () { if (gridApi.grid.selection.selectedCount > 0 && !selectionMenuAdded) { selectionMenuAdded = true; gridApi.core.addToGridMenu(gridApi.grid, [{ title: 'Export Selected to CSV', order: 3, id: 'uiSel', action: function ($event) { if (gridApi.grid.selection.selectedCount > 0) { var uiExporter = uiGridExporterService; var grid = $scope.gridApi.grid; uiExporter.loadAllDataIfNeeded(grid, uiGridExporterConstants.ALL, uiGridExporterConstants.VISIBLE).then(function () { var exportColumnHeaders = uiExporter.getColumnHeaders(grid, uiGridExporterConstants.VISIBLE); var selectionData = []; gridApi.selection.getSelectedRows().forEach(function (entry) { var innerData = []; for (var e in entry) { if (e !== '$$hashKey') { var selectObj = { value: entry[e] }; innerData.push(selectObj); } } selectionData.push(innerData); }); var csvContent = uiExporter.formatAsCsv(exportColumnHeaders, selectionData, grid.options.exporterCsvColumnSeparator); uiExporter.downloadFile($scope.gridOptions.exporterCsvFilename, csvContent, grid.options.exporterOlderExcelCompatibility); }); } } }]); } else if (gridApi.grid.selection.selectedCount === 0 && selectionMenuAdded) { selectionMenuAdded = false; gridApi.core.removeFromGridMenu(gridApi.grid, 'uiSel'); } }); } } Be sure to inject uiGridExporterConstants and uiGridExporterService.
{ "pile_set_name": "StackExchange" }
Q: Why am I unable to access the methods of an object via is ObjectContainer first of all, i'm not a native english speaker but, still, i'll try my best to be understandable and as clear as possible. So, in my programming class, I need to make a Tile based game (like zelda, for exemple) with animate cc (flash). On a map, I want to make a dance floor with tiles that changes on the rhythm of a music. these tiles are movieclip with two frame, one white and one red. This is how the tiles are generated: private function createGrid(): void { grid = new MovieClip(); addChild(grid); for (var r: int = 0; r < nbRow; r++) { for (var c: int = 0; c < nbCol; c++) { var t: Tiles = new Tiles(); t.x = t.width * c; t.y = t.height * r; grid.addChild(t); } } grid.x = 15; //center the grid on x grid.y = 35; //center the grid on y } This is the Tiles Class : package { import flash.display.MovieClip; import flash.events.*; public class Tiles extends MovieClip { private var rand:int; public function Tiles() { // constructor code getTiles(); } public function getTiles():void { random(); setColor(); } private function random() : void{ rand = Math.floor(Math.random()*100)+1; } private function setColor() : void{ if(rand<=30){ gotoAndStop(8); //red frame }else{ gotoAndStop(7); //white frame } } } } createGrid() place the tiles as soon as the map is placed on the stage and stock every tiles in the MovieClip grid. Now, I want the tiles to change randomly between red and white on the beat of a streamed music (and keep the ratio of 30% red tiles and 70% white tiles) var s: Sound = new Sound(); var sc: SoundChannel; s.load(new URLRequest("GameSong_mixdown.mp3")); sc = s.play(0, 1000); I know i need the leftpeek properties of my soundchannel to achieve that but,for now, I do my test with a button that trigger this function: private function setTiles(e: Event): void { // loop through all child element of a movieclip for (var i: int = 0; i < grid.numChildren; i++) { grid.getChildAt(i).getTiles(); } } Right now, the problem is : I'm unable to acces my Tiles method. I did a trace on grid,getChildAt(i), and saw all instances of my tiles in the console. So, i know for sure that every instances of my tiles are stored in grid. But, I don't know why, grid.getChildAt(i).getTiles(); doesn't work (and every other method from Tiles). The error message is: Call to a possibly udefined method getTiles through a reference with static type flash.display:DisplayObject Does someone know what i'm doing wrong ? ps: I translated all my class name, var name, etc from french to english to make the code clearer. A: Your mistake is that getChildAt(...) method has a return type of DisplayObject which is neither dynamic (will not let you access random properties) nor it have DisplayObject.getTiles() method. All you need is to tell the program that this object is actually of Tiles class: private function setTiles(e:Event):void { // loop through all child element of a movieclip for (var i: int = 0; i < grid.numChildren; i++) { // Cast display objects to Tiles class. var aTiles:Tiles = grid.getChildAt(i) as Tiles; // Call the method. aTiles.getTiles(); } }
{ "pile_set_name": "StackExchange" }
Q: How to get the title attribute of a input element? - webdriver How to get the attribute of Title in the input element <input type="image" title="Previous Page"> <input type="image" title="First Page"> <input type="image" title="Next Page"> <input type="image" title="Last Page"> A: What have you tried? Typically something like the following should work: WebElement element = driver.findElement(By.tagName("input")); String title = element.getAttribute("title"); A: The answer provided by Jim Evans is the correct one imo, but for a more specific one i'd advise something like below. Remeber that copy-pasta might not work and you need to change something to be able to work on your full HTML. List<WebElement> elements = driver.findElements(By.tagName("input")); for (WebElement element : elements) { if (element.getAttribute("type").equals("image")) { System.out.println(element.getAttribute("title")); } } The above code will loop for all the in your webpage that are from type="image" and print on the console the "title" attribute of each one of those. Still thing you should vote Jim's answer as the correct one though.
{ "pile_set_name": "StackExchange" }
Q: jQuery $(this).remove() not working after append I have a div with class="tags" with one predefined hyperlink. <div class="tags"> <a href="#">myLink</a> </div> And I have function to remove that hyperlink if user clicks on it. $('.tags a').click(function() { $(this).remove(); return false; }); And this works with predefined hyperlinks. If I add another links with the help of jQuery (after the page is loaded) $('.tags').append('<a href="#">newLink</a>'); Function to remove hyperlink (on click) won't be called on these, added links. How to solve this? A: You have to use the live-function: $(".tags a").live("click", function() { // ... }); Because you are adding the links after the initial load, the standard click event won't be binded to the dynamic added links.
{ "pile_set_name": "StackExchange" }
Q: How do you say "perhaps" or "maybe"? I have a very good guess about how to say "perhaps" or "maybe". But I suspect there are several ways of saying it, with varying degrees of certainty. I wanted to get a better idea. My guess is this. fortasse (also fortassis , but rarely, and not in Caes.; [...]) I.perhaps, peradventure, probably, possibly: A few questions. Is fortasse the best word to say "maybe" or "perhaps"? Are fortasse and fortassis interchangeable? What's the difference between forte, forsitan, and fortasse? A: forte (from fors, fortis, chance, luck etc.) simply means 'by chance'. fortasse (sometimes fortassis) is a contraction from forte an sit, 'as it might chance to be', usually translated as 'perhaps', 'as it may be' etc. Also found are fors sit an (often as one word) and its contraction forsan; and occasionally forsit (from fors sit). Larger Latin-English dictionaries (almost invariably based on Freund's original Latin-German) all give examples of usage. The best choice for English into Latin is no more than a matter of style.
{ "pile_set_name": "StackExchange" }
Q: How do I efficiently query two tables with a lookup table in between? I have three tables: Table1, Table2, and Lookup. Table1 and Table2 have no columns in common. Lookup is for tagging: it has two columns that match Table1 ids with Table2 ids. I am trying to design a query where I can take parameters to get an array of rows from Table1, then using all the ids in my result, get an array of all the corresponding Lookup rows, then use that to get an array of all the corresponding tags in Table2. The hard way would be to do the first query, programmatically get all of the unique ids, then select from Lookup based off those, etc. But that seems really inefficient. I'm using PHP, PDO, and PostgreSQL. What can I do? A: Try this: SELECT * FROM Lookup LEFT JOIN Table1 ON Table1.id=Lookup.Table1_id LEFT JOIN Table2 ON Table2.id=Lookup.Table2_id
{ "pile_set_name": "StackExchange" }
Q: How do I get useful SQL Server database performance statistics? We currently have several shared SQL Server servers and instances in our organization. They are going with a different architecture where business units will get their own SQL Server instances. We have SQL Server 2008R2. In the past, databases were put on servers in a more or less random fashion -- business use and disk space were the main drivers. I've been tasked with coming up with a plan for allocating our 50+ databases across 3 servers (one instance per server). My criteria for divvying them up is as follows: Business critical db's should be spread across the servers. i.e. avoid lumping a bunch of business critical db's all one server. For the remainder of the non-mission critical db's, consider: a. Disk space usage b. I/O usage -- memory, CPU, etc. 1 and 2a are easy for me to figure out. I know how to get data file sizes. My question is with that last bit - 2b. I do not know how relevant this is, what specific stats to look at, or how to get them. Frankly, I'm not 100% sure how to phrase this question! I think I basically want to know is, "How 'busy' is this db -- however you define 'busy'?" Or maybe, "How does this db impact the performance of the server?" I mean, disk space is important -- but it could (in theory) have a ton of rows or binary objects in there that are not written very often, so it has little impact on the performance of the server. I think I would want to know how much impact a db within a date range. Is there a way to get these kind of general stats? I'm not looking for expensive queries, detailed user stats, or query optimization here. I'm aware of the SSMS reports, but they seem to be more real-time. The end goal is to divide up our current databases into evenly balanced buckets, and I would think performance is one way to do that. Thoughts? Wisdom? Any other ideas on how to divvy up the db's? Thanks! Tom A: My question is with that last bit - 2b. I do not know how relevant this is, what specific stats to look at, or how to get them. If you are tight with budget for a good third party tool - Performance Advisor (note: We use do not use 3rd party tools - only SQL Server DMVs/XEvents, etc homegrown over the years), you can look at sys.dm_os_buffer_descriptors DMV. Remember that you have to have a job that dumps the data from the dmv to a physical table, since the DMV data get reset. From my answer : --Find out the database that consumes highest memory in buffer pool SELECT COUNT(*) AS cached_pages_count , ( COUNT(*) * 8.0 ) / 1024 AS MB , CASE database_id WHEN 32767 THEN 'ResourceDb' ELSE DB_NAME(database_id) END AS Database_name FROM sys.dm_os_buffer_descriptors GROUP BY database_id if you want something like CPU usage, Memory usage, Network usage and Disk space usage overtime then use Performance Data Collector. How 'busy' is this db -- however you define 'busy'?" Busy - I would define as how much space the database uses in buffer pool ? How much IO it is generating ? CPU used by databases. Is the database involved in read (reporting) or more write (OLTP) activity ? Its very important to do a Baselining of your sql server with SQL Server Dynamic Management Views Once you have proper data collected, you can easily figure out what databases to group together.
{ "pile_set_name": "StackExchange" }
Q: My search input and pagination aren't triggering anything in Reactjs I'm fairly new to react. My search input and pagination buttons aren't triggering anything and nothing comes up in the console, what is wrong with my code ? I tried putting every functions in App.js to get it cleaner. App.js import React, { Component } from "react"; import List from './List'; let API = 'https://swapi.co/api/people/'; class App extends Component { constructor(props) { super(props); this.state = { results: [], search: '', currentPage: 1, todosPerPage: 3 }; this.handleClick = this.handleClick.bind(this); this.updateSearch = this.updateSearch.bind(this); } componentWillMount() { this.fetchData(); } fetchData = async () => { const response = await fetch(API); const json = await response.json(); this.setState({ results: json.results }); }; handleClick(event) { this.setState({ currentPage: Number(event.target.id) }); } updateSearch(event) { this.setState({ search: event.target.value.substr(0, 20) }); } render() { return ( <div> <List data={this.state} /> </div> ); } } export default App; List.js import React, { Component } from 'react'; import Person from './Person'; class List extends Component { render() { const { data } = this.props; const { results, search, updateSearch, handleClick, currentPage, todosPerPage } = data; const indexOfLastTodo = currentPage * todosPerPage; const indexOfFirstTodo = indexOfLastTodo - todosPerPage; const currentTodos = results.slice(indexOfFirstTodo, indexOfLastTodo).filter(item => { return item.name.toLowerCase().indexOf(search) !== -1; }); const renderTodos = currentTodos.map((item, number) => { return ( <Person item={item} key={number} /> ); }); const pageNumbers = []; for (let i = 1; i <= Math.ceil(results.length / todosPerPage); i++) { pageNumbers.push(i); } const renderPageNumbers = pageNumbers.map(number => { return ( <li className="page-link" key={number} id={number} onClick={handleClick} style={{cursor: "pointer"}}>{number}</li> ); }); return ( <div className="flex-grow-1"> <h1>Personnages de Star Wars</h1> <form className="mb-4"> <div className="form-group"> <label>Rechercher</label> <input className="form-control" type="text" placeholder="luke skywalker..." value={search} onChange={updateSearch} /> </div> </form> <div className="row mb-5">{renderTodos}</div> <nav aria-label="Navigation"> <ul id="page-number" className="pagination justify-content-center">{renderPageNumbers}</ul> </nav> </div> ); } } export default List; The value of the input doesn't change one bit if I type in it and if I right click on a page number, the console gets me Uncaught DOMException: Failed to execute 'querySelectorAll' on 'Element': '#4' is not a valid selector. Any idea ? A: The issue is that in the List class you attempt take updateSearch and handleClick out of data (which in turn comes from this.props). But updateSearch and handleClick are never placed inside data. If you log either of these methods to the console you'll see they are undefined. To fix this, you need to pass updateSearch and handleClick from App to List. You can do this either by including the methods inside the data prop, or by passing them directly as their own props (which I would recommend). For example, you can change the render method of App to look something like this: render() { return ( <div> <List data={this.state} updateSearch={ this.updateSearch } handleClick={ this.handleClick } /> </div> ); } Then in the render method of List you can do this: const { data, updateSearch, handleClick } = this.props; and remove the definitions of the two methods from the destructuring of data below.
{ "pile_set_name": "StackExchange" }
Q: Convergence of sequence of functions. Can someone explain to me why ${f_n}=x^{\frac{1}{2n-1}}$ defined on [-1,1] converges pointwise to $1$ if $x \in (0,1)$, to $-1$ if $x \in (-1,0)$, and to $0$ if $x=0$. This is the answer I got but I think it should converge to $1$ if $x \in [-1,1]-\{0\}$. Because there is an $N$ for which the exponent gets extremely small so it approaches $0$ (so anything raised to the $0$ power is $1$). An intuitive explanation or a proof would be really appreciated. A: So you're only confused about the convergence on $(-1,0)$, yes? The answer says pointwise convergence to $-1$ but you say $1$, yes? I will address this confusion below with both a proof, and an intuitive explanation. Mathematically, we have convergence to $-1$ via the following. Let $x\in(-1,0)$, then $$\lim_{n\to\infty}x^{1/(2n-1)}=-\lim_{n\to\infty}|x|^{1/(2n-1)}=-(1)=-1$$ since the exponent $\frac{1}{2n-1}$ is always an odd root, so we can extract the $-1$ and just look at $|x|\in(0,1)$. Notice that we need to consider the limit with $|x|$ so that we can use continuity of $y\mapsto b^y$ for a fixed positive base $b$; if $b<0$ then $y\mapsto b^y$ is not continuous. Intuitively, we can think about the following. Take some number $x\in(-1,0)$. Then when we take odd roots of $x$ we don't change its sign, because $(-1)^{1/(2n-1)}=-1$. So as $n$ grows $|x|$ is getting closer and closer to $1$, as we can see by the argument you give, however the sign of $x$ is always negative as $n$ grows, so we ultimately end up at $-1$.
{ "pile_set_name": "StackExchange" }
Q: How to shift down columns row and re-assign column values in Pandas Dataframe? I have the following pandas DataFrame: import pandas as pd import numpy as np data = 'filename.dat' df = pd.read_table(data) print(df) 0.098722 08l23252 243434214 5 True 0 0.469112 -0.282863 -1.509059 2 True 1 0.283421 1.224234 7.823421 2 False 2 -1.135632 1.212112 -0.173215 4 False 3 2.34 0.271 0.0932 4 True 4 0.119209 -1.044236 -0.861849 4 True 5 -2.104569 -0.494929 1.071804 4 False 6 0.469112 -0.282863 -1.509059 3 True 7 1.023236 1.224234 7.823421 3 False 8 -1.135632 1.212112 -0.173215 3 False 9 23.23422 2.613492 2.341592 1 True .... The data in filename.dat is saved such the the first row is considered to be the columns. df.columns outputs Index(['0.098722', '08l23252', '243434214', '5', 'True'], dtype='object') How do I add a row such that the current "columns" values row shifts down into the data table, and I could rename columns by actual column names? At the moment, I cannot try df.columns = ['A1', 'B1', 'C1', 'D1', 'E1'] as this simply erases this row and overwrites the values with A1, B1, etc. A1 B1 C1 D1 E1 1 0.283421 1.224234 7.823421 2 False 2 -1.135632 1.212112 -0.173215 4 False 3 2.34 0.271 0.0932 4 True 4 0.119209 -1.044236 -0.861849 4 True .... A: try this: df = pd.read_table(data, names=['A1', 'B1', 'C1', 'D1', 'E1'], header=None) from docs: names : array-like, default None List of column names to use. If file contains no header row, then you should explicitly pass header=None
{ "pile_set_name": "StackExchange" }
Q: Using regex to get string after final occurrence of / in a URL I have a large list of URLS such as: https://www.walmart.com/ip/Cabbage-Patch-Kids-Naptime-Babies-Doll-Blonde-Hair-Blue-Eye-Girl/45792420 https://www.walmart.com/ip/My-Life-As-18-inch-Schoolgirl-Doll-Blonde/336940687 https://www.walmart.com/ip/My-Life-As-18-inch-Everyday-Girl-Doll-African-American/52730785 I need to find all instances after the final / such as 45792420 within the file. I'm using Sublime Text 3 to do the search with regex. I created the following regex \/(?:.(?!\/))+$ however it is returning the / with the string rather than just the string that occurs after the / For example /45792420 How can I just get whatever comes after the final / ? A: Just use \K to prevent anything before the \K from being included in your capture: \/\K(?:.(?!\/))+$
{ "pile_set_name": "StackExchange" }
Q: Excel VBA Commandbutton Switching Worksheet how to keep same viewarea I am using some form control commandbuttons on my worksheet as navigation buttons for switching between worksheets, my issue is the navigation buttons are at the bottom of my worksheet and in the same place on every worksheet which you have to scroll down to, when switching the worksheet page the position changes to the very top, is there anyway to make it so when switching worksheets to copy the current active sheet/scollbar position and make it the same when I go to my next sheet. the reason for this is so my navigation panel that I have created doesn't look like its moving between sheet changes My current code is this Sub Page2() Sheets("Page 2").Activate End Sub Many Thanks in advance A: Method2: Sub Page2() Application.ScreenUpdating = False Sheets("Page 2").Activate ActiveWindow.ScrollRow = 20 'this will be superior; set this number to the row of your buttons or whatever Application.ScreenUpdating = True End Sub
{ "pile_set_name": "StackExchange" }
Q: create a site in a staging environment Does it create problems? I didnt create site before time in salesforce, Now i wonder and i will try to create, My question! what if i create "blabla.salesforce.com" this site Does it work from staging environment or NOT i couldnt found strong information about that. A: Short answer is yes, you can create site in a sandbox and we have done so in the past. It won't impact production but you can create a change set to push the changes into prod.
{ "pile_set_name": "StackExchange" }
Q: How to generate a random word I don't know how I would take a word from a list in Python 3.3. This is my current code: print(random.randstr("blue","red","green","yellow")) And I get this error: print(random.randstr("blue","red","green","yellow")) NameError: name 'random' is not defined Can someone please help? A: you should import your Module or external library first. and random module dose not have random.str() function! Try This : import random a = ['blue', 'red', 'green', 'yellow', 'brown', 'black'] print(random.choice(a)) Good Luck.
{ "pile_set_name": "StackExchange" }
Q: How to call a C# class's static method from VB.Net? I have a C# dll and want to use it in VB.NET. I'm using C# 2008 Express and VB 2008 Express. I have added a reference in a VB project to the C# dll. When I create an instane of a class in the C# dll, it gives the following error messsage: "Type 'RF.RabinFingerprint' has no constructors". How do I fix this? My C# dll code: using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace RF { /// <summary> /// Génère des empreintes de fichiers /// </summary> public static class RabinFingerprint { /// <summary> /// Bit 64 of the polynomial P is always 1 and not treated directly. This is the polynomial /// with the leading coefficient removed (lcr). /// Represents t^64 + t^4 + t^3 + t + 1. /// </summary> private static readonly UInt64 p_lcr = 0x000000000000001BL; /// <summary> /// It's not necessary to provide definitions for such integral constant variables as long as their /// addresses are not taken. /// Degree of the polynomial P. /// </summary> private static readonly int K = 64; /// <summary> /// Represents t^(K-1) /// </summary> private static readonly UInt64 T_K_minus_1 = (UInt64)1L << (K - 1); /// <summary> /// Broder's paper presents four pre-computed tables because words are considered to be 32-bit. /// In this implementation W is a 64-bit integral type. Eight tables are used. /// Table A is i1^127 + i2^126 + ... + i8^120. /// Table B is i1^119 + i2^118 + ... + i8^112. /// Table C, D, .. /// Table E is i1^95 + i2^94 + ... + i8^88. (This is table A in the paper.) /// Table F, G, H. /// </summary> private static UInt64[] tableA_ = new UInt64[256]; //Assuming byte size 8. private static UInt64[] tableB_ = new UInt64[256]; private static UInt64[] tableC_ = new UInt64[256]; private static UInt64[] tableD_ = new UInt64[256]; private static UInt64[] tableE_ = new UInt64[256]; private static UInt64[] tableF_ = new UInt64[256]; private static UInt64[] tableG_ = new UInt64[256]; private static UInt64[] tableH_ = new UInt64[256]; /// <summary> /// Constructor /// </summary> static RabinFingerprint() { InitTables(); } /// <summary> /// Initialize tables /// </summary> private static void InitTables() { //This represents t^(k + i) mod P, where i is the index of the array. //It will be used to compute the tables. UInt64[] mods = new UInt64[K]; //Remember t^k mod P is equivalent to p_lcr. mods[0] = p_lcr; for (int i = 1; i < K; ++i) { //By property: t^i mod P = t(t^(i - 1)) mod P. mods[i] = mods[i - 1] << 1; //If mods[i - 1] had a term at k-1, mods[i] would have had the term k, which is not represented. //The term k would account for exactly one more division by P. Then, the effect is the same //as adding p_lcr to the mod. if ((mods[i - 1] & T_K_minus_1) != 0) mods[i] ^= p_lcr; } //Compute tables. A control variable is used to indicate whether the current bit should be //considered. for (int i = 0; i < 256; ++i) { int control = i; for (int j = 0; j < 8 && control > 0; ++j) { // bool.Parse(Convert.ToString()) if ((control & 1) == 1) //Ok, consider bit. ((byte)) { tableA_[i] ^= mods[j + 56]; tableB_[i] ^= mods[j + 48]; tableC_[i] ^= mods[j + 40]; tableD_[i] ^= mods[j + 32]; tableE_[i] ^= mods[j + 24]; tableF_[i] ^= mods[j + 16]; tableG_[i] ^= mods[j + 8]; tableH_[i] ^= mods[j]; } control >>= 1; } } } /// <summary> /// Compute hash key /// </summary> /// <param name="value">Value to hash</param> /// <returns>Value</returns> private static UInt64 ComputeTablesSum(ref UInt64 value) { value = tableH_[((value) & 0xFF)] ^ tableG_[((value >> 8) & 0xFF)] ^ tableF_[((value >> 16) & 0xFF)] ^ tableE_[((value >> 24) & 0xFF)] ^ tableD_[((value >> 32) & 0xFF)] ^ tableC_[((value >> 40) & 0xFF)] ^ tableB_[((value >> 48) & 0xFF)] ^ tableA_[((value >> 56) & 0xFF)]; return value; //Pass by reference to return the same w. (Convenience and efficiency.) } /// <summary> /// Compute hask hey /// </summary> /// <param name="HashArray">Array of Ulong bytes to ahsh</param> /// <returns>Hash key</returns> private static UInt64 Compute(UInt64[] HashArray) { UInt64 w = 0L; for (int s = 0; s < HashArray.Length; ++s) w = ComputeTablesSum(ref w) ^ HashArray[s]; return w; } /// <summary> /// Compute the fingerprint /// </summary> /// <param name="source">String to compute</param> /// <returns>Hash key</returns> public static UInt64 ComputeFingerPrint(string source) { byte[] table = Encoding.Unicode.GetBytes(source); UInt64[] values = new UInt64[table.LongLength]; ConvertBytes(ref table, ref values); return Compute(values); } /// <summary> /// Compute the fingerprint, you must use this method for very large text /// </summary> /// <param name="source">String to compute</param> /// <returns>Hash key</returns> public static UInt64 ComputeFingerPrint(ref string source) { return ComputeFingerPrint(source); } /// <summary> /// Compute the fingerprint, you must use this method for very large binary data /// </summary> /// <param name="source">Data to compute</param> /// <returns>Hash key</returns> public static UInt64 ComputeFingerPrint(ref byte[] source) { UInt64[] values = new UInt64[source.LongLength]; ConvertBytes(ref source, ref values); return Compute(values); } /// <summary> /// Compute the fingerprint, you must use this method for very large binary data /// </summary> /// <param name="source">Data to compute</param> /// <returns>Hash key</returns> public static UInt64 ComputeFingerPrint(byte[] source) { return ComputeFingerPrint(ref source); } /// <summary> /// Compute byte array to Uint64 array /// </summary> /// <param name="source">Table de byte source</param> /// <param name="destination">Tableau de Uin64</param> private static void ConvertBytes(ref byte[] source, ref UInt64[] destination) { for (long i = 0; i < source.LongLength; i++) destination[i] = Convert.ToUInt64(source[i]); } } } My VB code: Imports RF Module Module1 Sub Main() Dim t As New RabinFingerprint End Sub End Module A: If you want to use instances, you need to add a non-static constructor to the C# class - currently it's only got a static constructor. There is info on diffs between static/shared in VB.Net and C# here that could be useful in resolving this. If you were doing this in C# you just call the class's static methods like UInt64 result = RabinFingerprint.ComputeFIngerprint(...); etc. In VB.Net this looks something like this: Dim result = RF.RabinFingerprint.ComputeFingerprint(...) Here is an example from MSDN of what I mean. Here both Console.WriteLine and Regex.Split are static, just like your class's methods. Dim input As String = "plum--pear" Dim pattern As String = "-" ' Split on hyphens Dim substrings() As String = Regex.Split(input, pattern) For Each match As String In substrings Console.WriteLine("'{0}'", match) Next ' The method writes the following to the console: ' 'plum' ' '' ' 'pear'
{ "pile_set_name": "StackExchange" }
Q: Wilcard Search LIKE %e.name% from INNER JOIN I am trying to do a wildcard search on a value from a joined item. Ie. SELECT ( SELECT count(*) FROM user_contacts e WHERE ece.user = 1 AND ( e.name LIKE '%u.lastname%' OR e.name LIKE '%u.firstname%' ) ) as friends_count, u.user_id, u.firstname, u.lastname FROM users u But it doesnt work. I could instead do: e.name LIKE u.lastname That would work, but that would not include the wildcard %% which I need. Any ideas? A: You could concatenate it. e.name LIKE CONCAT('%', u.lastname, '%') A: You just need to use the right syntax for concatenation for MySQL: SELECT (SELECT count(*) FROM user_contacts e WHERE e.user = 1 AND (e.name LIKE concat('%', u.lastname, '%') or e.name LIKE concat('%', u.firstname, '%') ) ) as friends_count, u.user_id, u.firstname, u.lastname FROM users u;
{ "pile_set_name": "StackExchange" }
Q: get a Json value without string key - Java JSONObject It' easy to get a value from JSON when you have the string key, but what if you have situation like that: { "images":["URL1"] } And array and no key inside? I use this code: JSONArray imagesArr = propertiesjsonObject.getJSONArray("images"); for (int y=0; i<imagesArr.length(); y++) { JSONObject imagesJsonObject = imagesArr.getJSONObject(y); String str_image_url = imagesJsonObject.get("HOW TO GET THE VALUES HERE?"); } Propably it's ultra easy. Sorry to ask but I could not find proper example. PS. I use: import org.json.JSONArray; import org.json.JSONObject; PS2: For now there is only one element in array, but in future I suppouse there might be more. A: Try with this: ArrayList<String> urls = new ArrayList<String>(); JSONArray imagesArr = propertiesjsonObject.getJSONArray("images"); for (int i = 0; i < imagesArr.length(); i++) { String str_image_url = imagesArr.getString(i); urls.add(str_image_url); } urls is an array with all the url you got Hope this helps
{ "pile_set_name": "StackExchange" }
Q: Create Sharepoint Users from webservices I'm doing a some research on the feasiblity of a Sharepoint project that has come our way. Basically, we are looking at keeping users on the SP site and an external system in sync. We have no prior experience with SP though we are familiar with ASP.net. So, what we need is the ability to create users and set user role of SP users through web services. I have read that SP doesn't have it's own users and they come from AD or SQL DB etc. And the API methods I've seen under UserGroup web service indicates that I cannot really do what I'm looking for. E.g. I can't create a user with a given username and password on SP, over WS. Is this correct? If so, does that mean we have to directly code against the SQL DB containing the ASPNET membership tables? Or is there a 3rd party component that we can deploy on the SP host that will expose the user management functionality we require? A: You are correct. SharePoint itself doesn't manage authentication; you'll need a different method. For example: NTLM, LDAP, database, or third party. More info here: http://technet.microsoft.com/en-us/library/cc262350.aspx. Once you are able to authenticate users, you then use the SharePoint web services to give users permission to content within SharePoint.
{ "pile_set_name": "StackExchange" }
Q: Multi Threaded file sync between 2 Linux servers At the moment i'm running rsync for 2.2 million files total of 250GB and that just takes ages 700K files in 6 hours. Does anyone know a rsync like tool that can do this with multiple threads so it goes faster? A: I doubt cpu is the limiting factor here. You're most likely limited by both network bandwidth for the transfer, and disk IO; especially latency for all those stat calls. Can you break down the filesystem hierarchy into smaller chunks to process in parallel? What are the source files, and what's writing or modifying them? Would it be possible to send changes as they happen at the application level?
{ "pile_set_name": "StackExchange" }
Q: What is the easiest way to remove the papery covers from the peanuts? Intention is to make peanut butter. What is the easiest way to achieve the said aim? A: Here's someone with a lot of experience doing it! video Dropping the peanuts into boiling water for a couple of minutes, then draining and rinsing in cold water is supposed to make them easier and quicker to peel. I've heard freezing them overnight helps. One method method that I have actually done is to peel them by rubbing them with a towel while they are still warm from being roasted. The trick there is to only roast small batches at a time so you can get to them all before they cool.
{ "pile_set_name": "StackExchange" }
Q: Adding a custom column data type in Active Record On my local machine I develop my Rails application using MySQL, but on deployment I am using Heroku which uses PostgreSQL. I am in need of creating a new data type, specifically I wish to call it longtext, and it is going to need to map to separate column types in either database. I have been searching for this. My basic idea is that I am going to need to override some hash inside of the ActiveRecord::ConnectionAdapters::*SQL adapter(s) but I figured I would consult the wealth of knowledge here to see if this is a good approach (and, if possible, pointers on how to do it) or if there is a quick win another way. Right now the data type is "string" and I am getting failed inserts because the data type is too long. I want the same functionality on both MySQL and PgSQL, but it looks like there is no common data type that gives me an unlimited text blob column type? The idea is that I want to have this application working correctly (with migrations) for both database technologies. Much appreciated. A: Why don't you install PostgreSQL on your dev machine? Download it, click "ok" a few times and you're up and running. It isn't rocket science :-) http://www.postgresql.org/download/ PostgreSQL doesn't have limitations on datatypes, you can create anything you want, it's up to your imagination: CREATE DOMAIN (simple stuff only) CREATE TYPE (unlimited) A: The SQL that Frank mentioned is actually the answer, but I really was looking for a more specific way to do RDBMS specific Rails migrations. The reason is that I want to maintain the fact that my application can run on both PostgreSQL and MySQL. class AddLongtextToPostgresql < ActiveRecord::Migration def self.up case ActiveRecord::Base.connection.adapter_name when 'PostgreSQL' execute "CREATE DOMAIN longtext as text" execute "ALTER TABLE chapters ALTER COLUMN html TYPE longtext" execute "ALTER TABLE chapters ALTER COLUMN body TYPE longtext" else puts "This migration is not supported on this platform." end end def self.down end end That is effectively what I was looking for.
{ "pile_set_name": "StackExchange" }
Q: Can anyone offer me some shooting advice for a wedding ceremony? I will be taking some photos at a friend's wedding. Mainly the ceremony. It will be outdoors in some very nice gardens and a little before sunset, around 6.15pm while sunset is at 7.20pm in that city. My camera is not very powerful, it is a Nikon D40 and I will be using either my Nikon fixed 50mm f1.8 or my 18-105mm (depending on the advise). I have a flash (not too good either) Yongnuo YN-560 II, which I will be using. I will probably be sitting in 1st row. I was wondering if you could give me some advise as per: - Shooting mode (S or M)? - Shutter speed, Aperture (always maximum?) - Flash pointing (directly to the subject or to the top and with a reflector?) Thanks! A: For an outdoor wedding, it sounds like you should be crossing the golden hour near the end, but still have strong light. The bigger trick will be the angle at which the sun goes down. You will want to shoot with the sun behind you if at all possible. The fact that the wedding is outdoors is actually advantageous to your cheaper camera as light levels inside for a wedding are often far, FAR lower than an outdoor wedding. You may not even need the flash at all, though if you do need it for fill, use the reflector to provide a more diffused light source unless it is not powerful enough to give the fill you need (in which case you will need to switch to direct lighting.) I'd also recommend going with the zoom lens until you can no longer get the exposures you need. While primes are great for portraits and fixed shots where you have time to get everything just right, they are a major pain to work with in a wedding where you are a secondary concern and you don't have time to fine tune everything and have to work on the fly. I usually shoot aperture mode for weddings to give me direct creative control over depth of field, but I also monitor the shutter speed and ISO closely to make sure they stay in range for what my camera is capable of doing well. Granted, I also shoot on a 5D Mark iii, so I have a much wider array of usable ISOs than you will have, but you are also outside which should provide you far more light than I normally have for interior weddings, so you should probably still have some ability to adjust ISO to get wider depths of field for shots where that is advantageous. Also, since you don't have to worry about high levels of action in a wedding, there isn't much sense in using shutter priority, though shutter priority can be handy if you are taking photos of things like the bouquet and garter tosses where you want to be able to catch it in mid-air. Another practical, but important piece of advice is to remember that you are trying to capture the event, not be the event, so do what you can to avoid being a distraction. In your case, it sounds like you will be seated in a front row so it doesn't sound like you'll be moving in front of people or anything, but also be conscious of the shutter noise and flash (if you are using it) from your camera. Sorry if that seems obvious, but there are even many professionals who seem to forget that simple fact and end up being a serious distraction during the service. Using mirror lockup and shooting from the LiveView can help reduce noise some if you don't have a quiet shutter mode on your camera, though it will decrease the speed of auto-focus unless you have one of the new hybrid AF systems in your camera. However, since you are outside, it may be difficult to use the LCD since it is bright (and the noise will also likely be less of a problem as there aren't walls to bounce off of and there are other outdoor sounds going on.) Just try to stay aware of the situation and avoid causing unnecessary distractions to people. Watch for other people trying to take photos and try to stay out of the way when you can and balance it with your need to be able to take photos. Also, it doesn't hurt to check with your friend about any guidelines they'd like to have followed (such as use of flash and what not). Often, the response is to use your judgement, but it doesn't hurt to ask.
{ "pile_set_name": "StackExchange" }
Q: Product of two transcendental numbers is transcendental Let $\alpha,\beta$ be transcendental numbers. Which of the followings are true? 1)$\alpha\beta\ \text{ is transcendental}$. 2)$\mathbb{Q}(\alpha)\ \text{is isomorphic to }\mathbb{Q}(\beta)$ 3)$\alpha^\beta\ \text{is transcendental }$ 4)$\alpha^2\ \text{is transcendental}$ I know option 4 is true. And I feel option 1 is also true, but I don't know the exact reason. While I have no idea for the remaining two. A: Let $\alpha$ be any transcendental. Then $\beta := \frac{1}{\alpha}$ is transcendental and $\alpha\cdot \beta =1$. Thus 1. is false. Consider $f \colon \mathbb Q(\alpha) \to \mathbb Q(\beta), \frac{x_0 + x_1 \alpha + \ldots + x_n \alpha^n}{y_0 + y_1 \alpha + \ldots + y_m \alpha^m} \mapsto \frac{x_0 + x_1 \beta + \ldots + x_n \beta^n}{y_0 + y_1 \beta + \ldots + y_m \beta^m}$, where the $x_i,y_j$ are rationals. Verify that $f$ is indeed an isomorphism. Notice that $e$ and $\ln 2$ are transcendental, but $e^{\ln 2} = 2$. So this is false. If $\alpha$ is transcendental, then $\alpha^n$ is transcendental for every $n \in \mathbb N$ (if there were a nontrivial polynomial $p(x) \in \mathbb Z[x]$ with $p(\alpha^n) = 0$, then let $q(x)$ be the polynomial obtained from $p(x)$ by replacing every $x^k$ in $p(x)$ with $x^{n\cdot k}$. Then $q(x)$ is nontrivial and $q(\alpha) = p(\alpha^n) = 0$, so $\alpha$ is algebraic - Contradiction!)
{ "pile_set_name": "StackExchange" }
Q: How to add a class to body tag? I want to add a class to a body tag with jQuery. For example if the URL is http://www.mywebsite.com/about_us.asp, I want add the first five letters, in this case 'about', to the body tag: <body class="about"> How can I do that? A: This should do it: var newClass = window.location.href; newClass = newClass.substring(newClass.lastIndexOf('/')+1, 5); $('body').addClass(newClass); The whole "five characters" thing is a little worrisome; that kind of arbitrary cutoff is usually a red flag. I'd recommend catching everything until an _ or .: newClass = newClass.match(/\/[^\/]+(_|\.)[^\/]+$/); That pattern should yield the following: ../about_us.html : about ../something.html : something ../has_two_underscores.html : has A: Use: $(document.body).addClass('about'); A: You can extract that part of the URL using a simple regular expression: var url = location.href; var className = url.match(/\w+\/(\w+)_/)[1]; $('body').addClass(className);
{ "pile_set_name": "StackExchange" }
Q: Can magnitude be negative? My teacher told that magnitude is the positive value of that quantity or the modulus of that quantity. he also told that vector quantities have both magnitude and direction and scalar quantities have only magnitudes and hence are always positive. However, gravitational potential energy is always negative except for being 0(at infinity) But gravitational potential energy is also a scalar quantity. So is there magnitude negative? What I thought about it was that it's magnitude is negative. Let's take an example of any vector quantity,say velocity. If a body is moving with the velocity of -5m/s, that means it is moving with a speed of 5m/s in the direction opposite to the positive direction. And here, the body is covering 5 meters every second, though it's velocity is -5m/s. But if a body has potential energy -40J, it does not mean that it has actual potential energy 40J but is in opposite direction, hence the magnitude should be negative Please tell me that will the magnitude be positive or negative? A: Scalar quantities can be negative. Instead of saying "scalar quantities have only magnitudes," a better description might be that a scalar quantity can be described using only one number per point in space. That number may be positive or negative. In contrast, a vector quantity cannot be described using only one number per point in space. In 3-d space, we need 3 numbers per point in space to describe a vector quantity. The word "magnitude," whether applied to a scalar or a vector or anything else, normally refers to a non-negative number. It is sometimes used to refer to the absolute value of a scalar, and sometimes used to refer to the norm (e.g., length) of a vector. In summary, this is how the words are typically used: Scalar typically refers to a single element of a number field (or a single element per point in space), such as a real number (which can be positive or negative) or even a complex number (this is common in the context of quantum physics). Magnitude typically refers to a non-negative real number. The real culprit here is statements like "a vector has both magnitude and direction, but a scalar has only magnitude." The last part of that statement either (1) imposes an unconventional restriction on the usage of the word "scalar," or (2) exercises unconventional freedom in the usage of the word "magnitude." A: This is a very common misconception among physics students, so let me see if I can provide some examples that will make the distinction clearer. VECTORS are quantities that have a magnitude and a direction. The magnitude of the velocity is speed, which is always positive. Examples: As you pointed out, one of the simplest examples of a vector quantity is velocity. Other good examples are forces, and momenta. For a vector $\vec{v}$, the magnitude of the vector, $|\vec{v}|$ is the length of the vector. This quantity is always positive! The magnitude of velocity, for example, is speed, which is always positive. (If a car is traveling 95 mph, A radar gun would register the speed of a car as 95 mph regardless of whether the car was going backwards, forwards, or sideways). Similarly, the magnitude of a force is always a positive number, even if the force points down. If you have $7$ N forces point up, down, left and right, the magnitude of those forces are all just $7$ N. Once again, the magnitude of a vector is its length, which is always positive. SCALARS on the other hand work entirely differently. Scalar quantities have a numerical value and a sign. Examples: Temperature is a nice simple example. Others include time, energy, age, and height. For a scalar $s$, the absolute value of the scalar, $|s|$ is simply the same numerical value as before, with the negative sign (if it existed) chopped off. We do not (or at least we shouldn't!) talk about the "magnitude" of a scalar! Conceptually, I recommend thinking about the absolute value of a scalar, and the magnitude of a vector as completely different things. If it is $-3°F$ outside, it does not make sense to talk about the magnitude of the temperature. You could, however, compute the absolute value of the temperature to be $3°F$. Note that some scalar quantities don't make sense as negative numbers: A person's age is a scalar quantity, and we don't really talk about negative age. Another example is temperatures measured on the kelvin scale. So, to answer your question, energy is a scalar, so it does not have a magnitude. If a body has -40J of potential energy, then it simply has 40J less than your arbitrary 0 point. It does not make sense to talk about the magnitude of this scalar quantity. Please let me know if that helped or hurt your understanding!
{ "pile_set_name": "StackExchange" }
Q: Enable hardware-accelerated desktop effects with NVIDIA Optimus/Bumblebee I'm pretty new to Linux and I'm trying to install Ubuntu 12.04 on my personal laptop, a Dell XPS 15. It has an NVIDIA GT540M with Optimus. Conveniently, there's no way to disable Optimus in the BIOS. lspci output: 00:02.0 VGA compatible controller: Intel Corporation 2nd Generation Core Processor Family Integrated Graphics Controller (rev 09) 01:00.0 VGA compatible controller: NVIDIA Corporation GF108 [GeForce GT 540M] (rev a1) I have bumblebee installed and it seems to work fine. I've been using glxgears from mesa-utils to test it. I'm not sure if this is normal, but running "glxgears" by itself gives: Error: couldn't get an RGB, Double-buffered visual But "optirun glxgears" works fine, getting framerates around 5800-6000 in 5 seconds. My only issue is that the hardware-accelerated desktop effects aren't working. I can't enable wobbly windows or any animations. Worst of all, the Aero-like window-maximizing effect doesn't work. I haven't been able to get that effect enabled at all, even though it worked when I ran off the USB drive. I'm only assuming it's linked to my video card issues, but if there's a way to enable it please let me know! Is it that optirun uses the NVIDIA drivers, but the intel drivers aren't setup properly? Did I miss a step? Here's one more screenshot. It's also worth noting this is a 64 bit install of Ubuntu! A: If you use nvidia-current-updates, you have to edit /etc/bumblebee/bumblebee.conf and set KernelDriver=nvidia-current-updates under [driver-nvidia]. It sounds that you've just installed Bumblebee, but that you've selected the universe repository during installation. That pulled in the nvidia driver which broke your 3D acceleration and other OpenGL capabilities. Try restarting the X server, e.g. by rebooting the machine. In case the issue still persists, it is possible that some libraries have been installed in a wrong location. After installation of Bumblebee, /usr/lib/xorg/modules/extensions/ should not contain libglx.so, libglx.so.VERSION or nvidia_drv.so. If that is the case, remove those files (it requires root privileges): sudo rm -f /usr/lib/xorg/modules/extensions/libglx.so* /usr/lib/xorg/modules/extensions/nvidia_drv.so You may also have to reinstall the nvidia-current package if Bumblebee does not work afterwards: sudo apt-get install --reinstall nvidia-current Re-login and your problem should be solved.
{ "pile_set_name": "StackExchange" }
Q: Mount Mac disk image (and sparse bundle) on Windows or Linux Is it possible to mount the various disk image formats that Mac OS uses on other platforms? I suppose one problem would be that the file system in that image is usually HFS+. I am specifically interested in creating (AES) encrypted sparse bundles, so that I can securely store them for backup purposes. Being able to mount those on a non-Mac machine would be convenient. A: It appears that HFSExplorer gained support for sparsebundles in 0.22 (including encrypted ones). It can only browse/extract, though, not actually mount into the native filesystem interface. So your question may not have had a good answer in 2009, but it does now for anyone else who finds this in while searching :-) A: For mounting .dmg files in Windows, and making it readable, you can always use MacDrive. However, no solution currently exists for mounting encrypted Mac sparse bundles.
{ "pile_set_name": "StackExchange" }
Q: Ungzip csv files in web browser with javascript I want to download gzipped csv files from a web server and ungzip then in the browser. So far I have tried using pako and zlib to take a file gzipped on my server, but have had various issues. Trying to unzip a unix-gzipped file, I kept getting an incorrect header message. Next, I tried using node to zip the file on the server, and am currently getting this error Uncaught Error: invalid file signature:,� Here is the command I am using to get the file: $.ajax({ type: "GET", url: 'public/pols_zlib.csv.gz'}) .done(function(d){ var gunzip = new Zlib.Gunzip(d); plain = gunzip.decompress(); }); I am looking for any way to zip a file on my server and unzip it in the browser. A: I believe my earlier answer has value so I am creating a separate one here that addresses this more specific use case. The conditions are: cannot control the server must limit the file size of the csv's prior to uploading the server is not encoding the csv's with gzip I suggest using the JSXCompressor library to decode gzip files in javascript on the client. However, the gzip'd files must first be base64 encoded. The following linux command will do this: gzip -c file.csv | base64 > file.csv.gz.txt I recommend using the .txt file extension to ensure the server handles it like text. Since I'm using the DataURI to download the csv (see below), you could also base64 encode it before gzipping to save doing that on the client. However, it increases the file size (which you are trying to avoid). Once the files are gzip'd & base64'd, then can be uploaded to the server. Note that base64 will add substantial overhead but it is required. It is more pronounced with smaller files: uncompressed: 91 kB compressed: 38 kB compressed + base64: 72 kB uncompressed: 8.2 MB compressed: 1.9 MB compressed + base64: 2.6 MB Here is the HTML markup. This is a working example that I have tested. <html> <head> <title>Working Example</title> <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script src="jsxcompressor.min.js" type="text/javascript"></script> <script type="text/javascript"> $.ajax({ url: "/file.csv.gz.txt", cache: false }) .done(function (b64file) { // $('body').append(b64file); // debug var binary = JXG.decompress(b64file); $('#link').attr("href", "data:text/csv;base64," + btoa(binary)); }); </script> </head> <body> <a id="link" download="file.csv">file</a> </body> </html>
{ "pile_set_name": "StackExchange" }
Q: How to completely rid my potting soil/container of fungi which seems to continually attack my plants So, after so many dead plant and ruts, I have come to realize that for some reason, my plants seem to contract some fungal issue most every week. I am not exactly sure why but I have had to pluck up brown roots from most all of my current stock at least 1 every week in January and I wonder how much longer I can keep this up. I have resorted to soaking the roots in fungicide solution before replanting, and this of course is after changing out the potting soil failed. I have made certain to test and retest drainage on most all the posts, even adding stones and more holes to help in any way possible but somehow the roots keep getting infected after a couple of days. How can I completely rid my plants of fungal infections for pete's sake? Thanks in advance. A: I would also suggest that you only water the plants in the morning when the excess water will evaporate in the sunlight. I made this mistake several times with midnight watering which caused my salvia, Rosemary and lemon verbena to drown first then get fungal disease. A: Your question has more context when we read your first question about night blooming jasmine dying back. It appears that your indoor plants are dying and you don't know, but suspect, virus/fungus/bacteria. You can try these actions and see if they help: get rid of all existing potting soil wash all your empty pots in soap and water and scrub off all mineral and soil deposits disinfect all trimmers, pruners, scissors with bleach from your comments I also recommend that you do not use moisture control potting soil unless you can supply a high light environment. reexamine your watering practices. Studies have shown that the majority of indoor plant deaths are due to overwatering consider capillary mats or water wicks to supply only what the plants need Buy a test plant and put in a separate area from your other plants. Ensure that the light and temperature requirements of the plant are met. Do not repot it, do not treat with anything on arrival. Many of the virus/fungus/bacteria problems that indoors plants face come from these sources: too much water leads to soggy soil with no air pockets. Roots die and provide an entry point. cool temperatures and moist can provide the right environment for some pathogens soil splashing onto leaves can be a vector for some pathogens but this is rarer in indoor plants growers can have even more problems with pathogens which can infect an entire crop.See this production guide for Christmas cactus as an example of the problems that can happen. In some cases a newly purchased plant can look good but already be infected. The best solution is to provide an optimum environment with minimum shock. (There is no need to repot a new plant right away, wait and observe) A: I'm still not possessing enough information about the problem, but from what I can glean throughout your comments, it seems you observe the plants wilting before dying. You also say you've tried brand new pots and brand new potting compost, and that you use a moisture control compost, and don't overwater. Nonetheless, it sounds likely the plants are suffering from too much water, though its hard to be definite with so little information. Four questions - when you water, you presumably do it when the surface of the compost feels dry to the touch, but not so dry its shrunken from the sides of the pot? Second, do you water thoroughly when you do it? Third question, what are the plants standing in to stop water flooding your home or furniture? If they're standing in an outer pot or tray, do you empty that tray or pot 30 minutes after watering, and then again 30 minutes later if necessary, or do you leave any water that collects to sit there? If you are doing the latter, that could be the cause of plant death.
{ "pile_set_name": "StackExchange" }
Q: C# Newbie - Nested methods yet another System.NullReferenceException-Object error For purposes of learning, I've setup a method to call upon another method to display a value I defined via user input. However, I end up getting a nasty error: System.NullReferenceException - Object reference not set to an instance of an object Could someone please explain what I'm doing to cause the error; and, make this work without changing the code too much (keeping the nested methods). Program.cs namespace Test { class Program { static void Main(string[] args) { Parent theParent = new Parent(); Console.WriteLine("Enter Child Name:"); string input = Console.ReadLine(); theParent.Child.Name = input; theParent.FirstMethod(); Console.ReadLine(); } } } Parent.cs namespace Test { class Parent { public Child Child = new Child(); //I changed this line. It was originally only 'public Child Child' public void FirstMethod() { Child newChild = new Child(); newChild.SecondMethod(); } } } Child.cs namespace Test { class Child { private string name; public string Name { get { return name; } set { name = value; } } public void SecondMethod() { Parent theParent = new Parent(); Console.WriteLine(theParent.Child.Name.ToString()); } } } A: Reference types (classes) are initialized to null. In your Parent type, you declare Child like this: public Child Child; This makes the Child field null. You need to initialize it inline.. or set it in a constructor: public Child Child = new Child(); ...or... public Parent() { Child = new Child(); } ..or even inline when declaring the Parent object: Parent theParent = new Parent() { Child = new Child() }; Same for any others like this. A: Your Child is null. First you create a new Parent: Parent theParent = new Parent(); This has a public field child (note: use a property, not a public field): public Child Child; As you can see: this is uninstantiated. Then you use this child: theParent.Child.Name = input; But child is null! Thus, the NullReferenceException. You have to instante the child field: public Child Child = new Child(); Or in another place, that's up to you. Sidenote about the public field: you're breaking encapsulation by providing direct access to an instance member. You should use getters & setters (in C# conveniently provided by a property). New situation: void Main() { Parent theParent = new Parent(); string input = "jack"; theParent.Child.parent = theParent; // ADD THIS theParent.Child.Name = input; theParent.FirstMethod(); } class Parent { public Child Child = new Child(); //I changed this line. It was originally only 'public Child Child' public void FirstMethod() { // Child.parent = this; // REMOVE THIS Child.SecondMethod(); } } class Child { public Parent parent; private string name; public string Name { get { return name; } set { name = value; } } public void SecondMethod() { Console.WriteLine(parent.Child.Name); } } Output: jack
{ "pile_set_name": "StackExchange" }
Q: Why doesn't Spring throw DataAccessException in the event that Hibernate throws ObjectNotFoundException? Why doesn't Spring 3.0.4 HibernateTemplate method load() throw DataAccessException or more specifically, ObjectRetrievalFailureException, in the event that Hibernate 3.3.2GA throws ObjectNotFoundException? 2010-12-15 13:16:03,939 133247782 [[ACTIVE] ExecuteThread: '0' for queue: 'weblogic.kernel.Default (self-tuning)'] INFO org.hibernate.event.def.DefaultLoadEventListener - Error performing load command org.hibernate.ObjectNotFoundException: No row with the given identifier exists: [com.db.spgit.abstrack.model.ConsUsCustomMark#78445AAD8] at org.hibernate.impl.SessionFactoryImpl$1.handleEntityNotFound(SessionFactoryImpl.java:375) ~[hibernate-3.2.1.ga.jar:3.2.1.ga] at org.hibernate.event.def.DefaultLoadEventListener.load(DefaultLoadEventListener.java:145) ~[hibernate-3.2.1.ga.jar:3.2.1.ga] at org.hibernate.event.def.DefaultLoadEventListener.proxyOrLoad(DefaultLoadEventListener.java:179) ~[hibernate-3.2.1.ga.jar:3.2.1.ga] at org.hibernate.event.def.DefaultLoadEventListener.onLoad(DefaultLoadEventListener.java:103) ~[hibernate-3.2.1.ga.jar:3.2.1.ga] at org.hibernate.impl.SessionImpl.fireLoad(SessionImpl.java:878) [hibernate-3.2.1.ga.jar:3.2.1.ga] at org.hibernate.impl.SessionImpl.load(SessionImpl.java:795) [hibernate-3.2.1.ga.jar:3.2.1.ga] at org.hibernate.impl.SessionImpl.load(SessionImpl.java:788) [hibernate-3.2.1.ga.jar:3.2.1.ga] at org.springframework.orm.hibernate3.HibernateTemplate$3.doInHibernate(HibernateTemplate.java:558) [spring-orm-3.0.4.RELEASE.jar:3.0.4.RELEASE] at org.springframework.orm.hibernate3.HibernateTemplate.doExecute(HibernateTemplate.java:406) [spring-orm-3.0.4.RELEASE.jar:3.0.4.RELEASE] at org.springframework.orm.hibernate3.HibernateTemplate.executeWithNativeSession(HibernateTemplate.java:374) [spring-orm-3.0.4.RELEASE.jar:3.0.4.RELEASE] at org.springframework.orm.hibernate3.HibernateTemplate.load(HibernateTemplate.java:551) [spring-orm-3.0.4.RELEASE.jar:3.0.4.RELEASE] at org.springframework.orm.hibernate3.HibernateTemplate.load(HibernateTemplate.java:545) [spring-orm-3.0.4.RELEASE.jar:3.0.4.RELEASE] A: The exception is being logged, not necessarily thrown. What you see there is a log to info level of the exception stack trace, done by hibernate. If you look at the source code of DefaultLoadEventListener(line 134 in my version of the source) you will notice that it logs the exception and then rethrows. All we're seeing here is a log of the exception stack trace - there is no evidence here that spring is not transforming the exception.
{ "pile_set_name": "StackExchange" }
Q: emacs23 pops up debugger way too frequently Since I've upgraded to Ubuntu lucid and emacs23, Emacs pops up the debugger in situations, where emacs22 does not. For example, when hitting C-c C-c in org-mode, emacs22 simply states can do nothing useful at this location, whereas in emacs23 the debugger shows up. Debugger entered--Lisp error: (error "C-c C-c can do nothing useful at this location") signal(error ("C-c C-c can do nothing useful at this location")) error("C-c C-c can do nothing useful at this location") org-ctrl-c-ctrl-c(nil) call-interactively(org-ctrl-c-ctrl-c nil nil) That only illustrates the pattern -- the behavior is not limited to org-mode. Occurring every 3 minutes, it really annoys me. How can I prevent it? I've already tried to stop this using debug-on-error and stack-trace-on-error: it didn't work. A: Chances are that something is setting debug-on-error after you've configured it. Some ways to confirm: Start Org Mode, press C-c C-c to enter the debugger, and q to exit again. Now M-x set-variable RET debug-on-error RET nil RET, and try it again. Next, try starting emacs with the -q argument (to avoid executing your init file), and then entering org mode and hitting C-c C-c. This should not trigger the debugger. You could use M-x rgrep RET debug-on-error RET (or maybe debug-on-error t) on your site-lisp and custom lisp directories, to help track down which library is responsible. As I could replicate your issue, I've just done this for myself. For me, the culprit was: (load "nxhtml/autostart.el"). I'm upgrading nxhtml now, which I suspect will resolve things in my case. Edit: or not. The current version of nxhtml has moved the statement from autoload.el into nxhtml-base.el. If this is the same culprit for you, you could either edit that file, or make sure that your customisation of the variable happens after nxhtml's autostart file executes.
{ "pile_set_name": "StackExchange" }
Q: How to find what day of the week for any given date using Cocoa I'm trying to figure out what day (i.e. Monday, Friday...) of any given date (i.e. Jun 27th, 2009) Thank you. A: I've been doing: NSDateFormatter* theDateFormatter = [[[NSDateFormatter alloc] init] autorelease]; [theDateFormatter setFormatterBehavior:NSDateFormatterBehavior10_4]; [theDateFormatter setDateFormat:@"EEEE"]; NSString *weekDay = [theDateFormatter stringFromDate:[NSDate date]]; This has the added bonus of letting you choose how you'd like the weekday to be returned (by changing the date format string in the setDateFormat: call Lots more information at: http://developer.apple.com/documentation/Cocoa/Conceptual/DataFormatting/Articles/dfDateFormatting10_4.html#//apple_ref/doc/uid/TP40002369 A: You may have a look to the NSDate and NSCalendar classes. For example, here and here They provide the following code: NSDate *today = [NSDate date]; NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar]; NSDateComponents *weekdayComponents = [gregorian components:(NSDayCalendarUnit | NSWeekdayCalendarUnit) fromDate:today]; NSInteger day = [weekdayComponents day]; NSInteger weekday = [weekdayComponents weekday]; A: Use NSCalendar and NSDateComponents. As shown in the NSDateComponents documentation: NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar]; NSDate *date = [gregorian dateFromComponents:comps]; NSDateComponents *weekdayComponents = [gregorian components:NSWeekdayCalendarUnit fromDate:date]; int weekday = [weekdayComponents weekday];
{ "pile_set_name": "StackExchange" }
Q: When does the continuous Galois(=etale) cohomology of fields coincide with the naive one? Often true by the Bloch-Kato conjecture? For a field $F$ I am interested in its $l$-adic (Galois=\'etale) cohomology; here $l$ is a prime distinct from the characteristic of $F$ (for simplicity one may assume that the latter is $0$). For $i,j\in \mathbb{Z}$ one can define the corresponding "naive" cohomology group as $\varprojlim_n H^i(F, \mathbb{Z}/ l^n\mathbb{Z}(j))$. This is not a very "good" definition; the "correct" cohomology groups of $F$ are the continuous ones (defined by Jannsen) that take into account the (first) derived projective limit (functor) for the system $H^i(F, \mathbb{Z}/ l^n\mathbb{Z}(j))$. My question is: when does the latter $\varprojlim{}^1$-group necessarily vanishes or (at least) torsion? It seems that the Bloch-Kato conjecture yields: the transition maps are surjective (and so, $\varprojlim{}^1$ vanishes) if $j=i$. Is this correct? Are there any general results of this sort available for $j\neq i$ (and if $K$ does not contain all $\mu_{l^n}$)? For example, what is known for $j=1$, $i=2$ (this case is closely related to the Brauer group)? A: There are two questions here: when does the $\varprojlim\nolimits^1$ of a sequence of abelian groups $M_1 \longleftarrow M_2\longleftarrow M_3\dotsb$ vanish, and what can be said about the Galois cohomology with cyclotomic coefficients. Concerning the first question: this is called the Mittag-Leffler condition, and I recall it being formulated as follows. The $\varprojlim\nolimits^1$ vanishes if, and perhaps also only if, for every $i>0$ the decreasing sequence of subgroups $\operatorname{im}(M_i\leftarrow M_j)$ eventually stabilizes in $M_i$ as $j$ grows to infinity. Concerning the second question: certainly, it follows from the Milnor-Bloch-Kato conjecture that $\varprojlim_n{}^1 H^i(F,\mathbb Z/l^n\mathbb Z(j))=0$ when $i=j$, because this is a sequence of surjective maps of abelian groups. For $i\ne j$, this $\varprojlim\nolimits^1$ vanishing should not be true in general.
{ "pile_set_name": "StackExchange" }
Q: Find the maximum of $x^{x^{x^{⋰}}}.$ Question: Find the maximum of $x^{x^{x^{⋰}}}.$ Let $y = x^{x^{x^{⋰}}}.$ Then \begin{align} y & = x^y \\ \Rightarrow \ln y & = y\ln x \\ \Rightarrow \frac{1}{y} \frac{dy}{dx} & = y\left(\frac{1}{x}\right) + \ln x \cdot \frac{dy}{dx}. \end{align} Since we are looking for maximum, we set $\frac{dy}{dx} = 0.$ So, $$\frac{y}{x} = 0$$ $$\Rightarrow y = 0.$$ I am not sure what's wrong here. A: If we are allowed to consider values of $x$ s.t. this tends to $\infty$, then the answer is trivially $\infty$. Assuming the question is concerned with the interval over which this converges to real numbers though: Note that when $y=0$, you get $0=x^0$, which is a contradiction. Instead, the maxima in this case occurs when $y'=\infty$. Dividing everything by $y'$ and letting it go to infinity gives us $$\frac1y=\frac y{xy'}+\ln(x)$$ $$\frac1y=\ln(x)\tag{as $y'\to\infty$}$$ $$1=y\ln(x)$$ Since we also know that $\ln(y)=y\ln(x)$, we end up with $\ln(y)=1$, or $y=e$, which occurs at $x=\sqrt[e]e$. For more information on convergence, see here.
{ "pile_set_name": "StackExchange" }
Q: Is Stack Overflow a Wikipedia done right? I discovered Stack Overflow from some months, now, as a reader, and since last week as a member. But I was deeply involved in the growing of Wikipedia between 2003 and 2008, and what I saw didn't always made me happy. I get the impression that the process in Stack Overflow is very similar to the one in Wikipedia, but with some lessons understood in the meanwhile: Not all contributors have the same worth, both in knowledge and motivations. Let's go the end of the community-thought and let the community rate its own members, by rating their contributions Avoid the appearance of cliques by giving the rights progressively to the members I think that now, Wikipedia could have some things to learn from Stack Overflow. Has anybody some thoughts about this? A: While I think Wikipedia could learn some things from this healthy Q&A ecosystem, I don't think they're the same thing. It's much easier to get people answer questions in an unbiased way with rep, than it is to get people to speak on religion, political figures, and history in an unbiased way. In short, it's apples and oranges. Look at the About page. Stack Overflow is a little bit wiki, and a lot of other things. This system works for what we do here; I'm not sure everything here applies to a pure wiki. A: Interesting to hear this from somebody somewhat involved in Wikipedia. I must admit that I've been thinking about contributing to WP a few times, but was always put off by the strong feeling of being an outsider to a rather closed group, and what felt to me like both a complicated user interface and hierarchy - I have had a very hard time really understanding how things work there (and I'm a software developer!) It is certainly true that the SO community feels more transparent and open than the lot of Wikipedia's editors. I would welcome Stack Overflow-y elements on WP, although I can think of a number of valid counter-arguments - the reputation system is great and a strong motivator, but it puts more emphasis on individuals than an encyclopedia might want. Also, the size of the community on Wikipedia is still orders of magnitude larger than anything in the Stack Exchange network. Whether SO's community system will work without changes for those kinds of numbers is yet to be determined (although it's well possible that it will). A: Another big difference is that Stack Overflow, Super User, Server Fault, etc are specifically how to sites. Wikipedia is not a how to.
{ "pile_set_name": "StackExchange" }
Q: Is it possible to Assert a method has been called in VS2005 Unit Testing? I'm writing some unit tests and I need to be able to Assert whether a method has been called based upon the setup data. E.g. String testValue = "1234"; MyClass target = new MyClass(); target.Value = testValue; target.RunConversion(); // required Assertion Assert.MethodCalled(MyClass.RunSpecificConversion); Then there would be a second test where testValue is null and I would want to assert that the method has NOT been called. Update for specific test scenario: I haev a class which represents information deserialized from XML. This class contains a number of pieces of information that I need to convert into my own classes. The XML class is information about a person, including account info and a few phone numbers in different fields. I have a method to create my Account class from the XML class, and methods to create the correct phone classes from the XML class. I have unit tests for each of these methods, but I'd like to test that when the account convertion is called, it runs the phone conversions as the results are actually properties of the account class. I know I could test the properties of the account class after feeding in the correct information, however I have otehr nested properties that have further nested and testing the entire tree could become very cumbersome. I guess I could just have each level test the next level below it, but ideally I'd like to make sure the correct conversino methods are being called and the code is not being duplicated in the implementation. A: Without using a Mocking framework such as Moq, TypeMock, RhinoMocks that can verify your expectations, I would look at parsing the stack trace. The MSDN documentation here should help. Kindness, Dan
{ "pile_set_name": "StackExchange" }
Q: Can you use Facebook "Test Users" to test a Messenger Bot? I'm currently trying to make a Messenger Bot with the Messenger Platform. I have a Facebook page, app, everything set up, it currently works when I (an admin for the app) message it. So, I made a few test users to test it with more users. But, whenever I login as a test user, I can't seem to message the page. As a test user, I can't access the page, and a direct Messenger link gives an "access denied" page. As an admin, I tried to add this test users as a "Tester" under the roles, but I also get more "access denied" messages. So, is there a way to use a Facebook Test User to interact with my pre-approved Messenger Bot? A: A working workaround was described here: http://developers.facebook.com/bugs/230322797329131/?hc_location=uf‌i Kudos to Alex Garcia himself :)
{ "pile_set_name": "StackExchange" }
Q: Is Content-Type HTTP header always required? This question is about browser behavior as well as protocol specification for linking, importing, including or ajaxing css, js, image and other resources from within html, js or css files. While testing static files and compressed content delivery in different browsers, I found that some browsers start behaving differently if you move away from conventions. For example, IE6 creates problem if you do not send Content-Disposition: inline; header for all inline css and js etc files, and a recent version of safari does not properly handle pre-compressed gzip CSS files if you use file extension .gz like in main-styles.css.gz. My question is about the behavior of browsers about Content-Type response header. Since <link>, <script> and <img> tags already reasonably specify the content type of the resource, can this header be safely skipped, or do some browsers require it for some historical reason? A: In short, no, it's not required. But it's recommended. Most browser that I know of will treat <link>, <script>, and <img> properly if they are not sent with headers, but there's no real good reason not to send the headers. Basically, without Content-Type headers, the browser is left to try and guess based on the content. From RFC2616: Content-Type specifies the media type of the underlying data. Content-Encoding may be used to indicate any additional content codings applied to the data, usually for the purpose of data compression, that are a property of the requested resource. There is no default encoding. Any HTTP/1.1 message containing an entity-body SHOULD include a Content-Type header field defining the media type of that body. If and only if the media type is not given by a Content-Type field, the recipient MAY attempt to guess the media type via inspection of its content and/or the name extension(s) of the URI used to identify the resource. If the media type remains unknown, the recipient SHOULD treat it as type "application/octet-stream". Regarding the keyword SHOULD, specified in RFC2119: SHOULD: This word, or the adjective "RECOMMENDED", mean that there may exist valid reasons in particular circumstances to ignore a particular item, but the full implications must be understood and carefully weighed before choosing a different course.
{ "pile_set_name": "StackExchange" }
Q: How to avoid null value in textbox $(document).on("click", "label.radeem-textbox", function () { var txt = $(".mytxt").text(); $(".radeem-textbox").replaceWith("<input class='radeem-textbox redeem-textbox'/>"); $(".radeem-textbox").val(txt); return false; }); $(document).on("blur", "input.radeem-textbox", function () { var txt = $(this).val(); $(this).replaceWith("<label class='radeem-textbox'></label>"); $(".radeem-textbox").text(txt); }); <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script> <a href="javascript:void(0)" class="right-side-margin-top right-side-margin-bottom display-block add-to-wishlist"> <label class="add-to-wish radeem-textbox">Redeem a Coupon</label> </a> I have jquery code for label convert to textbox on click. But when i not enter nothing on textbox, the textbox and label is not showing.. So how to make textbox focused if not enter nothing.. <label class="add-to-wish radeem-textbox">Redeem a Coupon</label> <script type="text/javascript"> $(document).on("click", "label.radeem-textbox", function () { var txt = $(".mytxt").text(); $(".radeem-textbox").replaceWith("<input class='radeem-textbox'/>"); $(".radeem-textbox").val(txt); return false; }); $(document).on("blur", "input.radeem-textbox", function () { var txt = $(this).val(); $(this).replaceWith("<label class='radeem-textbox'></label>"); $(".radeem-textbox").text(txt); }); A: Add with if(txt.trim()). trim() It will validate the input box is empty or not.Its only allowed its not empty,null . $(document).on("click", "label.radeem-textbox", function () { var txt = $(".mytxt").text(); $(".radeem-textbox").replaceWith("<input class='radeem-textbox'/>"); $(".radeem-textbox").val(txt); return false; }); $(document).on("blur", "input.radeem-textbox", function () { var txt = $(this).val(); if(txt.trim()){ $(this).replaceWith("<label class='radeem-textbox'></label>"); $(".radeem-textbox").text(txt); } else{ console.log('enter text please') } }); <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <label class="add-to-wish radeem-textbox">Redeem a Coupon</label> Alternative way is : update with label tag contenteditable its same as your thing <label contenteditable="true">Click me to edit me</label>
{ "pile_set_name": "StackExchange" }