source
sequence
text
stringlengths
99
98.5k
[ "electronics.stackexchange", "0000443808.txt" ]
Q: Sizing the pulldown resistors for 74HCT08 logic inputs I have come across some text or blog before but I cannot find the source that: when we use 74HCT08 AND gate IC and for the logic inputs if we use pulldown resistors to prevent floating then we need to use the resistor pulldown resistor values Rp low such that the input should not rise over 0.9V. Regarding a such input as hand drawn below: Why does the value of resistor matter and how could high values make the input higher than 0.9V when the switch is open? A: If you know nothing about CMOS, you need ohms law, a data sheet, and some common sense. If you know something about CMOS, then just the common sense will do. Per the data sheet, the input leakage current for a 74HCT08 is \$1 \mathrm{\mu A}\$. Per ohms law, this means we need \$R < \mathrm{\frac{0.9V}{1\mu A} = 900k\Omega}\$. Common sense says that unless we're designing something for insanely low current consumption, and for which we can guarantee an electrically quiet environment, using the maximum resistance here is silly. So choose something convenient, like \$\mathrm{10k\Omega}\$. A basic knowledge of CMOS says that for all practical purposes a CMOS chip's input current is nothing -- so you fall back on common sense, and you're done. Note: that this is not the case for a lot of modern microcontrollers -- they are often designed so that without the pins being programmed, they have built-in weak pull-ups, to reduce current, and for historical reasons (see my final note, below). But sometimes they have built-in weak pull-downs on some pins, for practical reasons. So always read the data sheet. Final note: If you were designing circuits 30 years ago, then the gate in question may well have been TTL. In that case, you would want a pull-up resistor (because TTL inputs source a bit of current, but sink less). Then you'd use the same \$\mathrm{10k\Omega}\$, but it would be to VCC. There is no reason not to do this for CMOS, and it's oh-so-slightly more comfortable for old circuit designers when they see it.
[ "stackoverflow", "0056572681.txt" ]
Q: initialization Standard for char[](c-string) consider the following piece of code: int main(){ char hi[5] = "Hi!"; printf("%d", hi[4]); } What will be printed? More importantly, Is there a mention in the standard about what will be printed, in the newest C++ standards? If there is a mention, where is it? For some reason recent information about this is tremendously hard to find, and various sources have conflicting information. I've tried en.cppreference.com and cplusplus.com, the former did not have any info, the latter claimed the values are undetermined. However, using namespace std; int main(){ char mySt[1000000] = "Hi!"; for(int i=0;i<1000000;++i){ if(mySt[i]!='\0') cout << i <<endl; } } This prints only 0, 1, and 2 on my system, and so I expect the "rest" to be initialized to '\0'. Also to my knowledge char mySt[100000]="" initializes the whole array '\0', and it just feels awkward to say that it's different with any other string literal. However my instructor claims otherwise(he claims it is "undefined"), I need to back up my claim with recent and concrete evidence, if there is any. I compiled on MinGW g++ 8.2.0. Thank you in advance. To clarify, A: In both C++17 and the current C++20 draft, section [dcl.init.string] discusses initializing a character array with a string literal. Paragraph 3 of that section reads: If there are fewer initializers than there are array elements, each element not explicitly initialized shall be zero-initialized. So yes, all array elements beyond the ones initialized by characters in the literal are guaranteed to be zero values.
[ "stackoverflow", "0057064598.txt" ]
Q: Are you able to define a named function within sorted()? I am trying to define a function in the 'key' parameter of a sorted() function. I can get this to work by using a lambda function, however i was wondering if it was possible to split up my code, for readability (so i can spread it across multiple lines), to add a defined function in the key parameter. sorted_contacts = sorted(contacts_array, key= def d(x): #...do something here ); SyntaxError: invalid syntax Sorted_contacts = sorted(contacts_array, key= def d(x): ^ A: This is not possible in Python. Named functions are statements, and function arguments must be expressions. The closest you'll get is a lambda function, but it can only have one line of code. To solve your problem, you can define the function outside the call, and then reference it: def d(x): ... return ... sorted_contacts = sorted(contacts_array, key=d) This is due to the fact that in Python, functions are first-class objects, which means that they are useable in an expression like any other object (integer, string, class instance, etc.)
[ "english.stackexchange", "0000112181.txt" ]
Q: Single word for "unqualified truth" Suppose someone (let's call him Alex) is bad at playing soccer, but he does not want to hear that. Now if someone says to Alex in his face, "you are a really bad soccer player", what would be an apt word for that? In my mother tongue it is called "unqualified truth" for Alex. Is there an equivalent English term? A: You could use frankness, the adjective frank or the adverb frankly. These usually imply directness and honesty which may be uncomfortable or unpleasant to hear. A: As suggested by other answers, blunt, frank and candid are all appropriate adjectives for a person willing to express even unpleasant truths. An idiom for the action itself is to give it to [someone] straight. Another option (and one more similar in form to your direct translation of the original) is the unvarnished truth. A: I've used "blunt" or "bluntly" in the past. "Alex is an awful footballer, putting it bluntly"
[ "stackoverflow", "0007565068.txt" ]
Q: upload images having an url I have a script to upload files to the server from your computer. It works fine and basically it's a <form enctype="multipart/form-data" action="post_img_upload.php?id='.$topicid.'" method="POST"> <input name="uploaded_file" type="file" /> <input type="submit" value="Subila" /> then, the post_img_upload.php starts like this: $target = "pics/"; $fileName = $target . $_FILES["uploaded_file"]["name"]; // The file name $fileTmpLoc = $_FILES["uploaded_file"]["tmp_name"]; // File in the PHP tmp folder $fileType = $_FILES["uploaded_file"]["type"]; // The type of file it is $fileSize = $_FILES["uploaded_file"]["size"]; // File size in bytes $fileErrorMsg = $_FILES["uploaded_file"]["error"]; // 0 for false... and 1 for true $fileName = preg_replace('#[^a-z.0-9]#i', '', $fileName); // filter the $filename $kaboom = explode(".", $fileName); // Split file name into an array using the dot $fileExt = end($kaboom); Now I want to have the option to upload a file having an url address. Another form basically with <form action="post_img_url_upload.php?id='.$topicid.'" method="POST"> <input name="url" type="text" size="100" /> <input type="submit" value="Copiar"/> I would like to have post_img_url_upload.php similar to the post_img_upload.php. How can I approach that? How can I basically write $fileName = $target . $_FILES["url"]["name"]; ? Is it doable? Thanks! A: AFAIK, no. The server would only get the url string, and then should try to fetch the image itself (instead of the image data being transferred from the client). You could google for "php external request" as there are a couple of ways to do it (cURL, remote file access, etc.).
[ "stackoverflow", "0033898841.txt" ]
Q: Integrity_Error (key is still referenced) thrown even with on_delete=do_nothing I have a model: class Project(Model): name = models.TextField(...) ... bunch of fields ... I also have some models that track history in my application. These models have ForeignKey references to the Project model: class Historical_Milestone(Model): project = models.ForeignKey('Project', db_index=True, related_name='+', on_delete=models.DO_NOTHING, blank=True, null=True) When I delete an item in my Project table, I get the following IntegrityError: update or delete on table "project" violates foreign key constraint {...} on table "historical_milestone" DETAIL: Key (id)=(123) is still referenced from table "historical_milestone". The column in the historical table has related_name='+' set (indicating that I don't want the reverse lookup), and I have the on_delete=models.DO_NOTHING parameter set. According to the documentation on the DO_NOTHING option: If your database backend enforces referential integrity, this will cause an IntegrityError unless you manually add an SQL ON DELETE constraint to the database field. Shouldn't the related_name flag indicating I don't care about the reverse relationship take care of this? What manual step do I need to take to modify the Historical_Milestone table to prevent this error from happening? A: The related_name is for convenience, it doesn't affect the foreign key constraints that Django creates. Setting related_name='+' simply means you don't want to be able to access product.historical_milestone_set (or similar) in the ORM. If you want to keep the id after the project is deleted, and not enforce a foreign key constraint, it might be better to use an integer field. class Historical_Milestone(Model): project_id = models.PositiveIntegerField(db_index=True, blank=True, null=True)
[ "stackoverflow", "0063661474.txt" ]
Q: How can I encode an array of simd_float4x4 elements in Swift (convert simd_float4x4 to Data)? I am building an app that captures facetracking data from the iPhone TrueDepth camera. I need to write this data to files so I can use it as the basis for another app. Within the app, the data is saved into four separate arrays, one containing ARFaceGeometry objects, and the other three with transform coordinates as simd_float4x4 matrices. I am converting the arrays into Data objects using archivedData(withRootObject: requiringSecureCoding:) then calling write(to:) on them to create the files. The file containing the ARFaceGeometry data is written and read back in correctly. But the three simd_float4x4 arrays aren't being written, even though the code for doing so is identical. Along with my print logs, the error being given is 'unrecognized selector sent to instance'. Properties: var faceGeometryCapture = [ARFaceGeometry]() var faceTransformCapture = [simd_float4x4]() var leftEyeTransformCapture = [simd_float4x4]() var rightEyeTransformCapture = [simd_float4x4]() var faceGeometryCaptureFilePath: URL! var faceTransformCaptureFilePath: URL! var leftEyeTransformCaptureFilePath: URL! var rightEyeTransformCaptureFilePath: URL! Code for establishing file URLs: let fileManager = FileManager.default let dirPaths = fileManager.urls(for: .documentDirectory, in: .userDomainMask) faceGeometryCaptureFilePath = dirPaths[0].appendingPathComponent("face-geometries.txt") faceTransformCaptureFilePath = dirPaths[0].appendingPathComponent("face-transforms.txt") leftEyeTransformCaptureFilePath = dirPaths[0].appendingPathComponent("left-eye-transforms.txt") rightEyeTransformCaptureFilePath = dirPaths[0].appendingPathComponent("right-eye-transforms.txt") Code for writing the data to files: do { let data = try NSKeyedArchiver.archivedData(withRootObject: faceGeometryCapture, requiringSecureCoding: false) try data.write(to: faceGeometryCaptureFilePath) } catch { print("Error writing face geometries to file") } do { let data = try NSKeyedArchiver.archivedData(withRootObject: faceTransformCapture, requiringSecureCoding: false) try data.write(to: faceTransformCaptureFilePath) } catch { print("Error writing face transforms to file") } do { let data = try NSKeyedArchiver.archivedData(withRootObject: leftEyeTransformCapture, requiringSecureCoding: false) try data.write(to: leftEyeTransformCaptureFilePath) } catch { print("Error writing left eye transforms to file") } do { let data = try NSKeyedArchiver.archivedData(withRootObject: rightEyeTransformCapture, requiringSecureCoding: false) try data.write(to: rightEyeTransformCaptureFilePath) } catch { print("Error writing right eye transforms to file") } I'm guessing it's the simd_float4x4 struct that is causing the issue, as this is the only difference between working and not working. Can anyone confirm and suggest a solution? Thanks in advance. A: As already mentioned in comments structures can't conform to NSCoding but you can make simd_float4x4 conform to Codable and persist its data: extension simd_float4x4: Codable { public init(from decoder: Decoder) throws { var container = try decoder.unkeyedContainer() try self.init(container.decode([SIMD4<Float>].self)) } public func encode(to encoder: Encoder) throws { var container = encoder.unkeyedContainer() try container.encode([columns.0,columns.1, columns.2, columns.3]) } } Playground testing: do { let vector = simd_float4x4(2.7) // simd_float4x4([[2.7, 0.0, 0.0, 0.0], [0.0, 2.7, 0.0, 0.0], [0.0, 0.0, 2.7, 0.0], [0.0, 0.0, 0.0, 2.7]]) let data = try JSONEncoder().encode(vector) // 111 bytes let json = String(data: data, encoding: .utf8) print(json ?? "") // [[[2.7000000476837158,0,0,0],[0,2.7000000476837158,0,0],[0,0,2.7000000476837158,0],[0,0,0,2.7000000476837158]]]\n" let decoded = try JSONDecoder().decode(simd_float4x4.self, from: data) print(decoded) // "simd_float4x4([[2.7, 0.0, 0.0, 0.0], [0.0, 2.7, 0.0, 0.0], [0.0, 0.0, 2.7, 0.0], [0.0, 0.0, 0.0, 2.7]])\n" decoded == vector // true } catch { print(error) } edit/update: Another option is to save its raw bytes. It will use only 64 bytes: extension simd_float4x4: ContiguousBytes { public func withUnsafeBytes<R>(_ body: (UnsafeRawBufferPointer) throws -> R) rethrows -> R { try Swift.withUnsafeBytes(of: self) { try body($0) } } } extension ContiguousBytes { init<T: ContiguousBytes>(_ bytes: T) { self = bytes.withUnsafeBytes { $0.load(as: Self.self) } } var bytes: [UInt8] { withUnsafeBytes { .init($0) } } var data: Data { withUnsafeBytes { .init($0) } } func object<T>() -> T { withUnsafeBytes { $0.load(as: T.self) } } func objects<T>() -> [T] { withUnsafeBytes { .init($0.bindMemory(to: T.self)) } } var simdFloat4x4: simd_float4x4 { object() } var simdFloat4x4Collection: [simd_float4x4] { objects() } } extension Array { var bytes: [UInt8] { withUnsafeBytes { .init($0) } } var data: Data { withUnsafeBytes { .init($0) } } } let vector1 = simd_float4x4(.init(2, 1, 1, 1), .init(1, 2, 1, 1), .init(1, 1, 2, 1), .init(1, 1, 1, 2)) let vector2 = simd_float4x4(.init(3, 1, 1, 1), .init(1, 3, 1, 1), .init(1, 1, 3, 1), .init(1, 1, 1, 3)) let data = [vector1,vector2].data // 128 bytes let loaded = data.simdFloat4x4Collection print(loaded) // "[simd_float4x4([[2.0, 1.0, 1.0, 1.0], [1.0, 2.0, 1.0, 1.0], [1.0, 1.0, 2.0, 1.0], [1.0, 1.0, 1.0, 2.0]]), simd_float4x4([[3.0, 1.0, 1.0, 1.0], [1.0, 3.0, 1.0, 1.0], [1.0, 1.0, 3.0, 1.0], [1.0, 1.0, 1.0, 3.0]])]\n" loaded[0] == vector1 // true loaded[1] == vector2 // true
[ "stackoverflow", "0040303374.txt" ]
Q: FiddlerCore decoding an sdch response I'm getting an odd response from a site that I was looking to parse with FiddlerCore. In chrome developer tools if I inspect the response it looks completely normal, in fiddler it doesn't. Code snippet as follows(which used to work fine) String html = oSession.GetResponseBodyAsString(); Returns the following, which isn't html, note this is a sample rather than the full huge string. JRHwJNeR\0���\0\0\u0001��D\0�2�\b\0�\u0016�7]<!DOCTYPE html>\n win\"> It's also littered with "\n" and html like this \n\n\n\n\n \n <meta name=\"treeID\" content=\"dwedxE+pgRQAWIHiFSsAAA==\">\n Response headers are as follows: Cache-Control:no-cache, no-store Connection:keep-alive Content-Encoding:sdch, gzip Content-Language:en-US Content-Type:text/html;charset=UTF-8 Date:Fri, 28 Oct 2016 10:17:02 GMT Expires:Thu, 01 Jan 1970 00:00:00 GMT Pragma:no-cache Server:Apache-Coyote/1.1 Set-Cookie:lidc="b=VB87:g=518:u=60:i=1477649823:t=1477731496:s=AQG-LTdly5mcIjAtiRHIOrKE1TiRWW-l"; Expires=Sat, 29 Oct 2016 08:58:16 GMT; domain=.thedomain.com; Path=/ Set-Cookie:_lipt=deleteMe; Expires=Thu, 01-Jan-1970 00:00:10 GMT; Path=/ Strict-Transport-Security:max-age=0 Transfer-Encoding:chunked Vary:Accept-Encoding, Avail-Dictionary X-Content-Type-Options:nosniff X-Frame-Options:sameorigin X-FS-UUID:882b3366afaa811400a04937a92b0000 X-Li-Fabric:prod-lva1 X-Li-Pop:prod-tln1-scalable X-LI-UUID:iCszZq+qgRQAoEk3qSsAAA== X-XSS-Protection:1; mode=block Fiddler startup code: Fiddler.FiddlerApplication.AfterSessionComplete += FiddlerApplication_OnAfterSessionComplete; Fiddler.FiddlerApplication.BeforeResponse += delegate(Fiddler.Session oS) { oS.utilDecodeResponse(); }; Fiddler.FiddlerApplication.Startup(0, FiddlerCoreStartupFlags.Default); } Initially i'd assumed it was chunked/gzipped so I added utilDecodeResponse(); to onBeforeResponse which had no effect! Just to cover all the bases I'd also tried manually decoding responseBodyBytes in UTF-8, Unicode, Bigendian etc just on the off chance the response content type was incorrect AND disabled javascript and loaded the page to prove it wasn't some funky templating thingy, which also made no difference. Any ideas? UPDATE: In line with the information provided by Developer & NineBerry below the solution is as follows: In order to prevent the response being SDCH encoded you can add an handler like so: Fiddler.FiddlerApplication.BeforeRequest += delegate (Fiddler.Session oS) { oS.oRequest["Accept-Encoding"] = "gzip, deflate, br"; }; It should be noted that this isn't suitable for everything as you are manually setting the headers rather than checking to see if SDCH is present and then removing it, for my purposes this works fine, but for using the general proxy features of fiddler you'd want more logic here. A: The content encoding is shown as SDCH - Shared Dictionary Compression; so manually decoding responseBodyBytes in UTF-8, Unicode, Bigendian etc will not work in this case. You can find more details about SDCH here -SDCH Ref 1 & SDCH Ref 2 Excerpts from the above site: Shared Dictionary Compression is a content-encoding method which was proposed back in 2008 by Google, and is implemented in Chrome and supported by a number of Google servers. The full proposal can be obtained here -https://lists.w3.org/Archives/Public/ietf-http-wg/2008JulSep/att-0441/Shared_Dictionary_Compression_over_HTTP.pdf. Rather than replicate the contents of the document in this blog post, I’ll try and summarise as concisely as possible: The whole idea of the protocol is to reduce redundancy across HTTP connections. The amount of ‘common data’ across HTTP responses is obviously significant - for example you will often see a website use common header/footers across a number of HTML pages. If the client were to store this common data locally in a ‘dictionary’, the server would only need to instruct the client how to reconstruct the page using that dictionary.
[ "writers.stackexchange", "0000004525.txt" ]
Q: Where can I find exercises to help me develop fictional writing techniques useful in narrative nonfiction? I usually write explanatory nonfiction, but now I am interested in something more narrative--think Erik Larson or Rebecca Skloot, for example. I write clearly, and understand basic ideas about narrative elements like story arcs, scene setting, dialogue, etc. but there's a difference between understanding a concept and being able to apply it effectively to my writing. Where do you suggest I look to find the kinds of exercises or suggestions that help me move from conceptual understanding to skillful writing? A: I read a great book, Between the Lines: Master the subtle elements of fiction writing by Jessica Page Morrell. I wrote to her and we have corresponded. She also wrote Thanks, But This Isn't For Us: A (Sort Of) Compassionate Guide to Why Your Writing Is Being Rejected. Both books are a good fit for the writing transition you describe. The second has more exercises, both offer great information on the specifics you're looking for.
[ "stackoverflow", "0054160099.txt" ]
Q: Is SELECT * a good practice if I do not need any data? I see in many examples that contains "SELECT *" statement, even if clearly not all columns, or even any data is required/wanted. Ok, it is handy. Perhaps if someone creates an universal guide just tries to make thing simple? But what if I do want to get just one single record from one column? Does it matter if I do want the primary key, or not - is SELECT * good practice, or just lazy/practic thing that does not matter really? I'd give an example: In many questions/examples of "how to use "EXISTS" I see such an solution: (...) AND EXISTS (SELECT * FROM `table` WHERE ~~STATEMENT~~) Why should I use *, when I celarly do not need ANY data at all - all what I wanted was to check if an record that matches the STATEMENT does exist in table, nothing more. So why everywhere I see "SELECT *"? Literally, in all blogs, artcles, guides I see "SELECT *" and noone even mention about any other solution. My guess would be, that I should select the primary key just for the best preformance, like this: (...) AND EXISTS (SELECT `primary_key_column` FROM `table` WHERE ~~STATEMENT~~) Am I wrong? A: If you are writing application code, then select * is a poor practice. You want the application to be specific about the columns it is using. And you don't want to return unnecessary data to the application. If you are writing code that you expect to run over time -- say as a scheduled job -- then select * is also not recommended for similar reasons. MySQL tends to materialize subqueries (although it is getting better at avoiding this). So in MySQL, using select * in a subquery in the from clause (a "derived table") is not recommended for performance reasons. This is not true in other databases, which have smarter compilers. But for daily query writing, particularly in the outermost select, select * or select t.* is a great convenience. For EXISTS and NOT EXISTS, it makes no difference at all. I usually write: EXISTS (SELECT 1 FROM `table` WHERE ~~STATEMENT~~) EXISTS and NOT EXISTS are only looking for the existence of rows, not at the values in columns. So, what is selected should make no difference on performance. I use SELECT 1 because it is easy to type and I think pretty clearly conveys what it needs to.
[ "stackoverflow", "0013258049.txt" ]
Q: Why do e += 1 and e = e + 1 compile differently in CoffeeScript? I always assumed that <var> += 1 and <var> = <var> + 1 have the same semantics in JS. Now, this CoffeeScript code compiles to different JavaScript when applied to the global variable e: a: -> e = e + 1 b: -> e += 1 Note that b uses the global variable, whereas a defines a local variable: ({ a: function() { var e; return e = e + 1; }, b: function() { return e += 1; } }); Try it yourself. Is this a bug or is there a reason why this is so? A: I think I would call this a bug or at least an undocumented edge case or ambiguity. I don't see anything in the docs that explicitly specifies when a new local variable is created in CoffeeScript so it boils down to the usual We do X when the current implementation does X and that happens because the current implementation does it that way. sort of thing. The condition that seems to trigger the creation of a new variable is assignment: it looks like CoffeeScript decides to create a new variable when you try to give it a value. So this: a = -> e = e + 1 becomes var a; a = function() { var e; return e = e + 1; }; with a local e variable because you are explicitly assigning e a value. If you simply refer to e in an expression: b = -> e += 1 then CoffeeScript won't create a new variable because it doesn't recognize that there's an assignment to e in there. CS recognizes an expression but isn't smart enough to see e +=1 as equivalent to e = e + 1. Interestingly enough, CS does recognize a problem when you use an op= form that is part of CoffeeScript but not JavaScript; for example: c = -> e ||= 11 yields an error that: the variable "e" can't be assigned with ||= because it has not been defined I think making a similar complaint about e += 1 would be sensible and consistent. Or all a op= b expressions should expand to a = a op b and be treated equally. If we look at the CoffeeScript source, we can see what's going on. If you poke around a bit you'll find that all the op= constructs end up going through Assign#compileNode: compileNode: (o) -> if isValue = @variable instanceof Value return @compilePatternMatch o if @variable.isArray() or @variable.isObject() return @compileSplice o if @variable.isSplice() return @compileConditional o if @context in ['||=', '&&=', '?='] #... so there is special handling for the CoffeeScript-specific op= conditional constructs as expected. A quick review suggests that a op= b for non-conditional op (i.e. ops other than ||, &&, and ?) pass straight on through to the JavaScript. So what's going on with compileCondtional? Well, as expected, it checks that you're not using undeclared variables: compileConditional: (o) -> [left, right] = @variable.cacheReference o # Disallow conditional assignment of undefined variables. if not left.properties.length and left.base instanceof Literal and left.base.value != "this" and not o.scope.check left.base.value throw new Error "the variable \"#{left.base.value}\" can't be assigned with #{@context} because it has not been defined." #... There's the error message that we see from -> a ||= 11 and a comment noting that you're not allowed to a ||= b when a isn't defined somewhere. A: This can be pieced together from the documentation: =: Assignment in Lexical scope The CoffeeScript compiler takes care to make sure that all of your variables are properly declared within lexical scope — you never need to write var yourself. inner within the function, on the other hand, should not be able to change the value of the external variable of the same name, and therefore has a declaration of its own. The example given in this section is precisely the same as your case. += and ||= This is not a declaration, so the above does not apply. In its absence, += takes on its usual meaning, as does ||=. In fact, since these are not redefined by CoffeeScript, they take their meaning from ECMA-262 — the underlying target language — which yields the results you've observed. Unfortunately, this "fall-through" doesn't seem to be explicitly documented.
[ "stackoverflow", "0026949292.txt" ]
Q: Zend Framework Hosting - cannot include bootstrap.php I am using a hosting solution for my Zend Framework app, but cannot get it to load the application/bootstrap.php file. When I ftp on to the server, my doc root is /webspace/httpdocs/euro.millionsresults.com I placed the application, public, library etc. dirs in this directory. I then created a .htaccess, as per http://akrabat.com/zend-framework/zend-framework-on-a-shared-host/ /webspace/httpdocs/euro.millionsresults.com/.htaccess RewriteEngine On RewriteRule .* index.php This rewrites everything to my index.php file, which then includes the public/index.php file of the ZF, which is correct and works fine. The index.php file is: /webspace/httpdocs/euro.millionsresults.com/index.php <?php include 'public/index.php'; If I put in an echo in the public/index.php file, it works fine, proving public/index.php is now called when you try to access the site. The problem is, the public/index.php file needs to include the ../application/bootstrap.php file: /webspace/httpdocs/euro.millionsresults.com/public/index.php <?php echo "this is working"; require('../application/bootstrap.php'); However, application/bootstrap.php does not get included. If I put a die at the very top of application/bootstrap.php, nothing gets rendered. I have tried the following for public/index.php: require('../../../application/bootstrap.php'); require('/webspace/httpdocs/euro.millionsresults.com/application/bootstrap.php'); But nothing works in including application/bootstrap.php. Does anyone know what to do here? It is a cheap host I am on, with no access to php.ini. Additional Info: The issue seems to be with the include_path. When I do get_include_path(), I have: :/php/includes:/usr/share/pear:/usr/libexec/php4-cgi/share/pear:/opt/alt/php55/usr/share/pear:/opt/alt/php54/usr/share/pear:/opt/alt/php53/usr/share/pear I can set_include_path(), but what do I set it to? I have tried: set_include_path('/webspace/httpdocs/euro.millionsresults.com/application' . PATH_SEPARATOR. get_include_path()); set_include_path('/../../../application' . PATH_SEPARATOR . get_include_path()); set_include_path('../application' . PATH_SEPARATOR . get_include_path()); None of which work, i.e. when I have the following in my public/index.php file, I always get "does not exist": <?php echo "In file public/index.php <br>"; set_include_path('/../../../application' . PATH_SEPARATOR . get_include_path()); echo get_include_path(); if (file_exists('/../application/bootstrap.php')){ echo "<br>exists"; } else { echo "<br>does not exist"; } It doesn't matter what file I check existence of - any file in the application folder, or any folder not in public, is not found. A: In your public/index.php file, this line: require('../application/bootstrap.php'); assumes that your current working directory is public/ and that relative to this dir, one dir up, there is an application/bootstrap.php - relative require calls are relative to the current working directory or to the include_path. It seems that the ZF code assumes public/ is the document root, which is not true in your case. In Web environments, usually, the current working directory is the document root. So in your case, you may want to change require('../application/bootstrap.php') to: require('application/bootstrap.php'); If that does not work, I suggest finding out what the current working directory is vs. the public/index.php directory by running something like: var_dump(getcwd(), __DIR__); (if your PHP version is outdated, replace __DIR__ with dirname(__FILE__)) and, do your require call relative to that.
[ "stackoverflow", "0009018398.txt" ]
Q: Easy static link for a Flattr thing I would like to easily add a Flattr button to my RSS feed, without any JS As I understand that each thing on flattr is identified by its URL, I would like to simply add a link like this: http://flattr.com/thing-by-url/my-url.com/my-new-post If the thing does not exist, it should be created the first time someone Flattr it (just like my blog does with JS) From what I can read from the API, it is not currently possible and there's no way to add a static JS-less button in a RSS feed. What can I do ? Why isn't it possible to have a direct static link ? A: Why don't you use the http://developers.flattr.net/feed/? You can also add a static button with auto submit URL in feed body.
[ "unix.stackexchange", "0000110319.txt" ]
Q: Which Linux can I install from Windows? (but not Ubuntu) I have an old laptop, currently running Windows, but extremely slowly. I want to install Linux on it, probably a distro like Puppy, which plays well with low resources. But just about any distro will do as I will give the laptop to someone who only ever uses the browser (Chrome), no other apps. The problem is that while the laptop BIOS recognizes the internal CD, an external USB CD and a USB thumb drive and allows me to set them high in the boot order and also to select them from the one time boot menu, it will not actually boot from any of them. The only solution that I can see is to install Linux from Windows (and then, probably, remove Windows). I tried Wubi, which only installs Ubuntu, but that Ubuntu (12.04) would not recognize my Gigabit Ethernet card. I am drowning in other projects & just don't have time to sort that out, so am looking for another Linux which can be installed from Windows. I also found wubiX, a fork of Wubi, which says that it will allow to install any distro, but that has no download & the project was started in 2008. While I am aware that there are things that I could do (get the machine to boot from other than its hardrive, or sort out the Ubuntu networking (which I had expected to work out of the box), but I just don't have time, alas. I want to give this laptop to a friend who needs it and can't afford one otherwise. Does anyone know of a Linux distro, other than Ubuntu, which I can install from Windows? (Obviously, no virtual machines, as Windows has slowed to a crawl and a VM on top of that would not help) A: If you have a second machine where you can install your Distribution Of Choice (DOC) or have it installed in a VM, and if Ubuntu actually would run on that laptop you can do the following. Before playing around with the disc, consider taking it out of the laptop, hooking it up to another system and make a full dump of the disk (not of partitions), so in case of problems you can start over from scratch by restoring that dump As you already indicate you would consider removing Windows, first remove all unneeded installations from Windows and then install Ubuntu and have it shrink the Windows drive but not more than the DOC needs. From Ubuntu format the partition for your DOC as e.g. ext4. Tar the DOC on the other (VM) machine, transport it to Ubuntu and untar on the previous windows partition. Mount that partition and edit 'etc/fstab' on it to update the partitions your DOC uses (/dev/sdXY entries or UUIDs). Run update-grub. Ubuntu will recognize the new partition and make an entry in the grub menu. Now try and boot your COD, resolving any issues (did you edit fstab on the COD?). Once the COD boots without a problem, run its grub configuration and have it write the boot sector. Now you can boot without using Ubuntu and remove that partition after you successfully have done so. A: What you're looking for is xPUD; a distro with the tagline: "The shortest path to the cloud". It has a very fast boot time, its main component is an Internet browser, it has quite a small form factor and it can be installed from Windows. Note that you can't (easily) use it for much beyond web browsing, though.
[ "stackoverflow", "0009864286.txt" ]
Q: When tracking which elements were clicked e.target.id is sometimes empty I am trying to test the following JavaScript code, which is meant to keep track of the timing of user responses on a multiple choice survey: document.onclick = function(e) { var event = e || window.event; var target = e.target || e.srcElement; //time tracking var ClickTrackDate = new Date; var ClickData = ""; ClickData = target.id + "=" + ClickTrackDate.getUTCHours() + ":" + ClickTrackDate.getUTCMinutes() + ":" + ClickTrackDate.getUTCSeconds() +";"; document.getElementById("txtTest").value += ClickData; alert(target.id); // for testing } Usually target.id equals to the the id of the clicked element, as you would expect, but sometimes target.id is empty, seemingly at random, any ideas? A: Probably because the element that was clicked didn't have an ID. This will happen for example if you have HTML like this: <div id="example">This is some <b>example</b> text.</div> and someone clicks on the boldface word "example", so that the event target will be the b element instead of the div. You could try walking up the DOM tree until you find an element that does have an ID, something like this: var target = e.target || e.srcElement; while (target && !target.id) { target = target.parentNode; } // at this point target either has an ID or is null
[ "stackoverflow", "0017636362.txt" ]
Q: When I insert parent entity to repository it inserts duplicate of child entity Well, I have strange issue. I have Order, order has cart, cart has cart items collection, which consists of product and it's quantity: Order: public class Order : DatabaseEntity { public Order(Cart cart) { Cart = cart; } public int Id { get; set; } [Required] public Cart Cart { get; set; } ... } Cart: public class Cart : DatabaseEntity { public ICollection<CartItem> Items { get; set; } public void AddItem(Product product) { // Check is there such item, is Items null, update quantity // if there is already such item bla bla Items.Add(new CartItem(product)); } ... } Cart item: public class CartItem : DatabaseEntity { public CartItem(Product product) { Product = product; Quantity = 1; } public Product Product { get; set; } public int Quantity { get; private set; } } The problem is when I create new order and try to place it I get duplicate product record in database. Why is this happening, I've never faced this issue. What am missing? oO: [HttpPost] public ActionResult MakeOrder(MakeOrderViewModel makeOrderModel) { ... var cart = Session["cart"] as Cart; var order = new Order(cart); orderRepository.PlaceOrder(order); ... } Order repository: public void PlaceOrder(Order order) { _repository.InsertOrUpdate(order); } and repository itself: public class EFDatabaseRepository { ... public void InsertOrUpdate<TObject>(TObject entity) where TObject : DatabaseEntity { var entry = _database.Entry(entity); if(entry.State == EntityState.Detached) { // New entity _database.Set<TObject>().Add(entity); } else { // Existing entity _database.Entry(entity).State = EntityState.Modified; } Save(); } private void Save() { _database.SaveChanges(); } } DatabseEntity is just class with id field public class DatabaseEntity { public int Id { get; set; } } My database context class: public class DataBase : DbContext { public DbSet<Product> Products { get; set; } public DbSet<Order> Orders { get; set; } public DbSet<CartItem> CartItems { get; set; } public DbSet<Cart> Carts { get; set; } protected override void OnModelCreating(DbModelBuilder modelBuilder) { modelBuilder.Entity<CartItem>().HasRequired(ci => ci.Product); modelBuilder.Entity<Cart>().HasMany(c => c.Items); base.OnModelCreating(modelBuilder); } } A: Taken from this documentation: if the entity being added has references to other entities that are not yet tracked then these new entities will also be added to the context and will be inserted into the database the next time that SaveChanges is called. So you'll need to make sure that the context is tracking your existing entity in the Unchanged state before calling SaveChanges(). context.Entry(myExistingEntity).State = EntityState.Unchanged; Alternatively you could refactor your classes and work with foreign keys instead of at the conceptual level.
[ "unix.stackexchange", "0000032987.txt" ]
Q: Git-SVN Not Allowing Me to Authenticate Git 1.7.9.1 on Arch Linux: git svn init -s https://app.svn.beanstalk.com/repo Initialized empty Git repository in /path/to/repo/.git/ Authentication realm: <https://app.svn.beanstalk.com/repo:443> SVN Password for 'localuser': Authentication realm: <https://app.svn.beanstalk.com/repo:443> SVN Username: remoteuser Password for 'remoteuser': Authentication realm: <https://app.svn.beanstalk.com/repo:443> SVN Username: No matter how many times I enter my details, it never accepts them. I have logged in successfully with the same credentials in a web browser. I have also tried this without the -s, and with the --no-minimize-url flags. What's going on? A: @DavidAlpert's advice was correct. I fixed this by simply entering my domain credentials (username, then password) 3 or 4 times in a row. I don't know why, but it worked for me! I repeated this as an answer here since it is easy to miss in the comments.
[ "stackoverflow", "0042983677.txt" ]
Q: C# add method groups 1 by 1 to view list then execution list with contains method groups - only separated method no dynamically For better explanation here is a GUI screenshoot : SCREEN GUI ( can't add small image only link) And here is a all of my code with comments : using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.Media; // to play sounds namespace Music_PLayer { public partial class Form1 : Form { public Form1() { InitializeComponent(); //List View listView1.View = View.Details; listView1.FullRowSelect = true; // Columns CONSTRUCT listView1.Columns.Add("ID", 70); listView1.Columns.Add("Music name", 150); //combobox items comboBox1.Items.Add("Music 1"); comboBox1.Items.Add("Music 2"); comboBox1.Items.Add("Music 3"); comboBox1.Items.Add("Music 4"); comboBox1.Items.Add("Music 5"); } // ADD TO List VIEW private void add(int ID, string name_music) { string[] row = { Convert.ToString(ID), name_music }; ListViewItem item = new ListViewItem(row); listView1.Items.Add(item); } //button to delete selected items in list view private void button_delete_selected_music_Click(object sender, EventArgs e) { try { listView1.SelectedItems[0].Remove(); } catch { } } **//EDITED :** // buttton to add music to list view int i = 0; private void button_add_music_Click(object sender, EventArgs e) { if (comboBox1.SelectedIndex==0) { dictOfDelegate.Add("Music 1", playmusic1); add(i, comboBox1.Text); } if (comboBox1.SelectedIndex == 1) { dictOfDelegate.Add("Music 2", playmusic2); add(i, comboBox1.Text); } if (comboBox1.SelectedIndex == 2) { dictOfDelegate.Add("Music 3", playmusic3); add(i, comboBox1.Text); } if (comboBox1.SelectedIndex == 3) { dictOfDelegate.Add("Music 4", playmusic4); add(i, comboBox1.Text); } if (comboBox1.SelectedIndex == 4) { dictOfDelegate.Add("Music 5", playmusic5); add(i, comboBox1.Text); } } // button to start music private void button_start_music(object sender, EventArgs e) { } // Voids with music : public void playmusic1() { SoundPlayer audio = new SoundPlayer(Music_PLayer.Properties.Resources.playsound1); audio.Play(); } public void playmusic2() { SoundPlayer audio = new SoundPlayer(Music_PLayer.Properties.Resources.playsound2); audio.Play(); } public void playmusic3() { SoundPlayer audio = new SoundPlayer(Music_PLayer.Properties.Resources.playsound3); audio.Play(); } public void playmusic4() { SoundPlayer audio = new SoundPlayer(Music_PLayer.Properties.Resources.playsound4); audio.Play(); } public void playmusic5() { SoundPlayer audio = new SoundPlayer(Music_PLayer.Properties.Resources.playsound5); audio.Play(); } public delegate void PlayMusic(); // EDITED Dictionary<string, PlayMusic> dictOfDelegate = new Dictionary<string, PlayMusic>(); void CreateList() { dictOfDelegate.Add("Music 1", playmusic1); dictOfDelegate.Add("Music 2", playmusic2); dictOfDelegate.Add("Music 3", playmusic3); dictOfDelegate.Add("Music 4", playmusic4); dictOfDelegate.Add("Music 5", playmusic5); } void InvokeMethod(string item) { PlayMusic method = dictOfDelegate.First(x => x.Key == item).Value; method.Invoke(); } } } I want to to select a song from the combobox to add it to the playlist that will play from top to bottom after clicking on the "Start Music" button.. I would like to add a selected song from the combobox to the listview when you click the "Add Music to list" button. Of course, with the "Delete selected music" button I have the ability to delete a song from the list. So I have to do so for example when I select from the combobox (Music1) click on the button (Add Music to list), it will display ID 1 Music name Music 1 and when click on the Start Music button it will execute void playmusic1 (); I know I just only add text from combobox to listview but i don't know how can I get method there... I really don't know how to code Start Music button ( i thinking about queue) to play music one by one with my listView1. All I need is Collection or something or Queue. If I dont explain exacly just ask.. A: You really, really don't want to have a separate method to play each possible sound - that'll be a maintenance nightmare to say the least. One thing you could do is dynamically load things from resource files. The linked question has an example specifically for sound player. From the accepted answer, do the following to dynamically retrieve the resource: object o = Properties.Resources.ResourceManager.GetObject("whateverName"); You then cast it to a stream and play the audio. You don't necessarily have to use a resource file, though - if you know where the sounds are, you could easily just retrieve a list of file names in the folder(s) in the questions. Edit: If you really want separate methods, you could always use a Dictionary to map the sound name to the method to run. Something along the lines of this script I put together in LINQpad: void Main() { var db = new Dictionary<string, Action>(); db.Add("Music 1", PlaySound1); // Retrieve the method we're looking for and execute it db["Music 1"](); } private void PlaySound1() { // Play the sound } You could also do a switch statement: switch (soundName) { case "Music 1": // Play music 1 break; case "Music 2": // Play music 2 break; // ... }
[ "stackoverflow", "0001512219.txt" ]
Q: Are foreign key constraints needed? In a perfect world, are foreign key constraints ever really needed? A: Foreign keys enforce consistency in an RDBMS. That is, no child row can ever reference a non-existent parent. There's a school of thought that consistency rules should be enforced by application code, but this is both inefficient and error-prone. Even if your code is perfect and bug-free and never introduces a broken reference, how can you be certain that everyone else's code that accesses the same database is also perfect? When constraints are enforced within the RDBMS, you can rely on consistency. In other words, the database never allows a change to be committed that breaks references. When constraints are enforced by application code, you can never be quite sure that no errors have been introduced in the database. You find yourself running frequent SQL scripts to catch broken references and correct them. The extra code you have to write to do this far exceeds any performance cost of the RDBMS managing consistency. A: In addition to protecting the integrity of your data, FK constraints also help document the relationships between your tables within the database itself. A: The world is not perfect that's why they are needed.
[ "mathoverflow", "0000104840.txt" ]
Q: When is a $\ast$-algebra a $C^{\ast}$-algebra? The purpose of this question is to collect sufficient conditions on a unital $\ast$-subalgebra $\mathcal{A}$ of the algebra of bounded linear operators $B(\mathcal{H})$ on a separable Hilbert space $\mathcal{H}$ that guarantee that $\mathcal{A}$ is actually a $C^{*}$ algebra (is closed in the operator norm). Please provide links and references. At least, I'd like a reference or proof for the following: "Thm:" If $\mathcal{A}$ is a unital $\ast$-subalgebra of $B(\mathcal{H})$ and whenever $A\in\mathcal{A}$ is self-adjoint it follows that $A_{+}$ and $A_{-}$ both lie in $\mathcal{A}$, then $\mathcal{A}$ is norm-closed. (Here, $A_{+}$ and $A_{-}$ live naturally in the $C^{*}$-algebra generated by $A$ and $I$, isomorphic to $C(\sigma(A)))$, where $A$ corresponds to the function $f(x)=x$, $A_{+}$ corresponds to $max[f,0\]$ and $A_{-}$ to $min[f,0]$.) (Edit: Nik has pointed out that the "Thm" is false. The broader question stands: Is there any other interesting abstract characterization of a C*-algebra that doesn't obviously say the algebra is norm-closed?) A: Jon, I think your "Theorem" is false. For example, $A$ could be the algebra of complex-valued Lipschitz functions on $[0,1]$, acting as multiplication operators on $L^2[0,1]$. That's a unital *-subalgebra of $B(H)$ which is stable under lattice operations, but not closed in operator norm.
[ "stackoverflow", "0016145401.txt" ]
Q: Display Exception on try-catch clause Up to now, whenever I wanted to show an exception thrown from my code I used: try { // Code that may throw different exceptions } catch (Exception ex) { MessageBox.Show(ex.ToString()); } I used the above code mainly for debugging reasons, in order to see the exact type of exception and the according reason the exception was thrown. In a project I am creating now, I use several try-catch clauses and I would like to display a popup message in case of an exception, to make it more "user friendly". By "user friendly", I mean a message that would hide phrases like Null Reference Exception or Argument Out Of Range Exception that are currently displayed with the above code. However I still want to see relevant info with the type of exception that created the message. Is there a way to format the displayed output of thrown exceptions according to previous needs? A: You can use .Message, however I wouldn't recommend just catching Exception directly. Try catching multiple exceptions or explicitly state the exception and tailor the error message to the Exception type. try { // Operations } catch (ArgumentOutOfRangeException ex) { MessageBox.Show("The argument is out of range, please specify a valid argument"); } Catching Exception is rather generic and can be deemed bad practice, as it maybe hiding bugs in your application. You can also check the exception type and handle it accordingly by checking the Exception type: try { } catch (Exception e) { if (e is ArgumentOutOfRangeException) { MessageBox.Show("Argument is out of range"); } else if (e is FormatException) { MessageBox.Show("Format Exception"); } else { throw; } } Which would show a message box to the user if the Exception is an ArgumentOutOfRange or FormatException, otherwise it will rethrow the Exception (And keep the original stack trace). A: Exception.Message provides a more (but not entirely) user-friendly message than Exception.ToString(). Consider this contrived example: try { throw new InvalidOperationException(); } catch(InvalidOperationException ex) { Console.WriteLine(ex.ToString()); } Although Message yields a simpler message than ToString() the message displayed will still not mean much to the user. It won't take you much effort at all to manually swallow exceptions and display a custom message to the user that will assist them in remedying this issue. try { using (StreamReader reader = new StreamReader("fff")){} } catch(ArgumentException argumentEx) { Console.WriteLine("The path that you specified was invalid"); Debug.Print(argumentEx.Message); } catch (FileNotFoundException fileNotFoundEx) { Console.WriteLine("The program could not find the specified path"); Debug.Print(fileNotFoundEx.Message); } You can even use Debug.Print to output text to the immediate window or output window (depending on your VS preferences) for debugging purposes. A: try { /////Code that may throws several types of Exceptions } catch (Exception ex) { MessageBox.Show(ex.Message); } Use above code. Can also show custom error message as: try { /////Code that may throws several types of Exceptions } catch (Exception ex) { MessageBox.Show("Custom Error Text "+ex.Message); } Additional : For difference between ex.toString() and ex.Message follow: Exception.Message vs Exception.ToString() All The details with example: http://www.dotnetperls.com/exception
[ "stackoverflow", "0006826916.txt" ]
Q: Useful example with super and obscurity with extends in Generics? I know that there are a lot of questions about this topic, but unfortunately they couldn't help me to eliminate my obscurities. First of all, look at the following example. I don't understand, why the following "add"-method someCage.add(rat1) doesn't work and aborts with the following exception: Exception in thread "main" java.lang.Error: Unresolved compilation problem: The method add(capture#2-of ? extends Animal) in the type Cage is not applicable for the arguments (Rat) Is this the same reason why Cage<Rat> is not a Cage<Animal>? If yes, I don't understand it in this example, so I'm not sure what the compiler exactly does. Here is the code example: package exe; import cage.Cage; import animals.Animal; import animals.Ape; import animals.Lion; import animals.Rat; public class Main { public static void main(String[] args) { Lion lion1 = new Lion(true, 4, "Lion King", 8); Lion lion2 = new Lion(true, 4, "King of Animals", 9); Ape ape1 = new Ape(true, 2, "Gimpanse", true); Ape ape2 = new Ape(true, 2, "Orang Utan", true); Rat rat1 = new Rat(true, 4, "RatBoy", true); Rat rat2 = new Rat(true, 4, "RatGirl", true); Rat rat3 = new Rat(true, 4, "RatChild", true); Cage<Animal> animalCage = new Cage<Animal>(); animalCage.add(rat2); animalCage.add(lion2); Cage<Rat> ratCage = new Cage<Rat>(); ratCage.add(rat3); ratCage.add(rat1); ratCage.add(rat2); // ratCage.add(lion1); //Not Possible. A Lion is no rat Cage<Lion> lionCage = new Cage<Lion>(); lionCage.add(lion2); lionCage.add(lion1); Cage<? extends Animal> someCage = new Cage<Animal>(); //? = "unknown type that is a subtype of Animal, possibly Animal itself" someCage = ratCage; //OK // someCage = animalCage; //OK someCage.add(rat1); //Not Possible, but why? animalCage.showAnimals(); System.out.println("\nRatCage........"); ratCage.showAnimals(); System.out.println("\nLionCage........"); lionCage.showAnimals(); System.out.println("\nSomeCage........"); someCage.showAnimals(); } } This is the cage class: package cage; import java.util.HashSet; import java.util.Set; import animals.Animal; public class Cage<T extends Animal> { //A cage for some types of animals private Set<T> cage = new HashSet<T>(); public void add(T animal) { cage.add(animal); } public void showAnimals() { for (T animal : cage) { System.out.println(animal.getName()); } } } Moreover, I would be pleased if you could give me a meaningful "super" example with this animal-cage-code. Until now I haven't understood how to use it. There are a lot of theoretical examples and I read about the PECS concept but anyhow I wasn't able to employ it in a meaningful matter yet. What would it mean to have a "consumer" (with super) in this example? A: Example of super bound The introduced transferTo() method accepts Cage<? super T> - a Cage that holds a superclass of T. Because T is an instanceof its superclass, it's OK to put a T in a Cage<? super T>. public static class Cage<T extends Animal> { private Set<T> pen = new HashSet<T>(); public void add(T animal) { pen.add(animal); } /* It's OK to put subclasses into a cage of super class */ public void transferTo(Cage<? super T> cage) { cage.pen.addAll(this.pen); } public void showAnimals() { System.out.println(pen); } } Now let's see <? super T> in action: public static class Animal { public String toString() { return getClass().getSimpleName(); } } public static class Rat extends Animal {} public static class Lion extends Animal {} public static class Cage<T extends Animal> { /* above */ } public static void main(String[] args) { Cage<Animal> animals = new Cage<Animal>(); Cage<Lion> lions = new Cage<Lion>(); animals.add(new Rat()); // OK to put a Rat into a Cage<Animal> lions.add(new Lion()); lions.transferTo(animals); // invoke the super generic method animals.showAnimals(); } Output: [Rat, Lion] Another important concept is that while it is true that: Lion instanceof Animal // true it is not true that Cage<Lion> instanceof Cage<Animal> // false It this were not the case, this code would compile: Cage<Animal> animals; Cage<Lion> lions; animals = lions; // This assignment is not allowed animals.add(rat); // If this executed, we'd have a Rat in a Cage<Lion> A: You can add a Rat to a Cage<Rat> (of course). You can add a Rat to a Cage<Animal>, because a Rat "is" an Animal (extends Animal). You cannot add a Rat to a Cage<? extends Animal>, because <? extends Animal> might be <Lion>, which a Rat is not. In other words: Cage<? extends Animal> cageA = new Cage<Lion>(); //perfectly correct, but: cageA.add(new Rat()); // is not, the cage is not guaranteed to be an Animal or Rat cage. // It might as well be a lion cage (as it is). // This is the same example as in Kaj's answer, but the reason is not // that a concrete Cage<Lion> is assigned. This is something, the // compiler might not know at compile time. It is just that // <? extends Animal> cannot guarantee that it is a Cage<Rat> and // NOT a Cage<Lion> //You cannot: Cage<Animal> cageB = new Cage<Rat>(); //because a "rat cage" is not an "animal cage". //This is where java generics depart from reality. //But you can: Cage<Animal> cageC = new Cage<Animal>(); cageC.add(new Rat()); // Because a Rat is an animal. Imagine having your Cage<? extends Animal> created by an abstract factory method, which gets implemented by a subclass. In your abstract base class you cannot tell which type actually gets assigned, neither can the compiler, because maybe the concrete class gets only loaded at runtime. That means, the compiler cannot rely on Cage<? extends Animal> to not be a Cage of some other concrete subtype, which would make the assignment of a different subtype an error.
[ "stackoverflow", "0007368119.txt" ]
Q: What good homework style tutorials are recommended for learning functional programming in Python? I recommended to a friend to learn some functional programming using Python to expand his knowledge and overcome programmer's fatigue. I chose Python because that way there's a good chance he'll be able to use the new knowledge in practical daily work. I tried to find him some tutorials, and found a lot of guides - diving deep into how to use map, reduce, filter, etc., but don't provide exercises where he can learn while coding. Where can I find a tutorial that uses functional python to solve problems while teaching? An optimal answer for me would be homework from a functional programming course, that needs to be written in Python. Such a thing is probably rare because an academic course will usually prefer a purer functional language for such work. A: Maybe http://diveintopython.net/functional_programming/index.html helps. Some other useful links are: Functional Programming HOWTO Functional Programming with Python (by Pramode C.E.) Functional programming with Python (by CHRISTIAN HARMS)
[ "stackoverflow", "0051348238.txt" ]
Q: Laravel Class 'Тype' not found Using laravel, I have products page with few categories. When I create a new product and click save it is giving me an error: Class 'Тype' not found `protected function newRelatedInstance($class) { return tap(new $class, function ($instance) { if (! $instance->getConnectionName()) { $instance->setConnection($this->connection); } }); }` Despite the error the date is saved into the datebase and appear into the products list page. Product Model <?php namespace App\Models; use Illuminate\Database\Eloquent\Model; use Backpack\CRUD\CrudTrait; use Cviebrock\EloquentSluggable\Sluggable; use Cviebrock\EloquentSluggable\SluggableScopeHelpers; class Product extends Model { use CrudTrait; use Sluggable, SluggableScopeHelpers; /* |-------------------------------------------------------------------------- | GLOBAL VARIABLES |-------------------------------------------------------------------------- */ protected $table = 'products'; // protected $primaryKey = 'id'; // public $timestamps = false; // protected $guarded = ['id']; protected $fillable = ['name','description','slug', 'type_id', 'productcat_id', 'material_id', 'enviroment_id', 'manifacture_id']; // protected $hidden = []; // protected $dates = []; /** * Return the sluggable configuration array for this model. * * @return array */ public function sluggable() { return [ 'slug' => [ 'source' => 'slug_or_name', ], ]; } /* |-------------------------------------------------------------------------- | FUNCTIONS |-------------------------------------------------------------------------- */ /* |-------------------------------------------------------------------------- | RELATIONS |-------------------------------------------------------------------------- */ public function type(){ return $this->belongsTo('Тype'); } public function productcat(){ return $this->belongsTo('Productcat'); } public function material(){ return $this->belongsTo('Material'); } public function environment(){ return $this->belongsTo('Environment'); } public function manifacture(){ return $this->belongsTo('Manifacture'); } /* |-------------------------------------------------------------------------- | SCOPES |-------------------------------------------------------------------------- */ public function scopeFirstLevelItems($query) { return $query->where('depth', '1') ->orWhere('depth', null) ->orderBy('lft', 'ASC'); } /* |-------------------------------------------------------------------------- | ACCESORS |-------------------------------------------------------------------------- */ // The slug is created automatically from the "name" field if no slug exists. public function getSlugOrNameAttribute() { if ($this->slug != '') { return $this->slug; } return $this->name; } /* |-------------------------------------------------------------------------- | MUTATORS |-------------------------------------------------------------------------- */ } Product Controler <?php namespace App\Http\Controllers\Admin; use Backpack\CRUD\app\Http\Controllers\CrudController; // VALIDATION: change the requests to match your own file names if you need form validation use App\Http\Requests\ProductRequest as StoreRequest; use App\Http\Requests\ProductRequest as UpdateRequest; /** * Class ProductCrudController * @package App\Http\Controllers\Admin * @property-read CrudPanel $crud */ class ProductCrudController extends CrudController { public function setup() { /* |-------------------------------------------------------------------------- | BASIC CRUD INFORMATION |-------------------------------------------------------------------------- */ $this->crud->setModel('App\Models\Product'); $this->crud->setRoute(config('backpack.base.route_prefix') . '/product'); $this->crud->setEntityNameStrings('product', 'products'); /* |-------------------------------------------------------------------------- | BASIC CRUD INFORMATION |-------------------------------------------------------------------------- */ //$this->crud->setFromDb(); // ------ CRUD COLUMNS $this->crud->addColumn([ 'name' => 'name', 'label' => 'Name', ]); $this->crud->addColumn([ 'name' => 'slug', 'label' => 'Slug', ]); // ------ CRUD FIELDS $this->crud->addField([ // SELECT 'label' => 'Тип', 'type' => 'select', 'name' => 'type_id', 'entity' => 'type', 'attribute' => 'name', 'model' => "App\Models\Type", 'wrapperAttributes' => ['class' => 'col-md-4'], ]); $this->crud->addField([ // SELECT 'label' => 'Продукти', 'type' => 'select', 'name' => 'productcat_id', 'entity' => 'productcat', 'attribute' => 'name', 'model' => "App\Models\Productcat", 'wrapperAttributes' => ['class' => 'col-md-4'], ]); $this->crud->addField([ // SELECT 'label' => 'Материал', 'type' => 'select', 'name' => 'material_id', 'entity' => 'material', 'attribute' => 'name', 'model' => "App\Models\Material", 'wrapperAttributes' => ['class' => 'col-md-4'], ]); $this->crud->addField([ // SELECT 'label' => 'Среда', 'type' => 'select', 'name' => 'environment_id', 'entity' => 'envirnment', 'attribute' => 'name', 'model' => "App\Models\Environment", 'wrapperAttributes' => ['class' => 'col-md-4'], ]); $this->crud->addField([ // SELECT 'label' => 'Производител', 'type' => 'select', 'name' => 'manifacture_id', 'entity' => 'manifacture', 'attribute' => 'name', 'model' => "App\Models\Manifacture", 'wrapperAttributes' => ['class' => 'col-md-4'], ]); $this->crud->addField([ 'name' => 'name', 'label' => 'Заглавие (Име на продукта с кратко описание)', 'wrapperAttributes' => ['class' => 'col-md-6'], ]); $this->crud->addField([ 'name' => 'slug', 'label' => 'Slug (URL)', 'type' => 'text', 'hint' => 'Will be automatically generated from your name, if left empty.', 'wrapperAttributes' => ['class' => 'col-md-6'], ]); $this->crud->addField([ // WYSIWYG 'name' => 'description', 'label' => 'Описание', 'type' => 'textarea', ]); // add asterisk for fields that are required in ProductRequest $this->crud->setRequiredFields(StoreRequest::class, 'create'); $this->crud->setRequiredFields(UpdateRequest::class, 'edit'); } public function store(StoreRequest $request) { // your additional operations before save here $redirect_location = parent::storeCrud($request); // your additional operations after save here // use $this->data['entry'] or $this->crud->entry return $redirect_location; } public function update(UpdateRequest $request) { // your additional operations before save here $redirect_location = parent::updateCrud($request); // your additional operations after save here // use $this->data['entry'] or $this->crud->entry return $redirect_location; } } Type Model <?php namespace App\Models; use Illuminate\Database\Eloquent\Model; use Backpack\CRUD\CrudTrait; class Type extends Model { use CrudTrait; /* |-------------------------------------------------------------------------- | GLOBAL VARIABLES |-------------------------------------------------------------------------- */ protected $table = 'types'; // protected $primaryKey = 'id'; // public $timestamps = false; // protected $guarded = ['id']; protected $fillable = ['name']; // protected $hidden = []; // protected $dates = []; /* |-------------------------------------------------------------------------- | FUNCTIONS |-------------------------------------------------------------------------- */ /* |-------------------------------------------------------------------------- | RELATIONS |-------------------------------------------------------------------------- */ public function product() { return $this->hasMany('Product'); } Using backpack 3.4 Laravel 5.6 mysql.5.6 A: There is no class named Type. You are referring to a model name in those relationships. When referencing classes as strings, they are fully qualified names. Type is the fully qualified name for the class Type in the root namespace. There is no class in the root namespace named Type. I bet you have a App\Models\Type though. This is another reason to use the class constant and not string literals yourself, Class::class.
[ "stackoverflow", "0008639308.txt" ]
Q: is the sun.misc package still available in java? I would like to use the Base64 encoder of the package sun.misc.BASE64Encoder because I need to encode a password. However an error is being generated when I type in the import for this package. the message where the code for the encoder is to be used is the following: private synchronized static String hash(final String username, final String password) { DIGEST.reset(); return new BASE64Encoder().encode(DIGEST.digest((username.toLowerCase() + password).getBytes())); } Is there an equivalent class in java which does the same thing? Or maybe, does someone know how to be able to get the code of the original class maybe please? thanks :) A: I suggest you forget about the sun.misc.BASE64Encoder and use Apache Commons Base64 class. Here is the link: http://commons.apache.org/codec/apidocs/org/apache/commons/codec/binary/Base64.html Update (6/7/2017) Using sun.misc.BASE64Encoder will cause a compilation error with Java 9 and it is already giving a warning in Java 8. The right class to use is Base64 in java.util package. Example: import java.util.Base64; Base64.getDecoder().decode(...); A: There isn't a 'publicly available' (so to speak) class in Java for this. Consider using Apache Commons Codec package which contains an implementation of base64. Homepage is here: http://commons.apache.org/codec/. You use sun.* or com.sun.* packages directly at your own risk. Backwards compatibility is not guaranteed for those. A: See this question but IMHO the accepted answer is wrong. You never want to use the non-documented classes like anything starting with sun. The reason for this is that now your code depends on a particular JVM implementation (an IBM JVM might not have this for example). The 2nd answer (with the most votes) is the one you want.
[ "mathoverflow", "0000160239.txt" ]
Q: A question about the proof of Quillen's Theorem A (I posted this question on Mathstack but I haven't received any answers or comments so I thought I might as well try my luck here. I apologize if it is not an appropriate question.) Theorem (Quillen) Let $F:\mathcal{C} \rightarrow \mathcal{D}$ suppose that $ N(F\downarrow d)$ is weakly equivalent to $*$ for all $d \in \mathcal{D}$ then $NF: N\mathcal{C} \rightarrow N\mathcal{D}$ is a weak equivalence. The proof goes as follows: First we prove that if $F :\mathcal{C} \rightarrow \mathcal{D}$ is a functor, it is homotopy terminal if and only if $N(d \downarrow F)^{op}$ is weakly equivalent to a point for all $d \in \mathcal{D}$. If I can show/understand why $N(F\downarrow d)$ weakly equivalent to $ *$ implies that $N(d \downarrow F)^{op}$ is weakly equivalent to $*$ then the theorem follows easily ( by taking $X = Const_\mathcal{D} *$ in the definition of homotopy terminal ). So my question is: Why does $N(F\downarrow d)$ weakly equivalent to $ *$ for all $d \in \mathcal{D}$ imply that $N(d \downarrow F)^{op}$ is weakly equivalent to $*$ for all $d \in \mathcal{D}$? A: If $S \colon \mathcal A \to \mathcal B$ is a functor, let $\newcommand{\op}{\mathrm{op}}S^\op \colon \mathcal A^\op \to \mathcal B^\op$ be its opposite. Then $(S \downarrow T)^\op \cong T^\op \downarrow S^\op$. Combine this with the equality $NF = NF^\op$ (if you identify $N\mathcal C = N\mathcal C^\op$, etc.)
[ "stackoverflow", "0055696862.txt" ]
Q: How to install perl to /usr/local/bin I have a CD with a bunch of perl scripts, using /usr/local/bin/perl shebang. Yet on my machine perl is on /usr/bin . Can I just copy perl file or should have some more sophisticated install, like compiling from the source? Perl 5.22, Ubuntu 16.04 A: The simplest solution that is likely to work for most cases is just to create a symlink in /usr/local/bin pointing to ../../bin/perl. Another alternative is to use perl (or awk or sed) to change the first line of your files to point at the right place. A bit more work, but not really hard. If you need a private perl for some reason, and this isn't really very abnormal for perl shops, much like Java shops will have multiple JVMs floating around, or C# shops will have multiple levels of .NET / .NETCore floating around, then installing your own copy from source doesn't take a whole lot of work, though, even here, I'd suggest installing to somewhere else, and then creating the symlink you require so as to make it easier to upgrade and downgrade as required.
[ "stackoverflow", "0035826568.txt" ]
Q: Using JTree take each sub classes and sibling classes name in Java I created JavaTree. Now I want to take all sub classes and sibling classes name of each class. I could take super class using selectedNode.getParent().toString(). But following code for sub class gave result like java.util.Vector$1@3ae19358 and for sibling class, I couldn't found a way. Is there any way to take each sub and sibling classes names? import java.awt.BorderLayout; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JScrollPane; import javax.swing.JTree; import javax.swing.SwingUtilities; import javax.swing.event.TreeSelectionEvent; import javax.swing.event.TreeSelectionListener; import javax.swing.tree.DefaultMutableTreeNode; public class TreeExample extends JFrame { /****************** Developing a Simple JTree************************/ private JTree tree; private JLabel selectedLabel; //for Event Handlers public TreeExample() { //create the root node DefaultMutableTreeNode root = new DefaultMutableTreeNode("AA"); //create the child nodes DefaultMutableTreeNode bb = new DefaultMutableTreeNode("BB"); DefaultMutableTreeNode cc = new DefaultMutableTreeNode("CC"); //add the child nodes to the root node root.add(bb); root.add(cc); //create the tree by passing in the root node tree = new JTree(root); add(tree); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); this.setTitle("JTree Example"); this.pack(); this.setVisible(true); /****************** Adding More Children************************/ videoInfoNode.add(new DefaultMutableTreeNode("DD")); foodInfoNode.add(new DefaultMutableTreeNode("EE")); foodInfoNode.add(new DefaultMutableTreeNode("FF")); foodInfoNode.add(new DefaultMutableTreeNode("GG")); //To get the selected node information tree.getSelectionModel().addTreeSelectionListener(new TreeSelectionListener() { @Override public void valueChanged(TreeSelectionEvent e) { DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode) tree.getLastSelectedPathComponent(); //sub class if(selectedNode.getAllowsChildren()){----?????????? selectedLabel.setText(selectedNode.children().toString());}-----????????? else{ System.out.println("no children"); } //sibling class System.out.println(selectedNode.getSibling().....);--------???????? } }); } //end //main public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { new TreeExample(); } }); } } A: I could take super class using selectedNode.getParent().toString(). I guess you are meaning TreeNode. if(selectedNode.getAllowsChildren()){----?????????? Maybe you need to use TreeNode#isLeaf() instead of DefaultMutableTreeNode#getAllowsChildren(): import java.awt.BorderLayout; import java.util.Enumeration; import javax.swing.*; import javax.swing.event.TreeSelectionEvent; import javax.swing.event.TreeSelectionListener; import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.tree.TreeNode; public class TreeExample2 extends JFrame { /****************** Developing a Simple JTree************************/ private JTree tree; //private JLabel selectedLabel; //for Event Handlers public TreeExample2() { //create the root node DefaultMutableTreeNode root = new DefaultMutableTreeNode("AA"); //create the child nodes DefaultMutableTreeNode bb = new DefaultMutableTreeNode("BB"); DefaultMutableTreeNode cc = new DefaultMutableTreeNode("CC"); //add the child nodes to the root node root.add(bb); root.add(cc); //create the tree by passing in the root node tree = new JTree(root); add(tree); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); this.setTitle("JTree Example"); this.pack(); this.setVisible(true); /****************** Adding More Children************************/ bb.add(new DefaultMutableTreeNode("DD")); cc.add(new DefaultMutableTreeNode("EE")); cc.add(new DefaultMutableTreeNode("FF")); cc.add(new DefaultMutableTreeNode("GG")); //To get the selected node information tree.getSelectionModel().addTreeSelectionListener(new TreeSelectionListener() { @Override public void valueChanged(TreeSelectionEvent e) { Object o = tree.getLastSelectedPathComponent(); if (o instanceof DefaultMutableTreeNode) { //TreeNode selectedNode = (TreeNode) o; DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode) o; System.out.println("----"); //children if (!selectedNode.isLeaf() && selectedNode.getChildCount() > 0) { Enumeration enumeration = selectedNode.children(); while (enumeration.hasMoreElements()) { TreeNode node = (TreeNode) enumeration.nextElement(); System.out.println("child: " + node); } } else { System.out.println("no children"); } //sibling TreeNode parentNode = selectedNode.getParent(); if (parentNode != null) { for (int i = 0; i < parentNode.getChildCount(); i++) { TreeNode node = parentNode.getChildAt(i); if (!selectedNode.equals(node)) { System.out.println("sibling: " + node); } } } } } }); } public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { new TreeExample2(); } }); } }
[ "stackoverflow", "0016627204.txt" ]
Q: Database structure for storing a statement and 4 options with inline images I have a statement which can have multiple inline block images (like say mathematical formulaes) and has 4 associated choices (like in a quiz) and each one of them can have any number of inline images as well. I know in a naive manner I can store HTML for each of them Q_ID|Ques|Number Of Choices| Choice A | Choice B | Choice C | Choice D or we can have a Question Table Q_ID|Ques| Q_contains_image| Number Of Choices| Choice A | Choice ID| Choice_contains_image| Choice B | ....Choice C... | Choice D ... and an image table Img_Id|Q_ID/CHoice_ID|Image_path I still don't know if they are the best way and how will the second way affect the performance if we need to render the question with the choices in HTML. I don't like the first way because that would require hardcoding the path within the HTML and HTML is never nice to read when you see them as a result of an sql query. I want to know some good method to store them along with what would be implied costs of using a good method. A: Let's normalize the data. By normalizing the data, we eliminate redundancy in the data and reduce the storage needed to the minimum. You do need to join tables to get at all of the information. Joining tables is what relational databases were designed to do, so they join tables quickly. Question -------- Question ID Question Text Answer ------ Answer ID Question ID Answer Text Correct Answer -------------- Correct Answer ID Question ID Answer ID Question Image -------------- Question Image ID Question ID Question Image Answer Image ------------ Answer Image ID Answer ID Answer Image In each of the above tables, the first ID field is the primary (clustering) key. The primary key is an auto-incrementing integer or long. Any ID fields after the first field are foreign keys pointing back to the table with the primary key. In the Correct Answer table, you have an additional unique index on (Question ID, Answer ID). You don't store HTML in any of the database columns. You store text or images. Edited to answer the questions in the comments. Should I have a flag for the image in the question/image table or you suggest that I deduce it on the basis of getting a match or no match from the image table. You deduce it on the basis of getting a row or no row from the image table. What do you mean by correct answer id. Suppose I have a question with choices a,b,c,d and a,b are correct. How do you propose I feed that data here? If you have more than one correct answer for a question, you have more than one row in the Correct Answer table. The Question ID would be the same for both rows in your example, white the Answer IDs would point to the two correct answers.
[ "stackoverflow", "0016167322.txt" ]
Q: sql query for the below pattern I have a table : Name When I do a : SELECT * FROM Name, it give the results as : Name ====== aaa bbb ccc sss I want the result to be like in one row only : Name ==== aaa bbb ccc sss How can I get this? A: Try this one - DECLARE @temp TABLE ( col NVARCHAR(50) ) INSERT INTO @temp (col) VALUES ('aaa'), ('bbb'), ('ccc'), ('sss') SELECT str_string = ( SELECT col + ' ' FROM @temp FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)') Or try this - DECLARE @string NVARCHAR(MAX) = '' SELECT @string = @string + col + ' ' FROM @temp SELECT @string
[ "sharepoint.stackexchange", "0000059371.txt" ]
Q: Can't Change URL I am very much a noob at sharepoint, so this is probably an easy one. I am trying to get SharePoint 2013 up and running. When I go through the config wizard, it creates a site for me with a URL that starts with http://servername. This is NOT what I want. I want the URL to being http://FQDN since that is how people will actually be accessing it, and I want it on port 80. SharePoint is fighting me tooth and nail on this. I have no data to preserve. This is a vm with a snapshot pre SP install, so I can easily blow away everything I have and start again. And I have. A couple of times. What I am looking for the easiest way to get what I want. I would welcome any and all input. A: Go into Central Administration and look for Alternate Access Mappings, probably under Server Settings. From there, select your web application in the selector. Edit the public URLs and enter your desired URL as the default zone. Note: if you have tried to change the URL directly in IIS, then you may have to make the change there as well. I haven't done this in SP2013 but it should be the same as past versions, though the AAM link might be in a different location.
[ "stackoverflow", "0028946182.txt" ]
Q: External Library and Android Manifest Does External Android Library have their Android Manifest merged with the main app? Thanks A: Actually it depends on the API you are using. Suppose you are using external API that doesn't require any hardware or network permission from OS than you don't need to add anything new in the manifest file. And if you are using external API that requires such permissions, then you must have to add them in your manifest file.
[ "stackoverflow", "0041050306.txt" ]
Q: Accessing Table properties like rows,childNodes using Selenium Web Driver I am trying to access the properties of(Properties are the ones which you can see in the Chrome browser developer tools when you highlight the table control on the browser) table object using the selenium web driver. My requirement here is to access the table properties like rows and childNodes . I am using the below code to get the properties of the table. var propVlu = tblObj.GetAttribute("baseURI"); Console.WriteLine(propVlu.ToString()); The output of the code here is exactly what I want : Test Name: TblIterateDemo Test Outcome: Passed Result StandardOutput: http://testbpp.corum.com.au/main/(S(2zpcwh5e2xp4wfkbkhvxranb))/Customer.aspx But if I try to access a property which has some tree structure like the below : var propVlu = tblObj.GetAttribute(@"rows[""0""].baseURI"); if(propVlu != null) { Console.WriteLine(propVlu.ToString()); } else { Console.WriteLine("Property not found"); } I am getting an the following output Property not found Can some one please help me accessing these kind of properties belonging to a web control control on the browser. Please find the attachment containing the image.The property rows exists and also is not null when I check that on Chrome browser developer tools properties tab. Image of my Question Description cheers, Bharat. A: I finally found the way to solve it,I have done the following to access the rows property of a table object : var contents = ((IJavaScriptExecutor)drivr).ExecuteScript("return arguments[0].rows.length; ", tblObj); Console.WriteLine(contents.ToString()); I got some help from this place http://grokbase.com/t/gg/selenium-users/128dp25q60/how-to-get-all-html-attributes-for-a-tag
[ "stackoverflow", "0026334725.txt" ]
Q: How can I use Android TextToSpeak in a MVVMCross plugin? I have seen plenty of examples of how to use Android TextToSpeak in an Activity, and have also managed to get this to work just fine. I've also managed to get it to work using a bound service in a plugin, but it seems overcomplicated for my purposes. Here is my VoiceService class: public class VoiceService : IVoiceService, TextToSpeech.IOnInitListener { public event EventHandler FinishedSpeakingEventHandler; private TextToSpeech _tts; public void Init() { // Use a speech progress listener so we get notified when the service finishes speaking the prompt var progressListener = new SpeechProgressListener(); progressListener.FinishedSpeakingEventHandler += OnUtteranceCompleted; //_tts = new TextToSpeech(Application.Context, this); _tts = new TextToSpeech(Mvx.Resolve<IMvxAndroidCurrentTopActivity>().Activity, this); _tts.SetOnUtteranceProgressListener(progressListener); } public void OnInit(OperationResult status) { // THIS EVENT NEVER FIRES! Console.WriteLine("VoiceService TextToSpeech Initialised. Status: " + status); if (status == OperationResult.Success) { } } public void Speak(string prompt) { if (!string.IsNullOrEmpty(prompt)) { var map = new Dictionary<string, string> { { TextToSpeech.Engine.KeyParamUtteranceId, new Guid().ToString() } }; _tts.Speak(prompt, QueueMode.Flush, map); Console.WriteLine("tts_Speak: " + prompt); } else { Console.WriteLine("tts_Speak: PROMPT IS NULL OR EMPTY!"); } } /// <summary> /// When we finish speaking, call the event handler /// </summary> public void OnUtteranceCompleted(object sender, EventArgs e) { if (FinishedSpeakingEventHandler != null) { FinishedSpeakingEventHandler(this, new EventArgs()); } } public void Dispose() { //throw new NotImplementedException(); } public IntPtr Handle { get; private set; } } Note that the OnInit method never gets called. In my viewmodel I'd like to do this: _voiceService.Init(); _voiceService.FinishedSpeakingEventHandler += _voiceService_FinishedSpeakingEventHandler; ... and then later ... _voiceService.Speak(prompt); When I do this I get these messages in the output: 10-13 08:13:59.734 I/TextToSpeech( 2298): Sucessfully bound to com.google.android.tts (happens when I create the new TTS object) and 10-13 08:14:43.924 W/TextToSpeech( 2298): speak failed: not bound to TTS engine (when I call tts.Speak(prompt)) If I was using an activity I would create an intent to get this to work, but I'm unsure how to do that in a plugin. Thanks in advance, David A: Don't implement Handle yourself, instead derive from Java.Lang.Object public class VoiceService : Java.Lang.Object, IVoiceService, TextToSpeech.IOnInitListener and remove your Dispose() and Handle implementation More info here: http://developer.xamarin.com/guides/android/advanced_topics/java_integration_overview/android_callable_wrappers/ Also, I suggest you take an async approach when implementing your service, which would make calling it from view-model something like await MvxResolve<ITextToSpeechService>().SpeakAsync(text);
[ "stackoverflow", "0006215817.txt" ]
Q: Extracting 'single item' from Multi Dimensional Array (c#) Say I have the code var marray = new int[,]{{0,1},{2,3},{4,5}}; Is it possible to get a reference to the first item - i.e. something that looked like: var _marray = marray[0]; //would look like: var _marray = new int[,]{{0,1}}; Instead, when referencing marray from a one dimensional context, it sees marray as having length of 6 (i.e. new int[]{0,1,2,3,4,5}) A: Use a jagged array var marray = new[] { new[] { 0, 1 }, new[] { 2, 3 }, new[] { 4, 5 } }; Console.WriteLine(marray[0][1]);
[ "stackoverflow", "0006324605.txt" ]
Q: how to debug javascript on chrome I have this weird issue that jquery.load sometimes fails on chrome. I'm not gonna bother you guys with the details, I'm just looking for a pointing hand on how can i debug such an issue? I thought of maybe the firebug could help, but the issue happens only on chrome (even works on IE). I do something like: $("#contentid").html("Plz wait."); $("#contentid").load(url); $("#contentid").show(); I get only the "Plz wait" on #contentid, and i can see the url getting called, and check it manually and see it succeeds. UPDATE2: so i changed the load calls according to suggestions $('#conentid').load(url, function(response, status, xhr){ alert('Load was performed. url:' + url); if (status == "error") { alert("text: " + xhr.statusText); alert("readyState: "+xhr.readyState+"\nstatus: " + xhr.status); alert("responseText: "+xhr.responseText); } else { $("#conentid").show(); } }); I get status=='error' when the errors occur. xhr.statusText: 0 xhr.readyState: 4 xhr.statusText and xhr.responseText are empty any idea why? what does this mean? The url works manually. and this error happens only on chrome, and only sometimes A: Chrome actually has rather nice developer tools. Click the wrench icon, select developer tools from the menu. On this particular issue, I'll bet the show is being called before the load completes -- load happens asynchronously. Set up an event handler for "on load" on #contentid and do the show in that. Update Actually, there's a better way to do it; put your show into a callback on the load function: $('#conentid').load('ajax/test.html', function() { alert('Load was performed.'); $('#contentid').show(); }); Another Update Okay, the ready state of 4 indicates the XmlHTTPRequest completed normally. Now, there's one ambiguity here: is the xhr.statusText 0 or is it empty? What results do you see from this code (including the error code) on another browser? If it's working on firefox, and only working sometimes on Chrome, you may have an actual Chrome bug. A: Maybe someone else could have an explanation for this answer, but the problem was: I had a base href TAG (<base href="http://domain.com/" />) There are some references for problems with using jquery + base href out there. I have no idea why, but removing this line fixed everything. thanks for all your help, I learned some web debugging\ajax tips in the process.
[ "pt.stackoverflow", "0000041690.txt" ]
Q: Usar selectpicker no jQuery Eu tenho esse código de selectpicker(bootstrap) <select name="nivel_p" class="selectpicker"> <option>menor que 6</option> <option>7-15</option> <option>16-40</option> <option>maior que 40</option> </select> Eu preciso disparar um comando toda vez que a seleção do select for alterada,mas eu não faço a minima idéia de como faz pensei em algo como: $('select[name=nivel_p]').selectpicker(function() { } Mas não funcionou,qual a maneira correta de fazer isso? A: Para "disparar um comando toda vez que a seleção do select for alterada" pode fazer usar o evento change e o código seria assim: $('select[name=nivel_p]').on('change', function(){ // correr código aqui }); Exemplo: $('select[name=nivel_p]').on('change', function(){ alert('A opção selecionada mudou!\nO novo valor é: ' + $(this).val()); }); <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <select name="nivel_p" class="selectpicker"> <option>menor que 6</option> <option>7-15</option> <option>16-40</option> <option>maior que 40</option> </select>
[ "ru.stackoverflow", "0000035223.txt" ]
Q: Возможно ли узнать содержимое php-файла на удаленном сервере? Возможно ли узнать содержимое php-файла на удаленном сервере? A: Возможно, если на этом сервере у вас есть доступ к ФТП/SSH или стоит скриптик, исполняющий консольные команды. При правильном взаимодействии узнать код нельзя: при попытке вызвать файл, он тупо исполнится. Исключение - квайн.
[ "stackoverflow", "0001742538.txt" ]
Q: I want to import data from my stored procedure to a csv file I am using SQL Server 2005. I want to create a stored procedure that will save data into a .csv file. Below is the query I am trying but it is not creating any file in my system: use PBMS_DocumationWorkflow go create proc s_bcpMasterSysobjects as select '"' + name + '"' + ',' + '"' + convert(varchar(8), crdate, 112) + '"' + ',' + '"' + convert(varchar(8), crdate, 108) + '"' from master..sysobjects order by crdate desc go declare @sql varchar(8000) select @sql = 'bcp "exec PBMS_DocumationWorkflow..s_bcpMasterSysobjects" out c:\bcp\sysobjects.txt -c -t, -T -S'+ @@servername exec master..xp_cmdshell @sql Please suggest the cause or give me sample code which works fine. Thanks. A: Try changing the "out" to "queryout"
[ "stackoverflow", "0044432191.txt" ]
Q: How to compress IPV6 address using javascript? I have seen the code to compress IPV6 in java. The link specifies the same. Below is the code in Java . String resultString = subjectString.replaceAll("((?::0\\b){2,}):?(?!\\S*\\b\\1:0\\b)(\\S*)", "::$2"); But in Javascript I am confused as how can I get the regex expression to match the same . Can you share some pointers here? Example : fe80:00:00:00:8e3:a11a:2a49:1148 Result : fe80::8e3:a11a:2a49:1148 A: You can do it by replacing \b(?:0+:){2,} with : function compIPV6(input) { return input.replace(/\b(?:0+:){2,}/, ':'); } document.write(compIPV6('2001:db8:0:0:0:0:2:1') + '<br/>'); document.write(compIPV6('fe80:00:00:00:8e3:a11a:2a49:1148' + '<br/>')); Check it out at regex101.
[ "ell.stackexchange", "0000155376.txt" ]
Q: The usage of "Off" I saw a sentence that made me wonder what the usage of "Off" is. This is the sentence: I love that she can make a living off playing video games So what i understand is that "off" shows an activity but are there any other cases that we can use "off" in? For example can i say: I like that she can make a living off being a photographer. A: "Off" means approximately "out of", or "from" / "away from". For example, He needs to stop leeching money off his parents. (He needs to stop always asking his parents for money, getting money from his parents.) Sometimes "of" is added. He makes a living off of suing people. (used, for example, here) But this is more colloquial and more typical for AmE. Basing myself off of my previous experience, I expected this meeting to last at least two hours. (taking my previous experience as a starting point, I'm taking from it that my next experience will turn out to be X) [real-life example of usage here] "The Good Fight" (TV show) is a spin-off of "The Good Wife". "Spin-off" is a noun, but here the meaning of "off" is also present: We have taken a previous show, and from it, we made a sequel.
[ "stackoverflow", "0011679124.txt" ]
Q: Searching for #ifdef in a header file std::string systemStr = "C:\\gcc1\\gccxml.exe "; systemStr += "\"" ; systemStr += argv[1] ; std::cout<<"Header File is:"<<argv[1]<<endl; In the above code snippet, argv[1] represents the name of the header file. I want to open this header file and search for #ifdefs that may be present. How do I go about doing this? The problem is that argv[1] is a string. I'm sorry if I'm unclear. A: How about something like this... std::cout<<"Header File is:"<<argv[1]<<endl; std::ifstream file(argv[1]); int lineNum = 0; bool hasIfdef = false; while( file.good() ) { std::string line; std::getline( file, line ); lineNum++; if( line.find("#ifdef") != std::string::npos || line.find("#ifndef") != std::string::npos ) { std::cout << "Line " << lineNum << ": " << line << std::endl; hasIfdef = true; } }
[ "stackoverflow", "0013862056.txt" ]
Q: I get a PHP unexpected T_DOUBLE_ARROW It's a part of PHP automatic generated feed i only know bits and peaces of PHP so please stay calm with me but I'm getting: Parse error: syntax error, unexpected T_DOUBLE_ARROW in /home/u664558657/public_html/feed/example_rss2.php on line 68 switch($monitor->$newItem=>addElementArray(array('title'=>getStatus()) { case STATUS_ONLINE : p('<h2 class="online">Online</h2>'); break; case STATUS_OFFLINE : p('<h2 class="offline">Offline</h2>'); break; case STATUS_PAUSED : p('<h2 class="waiting">Paused</h2>'); break; case STATUS_DOWNTIME : p('<h2 class="waiting">Scheduled Downtime</h2>'); break; case STATUS_UNPOLLED : p('<h2 class="waiting">Unpolled</h2>'); break; }', 'link'=>'http://feed.vipo.ca/', 'description'=>'test description')); $TestFeed->addItem($newItem); A: switch($monitor->$newItem=>addElementArray(array('title'=>getStatus()) Should be: switch($monitor->$newItem->addElementArray(array('title'=>getStatus()) Have a look at => and change it to -> A: T_DOUBLE_ARROW is the token for =>. So the error is for $newItem=>addElementArray. It should be $newItem->addElementArray also there should be two more parenthesises after array('title'=>getStatus()). Like array('title'=>getStatus()))) Even After that this part makes no sense ', 'link'=>'http://feed.vipo.ca/', 'description'=>'test description'));
[ "stackoverflow", "0061189133.txt" ]
Q: How can I concatenate multiple values for a single identifier in SQL? My Code: SELECT o.ORDER_ID ,o.ORDER_DESCRIPTION ,o.ORDER_DATE ,o.ORDER_ITEM_ID , i.CONCATENATED_ITEM_DESC FROM ORDERS o INNER JOIN ( SELECT i.ITEM_ID, CASE WHEN COUNT(i.ITEM_ID > 1) THEN 'CONCATENATE THE DESCRIPTIONS' END AS CONCATENATED_ITEM_DESC FROM ITEMS i )i ON o.ORDER_ITEM_ID = i.ITEM_ID ; I'm trying to get the description from another table concatenated. A: The standard function is listagg(): SELECT o.*, i.CONCATENATED_ITEM_DESC FROM ORDERS o INNER JOIN (SELECT i.ITEM_ID, LISTAGG(ITEM_DESC, ', ') WITHIN GROUP )ORDER BY ITEM_DESC) AS CONCATENATED_ITEM_DESC FROM ITEMS i GROUP BY i.ITEM_ID ) ON o.ORDER_ITEM_ID = i.ITEM_ID; However, many databases have other names for the function, including string_agg() and group_concat().
[ "stackoverflow", "0026804955.txt" ]
Q: Laravel PHP: Eloquent Repository does not recognize model I'm having a problem with an Eloquent Repository that I've created where it's not recognizing the model for the data I'm trying to collect from my form. I even copied my model into the Eloquent Repository's namespace but it's still not being recognized. Eloquent Repository (app\Acme\repositories\Eloquent\EloquentVideoRepository.php): <?php namespace Acme\repositories\Eloquent; use acme\repositories\VideoRepository; /* Tried copying the 'Video' model into the same namespace as this Eloquent Repository but it is not being recognized. */ use acme\repositories\Video; class EloquentVideoRepository implements VideoRepository { public function all() { return Video::all(); } /* This function below generates an error since the 'Video' class is not found from my 'Video' Model */ public function create($input) { return Video::create($input); } } Model(app\models\Video.php): <?php /* Original Line of code below that generated the error: class Video extends Eloquent */ /* EDIT: I put a backslash in front of Eloquent and now the model is recognized. */ class Video extends \Eloquent { /** * The table used by this model * * @var string **/ protected $table = 'videos'; /** * The primary key * * @var string **/ protected $primaryKey = 'video_id'; /** * The fields that are guarded cannot be mass assigned * * @var array **/ protected $guarded = array(); /** * Enabling soft deleting * * @var boolean **/ protected $softDelete = true; } I've also copied the Model above to 'app\acme\repositories'. Error Message that is displayed: 'Class acme\repositories\Video not found' I've tried perform php artisan dump-autoload even after copying the model into this namespace but it's still not working. Any help is appreciated. A: The Video class file is missing any namespace declaration and therefore is in the default namespace. Extending something does not change it's namespace. Add this line on top to add it itno your desired namespace: namespace Acme\repositories\Eloquent; Or add a use line as below to your other file, but I doubt that is what you want: use \Video;
[ "unix.stackexchange", "0000487831.txt" ]
Q: Grep Showing Extra Lines So I have a text file: 4556 4618 7843 8732 4532 0861 1932 5122 3478 893* 6788 6312 5440 3173 8207 0451 67886 6011 2966 7184 4668 3678 3905 5323 2389 4387 9336 2783 239 235 453 3458 182 534 654 765 4485 0721 1308 2759 46759 543 2345 I want to grep only the numbers that have 4 digits together, 4 times in a row (seperated by a space). For example: 4556 4618 7843 8732 I am using: grep -E "([0-9]{4} [0-9]{4} [0-9]{4} [0-9]{4})" test.txt Which shows me: 4556 4618 7843 8732 4532 0861 1932 5122 5440 3173 8207 0451 67886 6011 2966 7184 4668 4485 0721 1308 2759 Using this there is an extra line that shouldn't appear, where there is a 5th set of numbers that has 5 digits on the end. So I used: grep -E "([0-9]{4} [0-9]{4} [0-9]{4} [0-9]{4})$" test.txt But this only gave me two results instead of the 4 it should: 4556 4618 7843 8732 4485 0721 1308 2759 Can someone tell me what I'm doing wrong? A: You got halfway there with the end-of-line anchor $; you just need to anchor the beginning of the line, too, with ^. Looks like you're OK with a leading space, so allow for that as well, with *: grep -E "^ *([0-9]{4} [0-9]{4} [0-9]{4} [0-9]{4})$" test.txt If it helps to simplify the typing (or understanding) any, you could combine the first three patterns: grep -E "^ *([[:digit:]]{4} ){3}[[:digit:]]{4}$" ... meaning you want 3 of the quantity (4 digits followed by a space) followed by a space, then 4 digits, then EOL. A: $ grep -E '^[[:blank:]]*[0-9]{4} [0-9]{4} [0-9]{4} [0-9]{4}[[:blank:]]*$' file 4556 4618 7843 8732 4532 0861 1932 5122 6011 2966 7184 4668 4485 0721 1308 2759 Your expression matches lines with four or more sets of space-delimited four-digit numbers. The parentheses don't do anything in the expression. The expression above anchors the pattern to the start and end of the line and only allows spaces or tabs to exist before the first and after the last sets of digits. As an alternative to using the ^ and $ anchors, you could instead use grep -x: grep -Ex '[[:blank:]]*[0-9]{4} [0-9]{4} [0-9]{4} [0-9]{4}[[:blank:]]*' And shortening this, just like Jeff has shown, grep -Ex '[[:blank:]]*([0-9]{4} ){3}[0-9]{4}[[:blank:]]*'
[ "stackoverflow", "0034434410.txt" ]
Q: How do I view LightSwitch database data in Visual Studio? I have added data to a table and I want to delete or edit it without creating a view screen. How can I view data in a table of a LightSwitch database inside Visual Studio in debug mode? There is no option for viewing table data when right clicking an lsml file. I also tried adding a new connection in the server explorer using a Microsoft SQL server database file and choosing bin/data/ApplicationDatabase.mdf, but I got the error: "The file is in use." Closing the solution in Visual Studio didn't solve the problem and I still get the same error again. A: If you're using Visual Studio 2013 and an intrinsic LightSwitch database, you can use the server explorer management options to view and maintain the table data. In order to do this, you'll need to use the following settings when adding the connection: Data source: Microsoft SQL Server (SqlClient) Server name: (localDb)\v11.0 Log on to the server: Use Windows Authentication Connect to a database: Select the appropriate database name When selecting the database name, it should appear as the full project folder path followed by \BIN\DATA\APPLICATIONDATABASE.MDF.
[ "askubuntu", "0000014334.txt" ]
Q: Dual network connection I have a usb cellular modem and a Home LAN connection on my Ubuntu 10.10 box. Both work independently. I want to know how to have both connected at the same time, and be able to specify which application uses which device to connect to the internet. Does anyone know how to do this? A: There is no direct way to tell an application to use a specific connection, you can do two different but complex things in order to acheve the same result. First you can bind the two networks together so they're both being used: http://www.tomshardware.com/forum/21544-42-combining-multiple-internet-connections-home-network The other is that you set up one connection as a proxy service and configure individual apps to use the proxy instead of the general network. http://www.ehow.com/how_5019947_set-up-proxy-server-ubuntu.html
[ "scifi.stackexchange", "0000083943.txt" ]
Q: Is an android from Star Trek cold or hot to the touch? It may seem silly to ask and/or obvious to answer. I can't recall exact episode titles I'm afraid, but when Deanna was pregnant, Data was assumed by Pulaski to be cold to the touch. In contrast, the child in Pen Pal had no lines indicating this fact, and she of all witnesses would be likely to say he was cold, even if she had known prior to their meeting. This might be inaccurate to the trek-lore of the androids but since there is mechanical functions working about him, perhaps, under my own personal theory, rather than typical human warmth upon his bioplasmic skin, he might have artificial warmth, like that of a surge protector of computer cords. Or maybe I am terribly wrong and there is none; rendering him cold like the surface of washing machines. What causes this roller-coaster of debate is that during Ensigns of Command, his new friend, a woman, kissed him and later on, out of support, and she clearly enjoyed it. I think he has to have warmth. I can't imagine anyone having her expression kissing cold lips. Anyway, I'd like some input on this. It's boggling my mind. A: Human-normal. A Soong-Type android is designed to closely mimic the human body. This includes a regulated temperature, "fully-functional" anatomy, hair growth - even pumping bodily fluids and a pulse. Much of this was discussed in the TNG 2-part episode "Birthright." Numerous members of the Enterprise crew, including those unfamiliar with Data, have had physical contact with the android and expressed no surprise at his skin temperature. As you mentioned, he was kissed by Ard'rian with no indication on her part that he was cold. He was also intimate with Tasha Yar, although her reaction (beyond embarrassment) was never seen on-screen. However, we have every indication that - physically, at least - the interaction was normal. In fact, all indications on-screen are that Data could pass for human if not for his golden skin & eyes. As for Dr. Pulaski, it's important to note that the character is shown to have a certain hostility towards technology in general. Other comments by her have indicated that she thinks of Data as nothing more than a machine, a cold, emotionless robot. In essence, as Data is considered by Federation law to be his own "species", we could say that Pulaski is "speciesist" against him. A: This small bit of dialog from Birthright Part 1: BASHIR: You're breathing.  DATA: Yes. I do have a functional respiration system. However, its purpose is to maintain thermal control of my internal systems. I am, in fact, capable of functioning for extended periods in a vacuum.  We can directly know that Data's breath will have some heat to it, we can infer that his body will have some level of heat to it as well. Furthermore: BASHIR: Your creator went to a lot of trouble to make you seem human. I find that fascinating. There is a constant thread of Data not being recognized as artificial. Some think he is weird but not outside the range of possible human looks. Soong, the perfectionist he is, would not overlook body temperature.
[ "stackoverflow", "0017051974.txt" ]
Q: How do I use a static function in blade.php tempate in laravel 4? I have a class public static method that grabs some database information and returns a integer. In a controller i can call that method just fine. How do i call that static method in a blade template? For example: @foreach ($tasks as $task) {{Task::percentComplete($task->id)}}%<br /> @endforeach Thank you A: You could either A- Make it a Facade : http://laravel.com/docs/facades B- Move it into a helper/library : https://stackoverflow.com/a/13481218/2446119 I personally think that helpers and libraries are much easier and quicker to code, but facades are cleaner.
[ "mathoverflow", "0000161247.txt" ]
Q: Must a closed totally path-disconnected subset of the sphere have connected complement? This question (which is more a curiosity than a research problem) originates from these two: https://math.stackexchange.com/questions/720254/is-there-a-nonempty-open-bounded-subset-of-plane-whose-boundary-contains-no-1-di complement of a totally disconnected closed set in the plane The first question basically asks: does there exist a non-dense, open subset of $S^2$ whose boundary contains no image of injective paths? I think that this reduces to asking for an open, non-dense set whose boundary is totally path-disconnected. If we remove the word "path", then the answer is given in question 2. Is the answer easy/known/unknown including the word "path"? A: A circular version of the pseudo-arc (where you construct it out of "circular chains" whose ends connect up to each other) is a counterexample. It is connected and totally path-disconnected, and its complement has two components. This example seems to be due to Bing (Example 2 of this paper).
[ "stackoverflow", "0062149048.txt" ]
Q: Apache Olinge OData service throws EdmSimpleTypeException when the column in database is of type TEXT or BLOB I have made an entity by using JPA in eclipse. The definition of the table in my MySQL is like this: CREATE TABLE `users` ( `id` int(255) NOT NULL, `name` varchar(255) NOT NULL, `photo_content` text CHARACTER SET ascii DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8; and the equivalent entity that I generated by JPA is like this: import java.io.Serializable; import javax.persistence.*; import java.util.Set; /** * The persistent class for the users database table. * */ @Entity @Table(name="users") @NamedQuery(name="User.findAll", query="SELECT u FROM User u") public class User implements Serializable { private static final long serialVersionUID = 1L; @Id @Column(unique=true, nullable=false) private int id; @Column(nullable=false, length=255) private String name; @Lob @Column(name="photo_content") private String photoContent; //bi-directional many-to-one association to Answer @OneToMany(mappedBy="user") private Set<Answer> answers; //bi-directional many-to-one association to Survey @OneToMany(mappedBy="user") private Set<Survey> surveys; public User() { } public int getId() { return this.id; } public void setId(int id) { this.id = id; } public String getName() { return this.name; } public void setName(String name) { this.name = name; } public String getPhotoContent() { return this.photoContent; } public void setPhotoContent(String photoContent) { this.photoContent = photoContent; } public Set<Answer> getAnswers() { return this.answers; } public void setAnswers(Set<Answer> answers) { this.answers = answers; } public Answer addAnswer(Answer answer) { getAnswers().add(answer); answer.setUser(this); return answer; } public Answer removeAnswer(Answer answer) { getAnswers().remove(answer); answer.setUser(null); return answer; } public Set<Survey> getSurveys() { return this.surveys; } public void setSurveys(Set<Survey> surveys) { this.surveys = surveys; } public Survey addSurvey(Survey survey) { getSurveys().add(survey); survey.setUser(this); return survey; } public Survey removeSurvey(Survey survey) { getSurveys().remove(survey); survey.setUser(null); return survey; } } As soon as the column photo_content has some value like this: data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAQAAAAEACAYAAABccqhmAAAABmJLR0QA/wD/AP+gvaeTAAAACXBIWXMAAAsTAAALEwEAmpwYAAAopElEQVR42u2deXxU5b3/33NmyWQhhAQSSIIxAwIiKKCCUqgUURGdunSzYqttbW9v7/XW3uu1tW6tSzftta297e8Wf+7WrVXrWGy9Vm21WBFRQVYhkJhAyELWmcx+7h/nAFkns8+cme/79eIFLzKZ85zPeb6f86zfx3TetRciGJdwpauwqITpwAlAJVCh/zny7ylAGWAHSoACwAYUDvuqAcAP+IB+wAt0A+1AJ9AFtOr/bgMaPf3sVdqcA/IUjItFJDBMkM8B5gLzgOOB44CZeqAng8JBphDVdxaVACWuNmAP0ATsBz4Atnv62SnmIAYgxIjd4ZoALAQWA6cCJwOzsvhZVep/lg4zhyAlrj3Ae8A7wEbgXW+Ds0+ecvZgki5AhpnqqrIXcRawHFiG9obPVWMOorUQ3gBe93r4K63OQ1IJxADyBr05vxJYBZyL1qzPZ7YDLwEve/p5RboNYgA5h1LtqrXZcQIXAp9g5ACcoDEAvAq84PfiCh9wNoskYgCGxFzrqrPa+AxwCXAmYBJVYkIF3gSeDfh5OtTsbBRJxACyPegnWW1cBlwhQZ8SM3g04OeJULOzSyQRA8iWoDdZbXwC+CpwKdocu5A6/MAzwLqAn1dDzU5VJBEDSD/a6P2XgKuBGSJIRtgL3Of18IDMJogB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7EMWAWcD5yY55LsAF4EXq6bzRtGza8vBiDEhLnWZQo1O1V9NmEpsAxt3OBUcreF4Ac2AxuAN6qms+FIf/6oHoIYQD4TrnQVtrdwGtrxZ4vQUpnNwXhjCCpa/vytR4J+Sg2blDbngDxlMQAhdlM4UTeDWcBMYLr+74oMF68T2A18BOzR/711Sg07JNjFAIT0mEMdUI92bPpU/e8KoBCYBkwGCoCJ+q+Vc6xFoQIB4Ejfu1f/Px/QARwEBvRAb0Mbh28D9k2poVGC3Nj8H1wwenSbpdbLAAAAEnRFWHRFWElGOk9yaWVudGF0aW9uADGEWOzvAAAAAElFTkSuQmCC and I try to read the Users by OData service I will see the following exception: <error xmlns="http://schemas.microsoft.com/ado/2007/08/dataservices/metadata"> <code/> <message xml:lang="en">Missing message for key 'org.apache.olingo.odata2.api.edm.EdmSimpleTypeException.PROPERTY_VALUE_FACETS_NOT_MATCHED'!</message> </error> How can I solve it? I found another post here that in the answer, it has been claimed that this error is because of data type conversion but when it is long string we don't have any type casting! A: It is only needed to force olingo to remove length for the attribute. By the above definition for the User entity it will end up with maxLength=255 in the metadata. So when we want to use LongText or Blob or Clob with olingo-jpa we must provide a negative size for the property, then it will assume unlimited size for the property! @Lob @Column(name="photo_content", length=-1) private String photoContent;
[ "stackoverflow", "0051756804.txt" ]
Q: Why am I missing "META-INF" folder in my apk in Unity? I have signed my apk. But META-INF folder is missing. Please help me fix this. Thanks in advance! A: try to generate signed apk with command (windows cmd) create a key using keytool -genkey -v -keystore my-release-key.keystore -alias alias_name -keyalg RSA -keysize 2048 -validity 10000 then sign the apk using : jarsigner -verbose -sigalg SHA1withRSA -digestalg SHA1 -keystore my-release-key.keystore my_application.apk alias_name
[ "stackoverflow", "0058430305.txt" ]
Q: How to display remapped key instead of original key in operator-pending mode in vim-airline? I have discovered Vim a year ago and I am getting more and more addicted to it. I remapped every key of my french dvorak-like bépo layout to stick to the qwerty layout for the normal mode, as described in "Reconfiguration totale des touches" on this page: https://bepo.fr/wiki/Vim, essentially because I learnt with Vim Adventures game. It works very well: For instance, yr remaps as cl : the command cuts the character to the right and enter insertion mode. However, the vim status line displays y for one second before displaying c: I changed my mapping from: noremap y c to this : map <nowait> y c without success. Anyone knows if it is possible to display a remapped operator-pending key immediately, i.e. "c" in my case ? A: This has nothing to do with vim-airline or any other plugin. The pending operator is shown due to showcmd standard option. AFAIK, there's no way to change this, except to disable it completely (set noshowcmd), or to patch Vim's source code.
[ "math.stackexchange", "0000783521.txt" ]
Q: Solving Pell's equation: algorithm to converge $\sqrt n$ I'm trying to come up with an algorithm to solve the Diophantine equation $$ x^2 - ny^2 = 1 $$ for minimum values of $x$ when $ n $ is given. This equation is also known as Pell's Equation. The only accepted solutions are positive integer values of $x$ and $y$, and it has been proven that no solutions exists for any $n$ that is a square. I know that I can solve this by looking at all convergents for $ \sqrt n $. For example, for $ n = 2 $, the solution is $ x = 3 $ and $ y = 2 $, which is the first convergent of $ \sqrt 2 $: $ 3 \over 2 $. However, I'm struggling with how to determine these convergents. I'm using this recursive formula: $$ \sqrt n = 1 + {n - 1 \over 1 + \sqrt n} $$ To calculate a $k ^{th}$ convergent, I apply the formula with depth $ k $ and fill in $ 1 $ for the base case. This works for the first few cases, but for $ n =6 $, this gives me $ 7 \over 2$ for the first convergent, whereas I know this should be $ 5 \over 2 $, because $ x = 5 $ and $ y = 2 $ is the solution for $ x^2 - 6y^2 = 1 $. I arrive at $ 7 \over 2$ like this: $ \sqrt 6 \approx 1 + {6 - 1 \over 1 + 1} = {7 \over 2 }$ A: I finally figured this out. There are remarkably few good resources on this topic. I finally stumbled upon this video, which (unexpectedly) does a great job explaining the convergence of square roots: https://www.youtube.com/watch?v=49CKAPq8g-w I got the formula used in the question from wikipedia and although it kind of works, it's not the correct way of converging square roots and doesn't lead to correct solutions to the Pell's equation. The correct way of converging is defining the term to be converged as an infinite formula of the following form: $$ T = b_0 + {1 \over b_1 + {1 \over b_2 + {1 \over ... }} }$$ In this formula, $ b_0,b_1,...,b_n $ are the partial denominators that we can use to get the convergents. This answer describes an algorithms to calculate these values for the convergence of square roots of a known $n$. Let's call the term to be converged $ T $. $T$ can be expressed like this: $$ T = {a_0 \sqrt x + a_1 \over a_2} $$ For the first iteration, $ T = \sqrt x$, so: $a_0, a_1, a_2 = (1,0,1) $ Find the highest integer $ b $ for which $ b < T $, or: $ b = \lfloor T \rfloor $. This is our first partial denominator. Separate $T$ and $b$: $$ T = b + T - b $$ Replacing $T$ gives: $$ T = b + {a_0 \sqrt x + a_1 \over a_2} - b $$ This can be unified: $$ T = b + {a_0 \sqrt x + a_1 - ba_2 \over a_2} $$ Flip this to $$ T = b + {1 \over {a_2 \over a_0 \sqrt x - (ba_2-a_1)}} $$ Rationalize the lower term by multiplying with $${a_0 \sqrt x + (ba_2-a_1) \over a_0 \sqrt x + (ba_2-a_1)}$$ Like this: $$ T = b + {1 \over {a_2 \over a_0 \sqrt x - (ba_2-a_1)}{a_0 \sqrt x + (ba_2-a_1) \over a_0 \sqrt x + (ba_2-a_1)} } $$ This gives: $$ T = b + {1 \over {a_2 a_0 \sqrt x + a_2(ba_2-a_1) \over a_0^2x - (ba_2-a_1)^2 } } $$ Now this may seem like we didn't gain much, but we actually have a term here that is of the same form as what we started with. So now we can do the next iteration by getting new values for $ a_0,a_1,a_2$: $$ a'_0 = a_2a_0 $$ $$ a'_1 = a_2(ba_2-a_1)$$ $$ a'_2 = a_0^2x - (ba_2-a_1)^2 $$ And now simply get the next partial denominator with the floor function! (step 1): $$ b' = \left\lfloor {a'_0 \sqrt x + a'_1 \over a'_2} \right\rfloor $$ Final note: when implementing this as an algorithm, these terms $a_0,a_1,a_2$ should be simplified after each iteration by dividing them with their greatest common divisor. Otherwise the numbers might grow too big to handle.
[ "stackoverflow", "0044488320.txt" ]
Q: Replace the opening and closing string, while keeping the enclosed value? String value="==Hello=="; For the above string, I have to replace the "==" tags as <Heading>Hello</Heading>. I have tried doing it like this: value = value.replaceAll("(?s)\\=\\=.","<heading>"); value = value.replaceAll(".\\=\\=(?s)","</heading>"); However, my original dataset is huge, with lots of strings like this to be replaced. Can the above be performed in a single statement, giving preference to performance? The regex should not affect strings of form, ===<value>===, where value is any string of characters[a-z,A-Z]. A: To avoid iterating over string many times to first replace ===abc=== and then ==def== we can iterate over it once and thanks to Matehr#appendReplacement and Matcher#appendTail dynamically decide how to replace found match (based on amount of =). Regex which can search find both described cases can look like: (={2,3})([a-z]+)\1 but to make it more usable lets use named groups (?<name>subregex) and also instead of [a-z] use more general [^=]+. This will give us Pattern p = Pattern.compile("(?<eqAmount>={2,3})(?<value>[^=]*)\\k<eqAmount>"); Group named eqAmount will hold == or ===. \\k<eqAmount> is backreference to that group, which means regex expects to find it also == or === depending on what eqAmount already holds. Now we need some mapping between == or === and replacements. To hold such mapping we can use Map<String,String> replacements = new HashMap<>(); replacements.put("===", "<subheading>${value}</subheading>"); replacements.put("==", "<heading>${value}</heading>"); ${value} is reference to capturing group named value - here (?<value>[^=]*) so it will hold text between both == or ===. Now lets see how it works: String input = "===foo=== ==bar== ==baz== ===bam==="; Map<String, String> replacements = new HashMap<>(); replacements.put("===", "<subheading>${value}</subheading>"); replacements.put("==", "<heading>${value}</heading>"); Pattern p = Pattern.compile("(?<eqAmount>={2,3})(?<value>[^=]*)\\k<eqAmount>"); StringBuffer sb = new StringBuffer(); Matcher m = p.matcher(input); while (m.find()) { m.appendReplacement(sb, replacements.get(m.group("eqAmount"))); } m.appendTail(sb); String result = sb.toString(); System.out.println(result); Output: <subheading>foo</subheading> <heading>bar</heading> <heading>baz</heading> <subheading>bam</subheading>
[ "stackoverflow", "0003099766.txt" ]
Q: Highlight selection even when tree is not focused I use simultaneously several TVirtualStringTree on the same form. If a tree has a selected node, but the focus is currently on another tree, the selection is highlighted with a pale gray color. Is there a simple way to have the selection of an unfocused TVirtualStringTree highlighted with the usual selction color (blue on my computer) ? Thanks A: While setting the colours will work, the "correct" method is enabling TreeOptions --> PaintOptions --> toPopupMode toPopupMode // Paint tree as would it always have the focus (useful for tree combo boxes etc.)
[ "math.stackexchange", "0000446960.txt" ]
Q: Prove that if A is symmetric and invertible, then$ (A^{-1})^t = (A^t)^{-1}$. I have a problem. Prove that if A is symmetric and invertible, then $(A^{-1})^t = (A^t)^{-1}$. This is what I have done, please tell me if it is correct: Say $C=A^{-1}$. Then, $C^t = ((C^{-1})^t)^{-1} = ((C^{-1})^{-1})^t = C^t$. A: If $A$ is an invertible matrix (symmetric or not symmetric) then $$AA^{-1}=I\Rightarrow \left(AA^{-1}\right)^T=\left(A^{-1}\right)^TA^T=I$$ so the matrix $A^T$ is invertible and $$\left(A^T\right)^{-1}=\left(A^{-1}\right)^T$$
[ "stackoverflow", "0020845931.txt" ]
Q: Function constructor in javascript HTML: <textarea id="ta" cols="20" rows="20">alert("Hello World");</textarea> <input type="button" value=" Exec " onclick="exec()" /> JS: function exec() { var code=document.getElementById('ta').value; var fn=new Function(code); fn(); } http://jsfiddle.net/3Z5qP/6/ Can anyone tell me the logic behind the code on how it display's "Hello World" and i was looking at the MDN Does this code above creates a new alert function for me using the new Function constructor A: Function(string) returns a function with string as its body. That code grabs the text in the text area, inserts it into the body of a function, and then runs it. In this case, the code is the single command, alert("Hello World");. You can try it in a simpler example: var t = new Function('alert("hello, world")'); t(); // Alerts "hello, world"
[ "stackoverflow", "0004666101.txt" ]
Q: Returning timer job status from custom timer job There is a timer job status page in Central Admin /_admin/ServiceRunningJobs.aspx How can I properly return the status for my custom timer job ? The Execute() method of timer job returns void. A: It either fails (Exception) or succeeds (Method completes)
[ "stackoverflow", "0054892676.txt" ]
Q: Why is Pandas df.to_hdf("a_file", "a_key") output increases in size when executed multiple times Pandas has a method .to_hdf() to save a dataframe as a HDF table. However each time the command .to_hdf(path, key) is run, the size of the file increases. import os import string import pandas as pd import numpy as np size = 10**4 df = pd.DataFrame({"C":np.random.randint(0,100,size), "D": np.random.choice(list(string.ascii_lowercase), size = size)}) for iteration in range(4): df.to_hdf("a_file.h5","key1") print(os.path.getsize("a_file.h5")) And the output clearly shows that the size of the file is increasing: # 1240552 # 1262856 # 1285160 # 1307464 As a new df is saved each time, the hdf size should be constant. As the increase seems quite modest for small df, with larger df it fastly leads to hdf files that are significantly bigger than the size of the file on the first save. Sizes I get with a 10**7 long dataframe after 7 iterations: 29MB, 48MB, 67MB, 86MB, 105MB, 125MB, 144MB Why is it so that the hdf file size is not constant and increase a each new to_hdf()? A: This behavior is not really documented if you look in a fast manner at the documentation (which is 2973 pdf pages long). But can be found in #1643, and in the warning in IO Tools section/delete from a table section of the documentation: If you do not specify anything, the default writing mode is 'a'which is the case of a simple df.to_hdf('a_path.h5','a_key') will nearly double the size of your hdf file each time you run your script. Solution is to use the write mode: df.to_hdf('a_path.h5','a_key', mode = 'w') However, this behavior will happen only with the fixed format (which is the default format) but not with the table format (except if append is set to True).
[ "tex.stackexchange", "0000020161.txt" ]
Q: Vertical centering of text within a table I have a table defined as: \begin{table} \begin{center} \setlength{\extrarowheight}{3.0pt} \begin{tabular}{ | c | p{12.5cm} |} \hline \textbf{Item 1} & Long description of item 1 \\ \hline % ... (etc) \end{tabular} \end{center} \end{table} I want the text in the first column to be both vertically and horizontally aligned. Given the code above, the text is only horizontally aligned. I have tried fixing this by changing the column alignment/width specifier from 'c' to 'm{2.5cm}', but to no avail. How do I make the column centered both horizontally and vertically? A: Write \begin{tabular}{|c|m{12.5cm}} This requires loading the array package (that you're already loading, but other users might not know it). Some comments Each table has its particular features and it's quite difficult to state "universal rules". In general, however, vertical rules should be avoided as they make the table more difficult to read horizontally. A generous amount of space between rows can visually separate them in a more pleasant way than with a rule. Whether centering vertically the description in the first column depends on the table, but I feel it can be distracting.
[ "stackoverflow", "0042314731.txt" ]
Q: How to write registered user into database in Swift? When i select register.. the data is sent to Firebase authentication but does not store in the database? Can anyone tell me where im going wrong? func handleRegister(){ // Validation guard let email = emailTextField.text, let password = PassTextField.text, let name = nameTextField.text else{ print("Please provide an Email and Password") return } FIRAuth.auth()?.createUser(withEmail: email, password: password, completion: { (user: FIRUser?, error) in if error != nil { print(error!) return } // Successfully authenticated user // Saving Data to the Database let ref = FIRDatabase.database().reference(fromURL: "https://chat-47e5b.firebaseio.com/") let values = ["name": name, "email": email] ref.updateChildValues(values, withCompletionBlock: { (err,ref) in if err != nil { print(err!) return } print("Saved user successfully into Firebase") }) }) } A: You are not doing it right, you should first get a reference to the db: self.ref = FIRDatabase.database().reference() Then: let values = ["name": name, "email": email] self.ref.child("users").child(user.uid).setValue(values) As a side note, convert this: if error != nil { print(error!) return } To this: guard let error = error else { print(error) return }
[ "robotics.stackexchange", "0000000274.txt" ]
Q: Low-cost servo with digital control interfaces? Some years ago, there where some projects that provided hardware and software to perform modifications on standard hobby servos to convert them to digital servos, with all the advantages that come with it. OpenServo is a little outdated, and does not seem to be worked on anymore, and there is no hardware to buy. Sparkfun has its own version of the OpenServo, which at least is available for buying. Do you know if there are other mods, or even complete low cost digital servos? I am mostly interested in position feedback, and servo chaining. A: Yes, the v3 OpenServo is out of stock. In fact we are working on a new version 4 of OpenServo that will modernise the codebase. There are no timelines for the v4 as yet, but work has only just started. I would recommend the SparkFun board for now.
[ "stackoverflow", "0007016725.txt" ]
Q: php not picking up data from help? I'd really appreciate some help. I have a php/html script that displays a certain select with options based on $specqId, if the $specqId does not equal any of the specified numbers in the if/else if statement, then just display input <?php if($specqId == 5){ ?> <select id="a1" name"a1"> <option value="8.5 x 11">Letter 8.5" x 11"</option> <option value="8.5 x 14">Legal 8.5" x 14"</option> <option value="11 x 17">Tabloid 11" x 17"</option> </select> <?php }else if($specqId == 6){ ?> <select id="a1" name"a1"> <option value="18 x 24">18" x 24"</option> <option value="20 x 30">20" x 30"</option> <option value="30 x 40">30" x 40"</option> </select> <?php }else if($specqId == 8){ ?> <select id="a1" name"a1"> <option value="8.5 x 11">8.5" x 11"</option> </select> <?php }else { ?> <input type="text" name="a1" id="a1" value="" size="30"/> <?php }//end else ?> Now, here is the weird thing, the php that processes this form, does not pick up anything except whats in the input tag, it does not pick up whats in the select tag... any thoughts? A: Just a little syntax error. Change this <select id="a1" name"a1"> to: <select id="a1" name="a1">
[ "stackoverflow", "0004981052.txt" ]
Q: how to re-parent in Git What non-interactive git command(s) achieve the change from Before to After in each case? 1a. re-parenting I Before: A---B---C---D After: C'---D' / A---B 1b. re-parenting II Before: C---D / A---B After: C / A---B---D' 1c. re-parenting III Before: C / A---B---D After: C---B'---D' / A A: These all look like applications of git rebase --onto. 1a. re-parenting I Before: A---B---C---D After: C'---D' / A---B Set up branches to label the particular commits and then rebase onto. git checkout -b ex1a-b B git checkout -b ex1a-d D git checkout -b ex1a-a A git rebase --onto ex1a-a ex1a-b ex1a-d 1b. re-parenting II Before: C---D / A---B After: C / A---B---D' Creating branches similar to above: git rebase --onto ex1b-b ex1b-c ex1b-d. 1c. re-parenting III Before: C / A---B---D After: C---B'---D' / A Again with the branches, but now just git rebase ex1c-c ex1c-d. A: It depends on your definition of B', C', and D'. If you want to move around patches, so that (in the first example) git diff B C == git diff A C', then you want to "rebase" (not "reparent") using git rebase as described by Emil. If, on the other hand, you want to move around snapshots, then you really do want to "reparent". To do this, I suggest using git reparent. Most likely, you actually want to rebase and not reparent, but for reference, here are the commands for reparenting. They are somewhat complicated because this is not a normal thing to do. (The following assumes you are currently in a branch at D.) 1a. re-parenting I git rebase -i B # Select the "edit" command for C git reparent -p A git rebase --continue 1b. re-parenting II git reparent -p B 1c. re-parenting III git rebase -i A # Select the "edit" command for B git reparent -p C git rebase --continue
[ "unix.stackexchange", "0000156985.txt" ]
Q: keyboard hard remap keys? I am trying to find a way to remap keyboard keys forcefully. I tried using xmodmap and setxkbmap, but they do not work for one specific application. Such commands work for other normal windowed/applications on X tho. I think the application may be reading the keyboard raw data and ignoring X input? So, how to remap keys without using xmodmap and setxkbmap? if it is ever possible to be done using some software. I also tried xkeycaps, xkbcomp, but did not try loadkeys, as it is running on X. I found here that I could try setkeycodes, "because after assigning kernel keycode the button should work in xorg", but I also found that "you can't use 'setkeycodes' on USB keyboards", that's my case (I am interested in case someone make it work on ps2 as I think I could use an adapter). This seemed promising "Map scancodes to keycodes", but after a few tests nothing changed, here are they: I found keycode "36" ("j" key) at vt1 with showkey I found scancode "7e" (keypad ".") at vt1 with showkey --scancodes $cat >/etc/udev/hwdb.d/90-custom-keyboard.hwdb keyboard:usb:v*p* keyboard:dmi:bvn*:bvr*:bd*:svn*:pn*:pvr* KEYBOARD_KEY_7e=36 $udevadm hwdb --update #updates file: /lib/udev/hwdb.bin $udevadm trigger #should apply the changes but nothing happened $cat /lib/udev/hwdb.bin |egrep "KEYBOARD_KEY_7e.{10}" -ao KEYBOARD_KEY_7eleftmeta $#that cat on hwdb.bin did not change after the commands.. Obs.: did not work either with: KEYBOARD_KEY_7e=j Some more alternative ways (by @vinc17) to find the keys: evtest /dev/input/by-id/... or input-kbd 3 (put the id index found at ls -l /dev/input/by-id/* from ex. event3) PS.: *If you are interested on testing yourself, the related thread for the application is this: http://forums.thedarkmod.com/topic/14266-keyboard-issue-in-new-version-108/ The issues I have are the same: some keys (KP_Decimal, DownArrow, UpArrow, RightArrow) are ignored and considered all with the same value there "0x00" A: First find the scancode of the key that needs to be remapped, e.g. with the evtest utility. A line like the following one (with MSC_SCAN in it) should be output: Event: time 1417131619.686259, type 4 (EV_MSC), code 4 (MSC_SCAN), value 70068 followed by a second one giving the current key code. If no MSC_SCAN line is output, this is due to a kernel driver bug, but the scancode can still be found with the input-kbd utility; evtest should have given the key code, so that it should be easy to find the corresponding line in the input-kbd output (e.g. by using grep). Once the scancodes of the keys to be remapped have been determined, create a file such as /etc/udev/hwdb.d/98-custom-keyboard.hwdb containing the remappings. The beginning of the file /lib/udev/hwdb.d/60-keyboard.hwdb gives some information. In my case (which works), I have: evdev:input:b0003v05ACp0221* KEYBOARD_KEY_70035=102nd # Left to z: backslash bar KEYBOARD_KEY_70064=grave # Left to 1: grave notsign KEYBOARD_KEY_70068=insert # F13: Insert (Before udev 220, I had to use keyboard:usb:v05ACp0221* for the first line.) The evdev: string must be at the beginning of the line. Note that the letters in the vendor and product id should be capital letters. Each KEYBOARD_KEY_ settings should have exactly one space before (note: a line with no spaces will give an error message, and a line with two spaces were silently ignored with old udev versions). KEYBOARD_KEY_ is followed by the scancode in hexadecimal (like what both evtest and input-kbd give). Valid values could be obtained from either the evtest output or the input-kbd output, or even from the /usr/include/linux/input.h file: for instance, KEY_102ND would give 102nd (by removing KEY_ and converting to lower case), which I used above. After the file is saved, type: udevadm hwdb --update to (re)build the database /etc/udev/hwdb.bin (you can check its timestamp). Then, udevadm trigger --sysname-match="event*" will take the new settings into account. You can check with evtest. In 2014, the released udev had incomplete/buggy information in /lib/udev/hwdb.d/60-keyboard.hwdb, but you can look at the latest development version of the file and/or my bug report and discussion concerning the documentation and spacing issues. If this doesn't work, the problem might be found after temporarily increasing the log level of udevd with udevadm control (see the udevadm(8) man page for details). For old udev versions such as 204, this method should still work.
[ "stackoverflow", "0003677875.txt" ]
Q: jquery and ajax where this technologies are used? I'm doing project where i'm going to use Jquery and ajax. I'm starting to learn this technology,i hv one doubt abt where does this jquery and ajax are used, are they used for same purpose. can anybody tell me situtation where jquery or ajax can be used both are for same purpose or different ? and any best book to start with jquery and ajax i'm doing with php ? A: jQuery is a javascript API. Makes it easier to use javascript (i think so). Ajax is a fancy name for any communication between a web page and its server. Bottomline: You can use jQuery to do Ajax easily. a good place to start jquery would be the jQuery book by Apress publications. That said, I've always relied on online tutorials (google) for my day-to-day needs rather than on a book. Cheers jrh
[ "stackoverflow", "0010904706.txt" ]
Q: how to find friend's past checkins near a location? In my app, a user is at a location and is looking for her friends who have been anywhere withing 10 miles of where she is. How do I find this with either FQL or graph? The only way that I can see is by running a search like so: https://graph.facebook.com/search?type=checkin and then running through the results to find out which location was within 10 miles. Is there a better way for this? Thanks for your help! Doles A: Although the initial answer did work for me for part of my purpose, it quickly became inadequate. Now, after banging my head against the wall, it finally broke (not my head - the wall). Here are two more BETTER ways that WORK to find what I need: This is to find just checkins: SELECT checkin_id, coords, tagged_uids, page_id FROM checkin WHERE (author_uid IN (SELECT uid2 FROM friend WHERE uid1 = me()) or author_uid=me()) and coords.latitude<'45.0' and coords.latitude>'29' and coords.longitude>'-175' and coords.longitude<'-5'; This is to find all location posts: SELECT id, page_id FROM location_post WHERE (author_uid IN (SELECT uid2 FROM friend WHERE uid1 = me()) or author_uid=me()) and coords.latitude<'45.0' and coords.latitude>'29' and coords.longitude>'-175' and coords.longitude<'-5'
[ "stackoverflow", "0043419599.txt" ]
Q: Promise.map function .then() block getting null before nested promise resolves I'm kicking off a nested promise mapping and seeing the outer .then() block print a null result before the resolve in the function is called. I feel like I must be messing up the syntax somehow. I've made this stripped down example: const Promise = require('bluebird'); const topArray = [{outerVal1: 1,innerArray: [{innerVal1: 1,innerVal2: 2}, {innerVal1: 3,innerVal2: 4}]},{outerVal2: 2,innerArray: [{innerVal1: 5, innerVal2: 6 }, {innerVal1: 7,innerVal2: 8 }]}] ; promiseWithoutDelay = function (innerObject) { return new Promise(function (resolve, reject) { setTimeout(function () { console.log("promiseWithDelay" ,innerObject); let returnVal = {} returnVal.innerVal1 = innerObject.innerVal1; returnVal.innerVal2 = innerObject.innerVal2; returnVal.delay = false; return resolve(returnVal); }, 0); }) } promiseWithDelay = function (innerObject) { return new Promise(function (resolve, reject) { setTimeout(function () { console.log("promiseWithDelay" ,innerObject); let returnVal = {} returnVal.innerVal1 = innerObject.innerVal1; returnVal.innerVal2 = innerObject.innerVal2; returnVal.delay = true; return resolve(returnVal); }, 3000); }) } test1 = function () { let newArray = []; let newArrayIndex = 0; Promise.map(topArray, function (outerObject) { Promise.map(outerObject.innerArray, function (innerObject) { Promise.all([ promiseWithoutDelay(innerObject), promiseWithDelay(innerObject) ]) .then(function (promiseResults) { newArray[newArrayIndex++] = {result1: promiseResults[1], result2: promiseResults[2]} }) }) }) .then(function () { return newArray; }) } var result = test1(); console.log("got result ",result); What I'm trying to do is loop over an outer array that has some values that I need. These values include a nested inner array that I must also loop over to get some values. In the inner loop I pass the outer and inner values to promise functions in a Promise.all. When the promise functions resolve they get assigned to a return object. It seems to be working fine except for one of the promise functions sometimes has a delay as it's doing some calculations. When this happens it is left out of the return value because it hasn't resolved yet. Shouldn't it wait until the inner loop with Promise.all resolves before it returns from the outer loop? Can you point me in the right direction? EDIT: Ended up with this solution based on @Thomas's suggestion: test1 = function(){ return Promise.map(topArray, function(outerObject){ let oVal = outerObject.outerVal; return Promise.map(outerObject.innerArray, function(innerObject){ innerObject.oVal = oVal; return Promise.all([ promiseWithDelay(innerObject), promiseWithoutDelay(innerObject)]) .then(function(results) { return { result1: results[0], result2: results[1], delay: results[2] } ; }) }) }).reduce(function(newArray, arr){ return newArray.concat(arr); }, []); } A: I'm not entirely sure I get your problem from your stripped down example, but I think what you want to do here is this: test1 = function(){ return Promise.map(topArray, function(outerObject){ return Promise.all(outerObject.innerArray) }).reduce(function(newArray, arr){ return newArray.concat(arr); }, []); }
[ "mathoverflow", "0000283634.txt" ]
Q: Are there unique additive decompositions of the reals? Given $b\in \mathbb{R}_{>1}$ is there $U\subseteq\mathbb{R}_{\ge 0}$ such that $U+bU=\mathbb{R}_{\ge 0}$ and $(U-U)\cap b(U-U)=\{0\}$ (or equivalently: $u+bv=u'+bv' \implies u=u', v=v'$)? Here is an example of near miss: if $b=10$ define $U$ as the set of positive reals with $0$ digits in odd places. Then the decomposition fails to be unique, but only for finite decimals, such as $1=1+10\times0=0.0909... +10\times 0.0909...$ This question is a simple case of a larger, still fuzzy problem I'm thinking about, but I don't want to jump into that without knowing what surely must already have been studied in depth. I welcome suggestions or edits for better title and tags. A: Can't this be solved in the following usual manner? Take the first ordinal $\phi$ of cardinality continuum, and let $\{p_\alpha\colon \alpha<\phi\}$ be an enumeration of points in $\mathbb R_{\geq 0}$, with $0$ being the minimal point. We construct the set $U$ by transfinite recursion on $\alpha$. Initially, we put $0$ into $U$. After performing step $\alpha$, we will have $(U-U)\cap b(U-U)=0$ and $\{p_\beta\colon \beta\leq \alpha\}\subseteq U+bU$. Assume we have reached step $\alpha$, so now $\{p_\beta\colon \beta<\alpha\}\subseteq U+bU$. If $p_\alpha\in U+bU$ as well, we do nothing on this step. Otherwise, we choose some distinct $x_\alpha$, $y_\alpha$ with $x_{\alpha}+by_\alpha=p_\alpha$ and put $x_\alpha,y_\alpha$ into $U$. There are continuumly many choices for this pair, and less obstructions (each of which involves one, two, or three elements from the recent $U$). Thus such pair can be chosen. [EDIT] The obstructions mentioned in the previous paragraph are: $$ x_\alpha-u_1=\pm b^{\pm1}(u_2-u_3);\\ y_\alpha-u_1=\pm b^{\pm1}(u_2-u_3);\\ x_\alpha-u_1=\pm b^{\pm1}(y_\alpha-u_2);\\ x_\alpha-y_\alpha=\pm b^{\pm1}(u_1-u_2);\\ x_\alpha-y_\alpha=\pm b^{\pm1}(x_\alpha-u_1);\\ x_\alpha-y_\alpha=\pm b^{\pm1}(y_\alpha-u_1). $$ Almost for every choice of the $u_i$, each of the obstructions prohibits a finite set of pairs $(x_\alpha,y_\alpha)$, since we have two linear equations on this pair (along with $x_\alpha+by_\alpha=p_\alpha$). There can be uncountably many such choices of the $u_i$, but their cardinality is still less than continuum --- by the choice of $\phi$; so still there are unobstructed pairs. Exceptions. It might occasionally happen that the obstruction is linearly dependent with the condition $x_\alpha+by_\alpha=p_\alpha$. These hypothetical occasions are $\bullet$ in the third equality, read as $x+by=u_1+bu_2$; but then $p_\alpha\in U+bU$ already; $\bullet$ in the fifth equality, read as $(1-b)x_\alpha-y_\alpha=-bu_1$; this would mean that $\frac{b-1}1=\frac{1}b$, i.e., $b^2=b+1$ --- but then $x_\alpha+by_\alpha=b^2u_1=u_1+bu_1$, so $p_\alpha\in U+bU$ already; $\bullet$ in the last equality, read as $x_\alpha+(b-1)y_\alpha=bu_1$ --- but the left-hand side is not proportional to $x_\alpha+by_\alpha$. In all other cases, the signs of coefficients of $x_\alpha$ and $y_\alpha$ in the linear equation provided by the obstruction are not the same. So still the method seems to work.
[ "stackoverflow", "0035711907.txt" ]
Q: Adding elements to Django database I have a large database of elements each of which has unique key. Every so often (once a minute) I get a load more items which need to be added to the database but if they are duplicates of something already in the database they are discarded. My question is - is it better to...: Get Django to give me a list (or set) of all of the unique keys and then, before trying to add each new item, check if its key is in the list or, have a try/except statement around the save call on the new item and reply on Django catching duplicates? Cheers, Jack A: If you're using MySQL, you have the power of INSERT IGNORE at your finger tips and that would be the most performant solution. You can execute custom SQL queries using the cursor API directly. (https://docs.djangoproject.com/en/1.9/topics/db/sql/#executing-custom-sql-directly) If you are using Postgres or some other data-store that does not support INSERT IGNORE then things are going to be a bit more complicated. In the case of Postgres, you can use rules to essentially make your own version of INSERT IGNORE. It would look something like this: CREATE RULE "insert_ignore" AS ON INSERT TO "some_table" WHERE EXISTS (SELECT 1 FROM some_table WHERE pk=NEW.pk) DO INSTEAD NOTHING; Whatever you do, avoid the "selecting all rows and checking first approach" as the worst-case performance is O(n) in Python and essentially short-circuits any performance advantage afforded by your database since the check is being performed on the app machine (and also eventually memory-bound). The try/except approach is marginally better than the "select all rows" approach but it still requires constant hand-off to the app server to deal with each conflict, albeit much quicker. Better to make the database do the work.
[ "mathematica.stackexchange", "0000129869.txt" ]
Q: How to minimize object size of a large list of strings Update: The discussion below was based on a made up example when objects are created in session. C.E. was absolutely right to point out that Mathematica can do the same trick and share objects. However, the question is inspired by reading large datasets from files. In this case, both MemoryInUse and ByteCount will show the same result. Suppose we create a matrix of strings: m1 = MemoryInUse[]; x=Table["String", {10000}, {100}]; ByteCount@x MemoryInUse[] - m1 (* 49040080 *) (* 9042656 *) Obviously, the trick with memory sharing works. Let's write this to file and read it back. Export["mat.csv", x, "CSV"]; m1 = MemoryInUse[]; x1 = Import["mat.csv", "CSV"]; MemoryInUse[] - m1 ByteCount@x1 x1===x (* 49044432 *) (* 49040080 *) (* True *) Apparently, Mathematica is using full space now (and even more for something else??) to store the matrix in memory. Any ideas how to force Mathematica to be less greedy after reading from file? Original post: I am trying to figure out the right way to work with large datasets. The problem is a huge memory overhead associated with a list of repeated strings in Mathematica. Specifically, I am comparing the memory management with R and it looks like Mathematica is far more greedy. Example: let's make a vector (or list) of one element which is a string of one character. R object.size(rep("1",1)) is 96 bytes Mathematica ByteCount@{"1"} is 88 bytes So we are good here. But let's see what happens when you do 100 elements. R object.size(rep("1",100)) is 888 bytes Mathematica ByteCount@Table ["1", 100] is 4896 bytes So we are using lot more memory in Mathematica now. Pushing it to the limits, let's do 1,000,000 R object.size(rep("1",1e6)) is 8,000,088 bytes Mathematica ByteCount@Table ["1", 1*^6] is 48,000,080 bytes All in all, Mathematica wants about 6 times more memory to store this simple list than R. What happens if we make the string longer? Let's do a 100 character string. R object.size(rep(strrep("1",100),1e6)) is 8,000,208 bytes Mathematica ByteCount@Table[StringJoin[Table["1", 100]], 1*^6] is 144,000,080 bytes Now R uses almost the same amount of memory as for the short string, but Mathematica uses an order of magnitude larger. Apparently, R understand that this is a repeating object and simply stores just one instance, while Mathematica stores all of them. For datasets and list of lists it is very important as usually there is a fixed list of string elements you use (names of categories, states, other features) and they are repeated many times. When importing such data set in R, it explicitly uses factor type, when the list of all instances is stored ones, and then the vector is simply a list of indices in that list. However, even when we are not using factor type in R, we have just seen that it still uses the same logic and stores such vectors much more efficiently. Can we emulate this in Mathematica? The problem is that of course, I don't want a brute force method when I read all the elements, make a unique list, and then make my own index. This would make dataset convenience go away. I would like to have a solution which works relatively seamlessly when used -- in other words I still have a sort of association or a dataset with multiple columns (some strings, some numbers etc.) that is memory optimized. A: The documentation for ByteCount states that ByteCount does not take account of any sharing of subexpressions. The results it gives assume that every part of the expression is stored separately. ByteCount will therefore often give an overestimate of the amount of memory currently needed to store a particular expression. When you manipulate the expression, however, subexpressions will often stop being shared, and the amount of memory needed will be close to the value returned by ByteCount. So what you are measuring is what the byte count would be if repetition is not taken into account, but it does not tell you how much memory Mathematica actually allocates. For that we can use a different approach: Clear[data]; mem = MemoryInUse[]; data = Table["1", 1*^6]; MemoryInUse[] - mem 8002664 Which is almost the same as R's 8,000,208 bytes. If you explicitly tell Mathematica that this is a list a repeated elements you can save some more memory, but not a lot in this case: Clear[data]; mem = MemoryInUse[]; data = ConstantArray["1", 1*^6]; MemoryInUse[] - mem 7999080 A: If the strings are repeated frequently and the order of the data is not critical, store the Tally of the data. mem = MemoryInUse[]; data = Transpose[{Table["1", 5*^5], Table["2", 5*^5]}] // Flatten; MemoryInUse[] - mem (* 8003392 *) mem = MemoryInUse[]; tally = Tally[data]; MemoryInUse[] - mem (* 2656 *) The sorted data can be reconstructed from the Tally Flatten[Table @@@ tally] === (data // Sort) (* True *)
[ "stackoverflow", "0009917383.txt" ]
Q: Prevent Diazo from escaping ampersands within an attribute I am using a template with the following TAL: <iframe tal:attributes="src view/src" /> where view.src returns a URL including a query string with ampersands. The template renders this fine, but after going through Diazo the ampersands are escaped as &amp; How can I prevent Diazo from doing this? A: The template is returning invalid HTML - outside of the CDATA script and style tags, ampersands should be encoded as entities (http://htmlhelp.com/tools/validator/problems.html#amp). The HTMLParser can guess what you mean, but the serializer encodes the data correctly on the way out and there is not way to avoid that. Note that this is just the HTML encoding of data, to take an example: <iframe src="http://example.com?foo=1&amp;baz=2" /> The value of the iframe's src attribute is http://example.com?foo=1&baz=2.
[ "stackoverflow", "0002553224.txt" ]
Q: Horizontal placement of components in JSF Should be simple but I couldn't find the answer, I would like to place components horizontally instead of vertically. What I'm trying to achieve is a rich:toolbar with 2 or more rows. I've been trying to do that with a toolbar that has a panelgrid and two panelgroups like this: <rich:toolbar...> <f:panelgrid columns="1"...> <f:panelgroup id="row1" .../> <-- Should be horizontal placement <f:panelgroup id="row2" .../> <-- Should be horizontal placement <f:panelgrid/> <rich:toolbar/> So how do I make the panelgroup layout horizontal (Or should I use something else?) Thanks! A: You probably already know that JSF in webserver ends up as HTML in webbrowser. In HTML, there are several ways to place elements horizontally (eventually with help of CSS): Group them in inline elements (like <span> or any element with display: inline;). Group them in block elements (like <div> or any element with display: block;) and give them all a float: left;. The JSF <h:panelGrid> renders a HTML <table> element wherein each child component is taken as a <td>. The columns attribute represents the max amount of <td> elements in a single <tr> (so that the <h:panelGrid> knows when to put a </tr><tr> in). The JSF <h:panelGroup> renders a <span> element. To achieve way 1 with JSF, you just need to group them in separate <h:panelGroup> components. <rich:toolbar ...> <h:panelgroup id="row1" ... /> <h:panelgroup id="row2" ... /> </rich:toolbar> Way 2 can be done the same way, but then with <h:panelGroup layout="block"> instead and a float: left; in their CSS.
[ "stackoverflow", "0046709646.txt" ]
Q: rxjava2 best practice to create an Observable from an existing Callback function I am new to rxjava2, and I want to use it to work with my existing code to solve the ignoring Callback hell. The main task is something like the code below : SomeTask.execute(new Callback() { @Override public void onSuccess(Data data) { // I want to add data into observable stream here } @Override public void onFailure(String errorMessage) { // I want to perform some different operations // to errorMessage rather than the data in `onSuccess` callback. // I am not sure if I should split the data stream into two different Observable streams // and use different Observers to accomplish different logic. // and I don't know how to do it. } } I have done some digging in Google and Stackoverflow, but still didn't find the perfect solution to create a observable to achieve these two goals. Wrap a existing Callback function. Process different Callback data in different logic. Any suggestion would be a great help. A: Take a look at this article. It will help you. Here is an possible solution to your problem (Kotlin): Observable.create<Data> { emitter -> SomeTask.execute(object: Callback() { override void onSuccess(data: Data) { emitter.onNext(data) emitter.onComplete() } override void onFailure(errorMessage: String) { // Here you must pass the Exception, not the message emitter.onError(exception) } } } Do not forget to subscribe and dispose the Observable. You must also consider using Single, Maybe or any of the other Observable types.
[ "stackoverflow", "0038893389.txt" ]
Q: Bokeh + interactive widgets + PythonAnywhere I was unable to find a minimal working example for an interactive web app using bokeh and bokeh widgets that runs on PythonAnywhere. Ideally, I would like to have a simple plot of a relatively complicated function (which I do not know analytically, but I have SymPy compute that for me) which should be replotted when a parameter changes. All code that I have found so far does not do that, e.g. https://github.com/bokeh/bokeh/tree/master/examples, or refers to obsolete versions of bokeh. Most of the documentation deals with running a bokeh-server, but there is no indication on how to have this running with WSGI (which is how PythonAnywhere handles the requests). For this reasone I have tried embedding a Bokeh plot within a Flask app. However, as far as I understand, in order to have interactive Bokeh widgets (which should trigger some computation in Python) do require a bokeh-server. I am not particularly attached to using either Flask or Bokeh, if I can achive a similar result with some other simpler tools. Unfortunately, a Jupyter notebook with interactive widgets does not seems to be an option in PythonAnywhere. I have installed bokeh 0.12 on Python 3.5. I have managed to run a simple bokeh plot within a flask app, but I am unable to use the Bokeh widgets. A: Here is a working example of Jupyter notebook with interactive widgets on pythonanywhere: %pylab inline import matplotlib.pyplot as plt from ipywidgets import interact def plot_power_function(k): xs = range(50) dynamic_ys = [x ** k for x in xs] plt.plot(xs, dynamic_ys) interact(plot_power_function, k=[1, 5, 0.5]) PythonAnywhere does have the ipywidgets module pre-installed. But if you are not seeing the interactive widgets, make sure that you have run jupyter nbextension enable --py widgetsnbextension from a bash console to get it enabled for your notebooks. You will have to restart the jupyter server after enabling this extension (by killing the relevant jupyter processes from the consoles running processes list on the pythonanywhere dashboard).
[ "stackoverflow", "0015377277.txt" ]
Q: padding for links vertical in nav bar I have worked on a new menu for my site, but I cannot seem to arrange for space between the links vertically (I want more white space between links) Any advice? html <ul class="menu"> <li><a href="#about">ABOUT</a></li> <li><a href="#contact">CONTACT</a></li> <li><a href="#services">SERVICES</a></li> </ul> css ul.menu { list-style-type:none; list-style-position: inside; margin:0; padding:0; padding-bottom: 1cm; } .menu li a, .menu li a:visited { padding:12px 0 0 0px; font-family: 'Roboto Condensed', sans-serif;font-size:20px;font-weight:700; color:#FFFFFF; background-color:#09F; text-align:center; padding:3px; text-decoration:none; } .menu li a:hover, menu li a:active { background-color:#666; } As you can see I have attempted the gaps with a piece of css: {padding:12px 0 0 0px;} but no luck.... everything else works fine - see fiddle @ http://jsfiddle.net/DCxvy/ A: Anchors are by default inline elements. To add certain padding values, you need to render them as inline block-level elements. Add display: block to your anchor styles: .menu li a { display: inline-block } Also, you should note that your .menu li a style has two entries for padding. The latter one (setting padding to 3px on all sides) is overriding your earlier definition. Here's a jsFiddle demo.
[ "stackoverflow", "0024851461.txt" ]
Q: Absolute path to file outside of project folder with getResourceAsStream() I want to create jar which will read txt fom jar and then save txt file to user.home folder. When it is runned again, it will read file from user.home. I read file like this: if(getClass().getResourceAsStream("/"+System.getProperty("user.home")+"/"+file_name) == null){ configStream = getClass().getResourceAsStream(file_name); } else { configStream = getClass().getResourceAsStream(System.getProperty("user.home")+ "/"+file_name); } BufferedReader br = new BufferedReader(new InputStreamReader(configStream)); And then I write to file like this: try { BufferedWriter out = new BufferedWriter(new FileWriter(System.getProperty("user.home")+ "/" + file_name)); for (int j = 0; j < y; j++) { for (int i = 0; i < x; i++) { if (((Block) (listArray.get(i).get(j))).getState() == blockState.blank) { out.write("0"); } else if (((Block) (listArray.get(i).get(j))).getState() == blockState.solid) { out.write("1"); } else if (((Block) (listArray.get(i).get(j))).getState() == blockState.player) { out.write("I"); } else if (((Block) (listArray.get(i).get(j))).getState() == blockState.spikes) { out.write("^"); } else if (((Block) (listArray.get(i).get(j))).getState() == blockState.water) { out.write("~"); } else if (((Block) (listArray.get(i).get(j))).getState() == blockState.transparent) { out.write("T"); } } out.write("\n"); } out.close(); } catch (IOException e) { e.printStackTrace(); } I don't know why, but program never read file from user.home, it always reads one from project folder. Where am I making a mistake? Thanks A: You cannot use getResourceAsStream on locations that are not within the JVM classpath. The following snippet works because somewhere within your JVM classpath the file_name exists. getClass().getResourceAsStream(file_name); What you are attempting to do here in the next snippet is to use the current class's classloader to load a file that may or may not be part of the JVM classpath. configStream = getClass().getResourceAsStream(System.getProperty("user.home")+ "/"+file_name); The relative root node from which this path will be traversed can also not be controller. Use a FileInputStream and load the file from an absolute path like /usr/local/file_name instead.
[ "stackoverflow", "0019829732.txt" ]
Q: Storing '\n' in Sql using Java I want to store a string containing '\n' in Sql using Java. But the problem is in the database instead of \n a new line is getting stored. e.g the string is "abcd\nefgh" then the database it is getting stored as abcd efgh I had the same issue when i was storing such things using php i overcame that using mysqli_escape_real_string() How can i overcome this problem in java? please help. A: But the problem is in the database instead of \n a new line is getting stored. Well it sounds like the string itself probably contains a newline. If you write: String x = "a\nb"; in Java, then that is a string with 3 characters: 'a' newline 'b' That should be stored as a string of 3 characters in the database. When you fetch it back, you'll faithfully get a string of 3 characters back. The database will simply store what you give it. Now if you're saying that you're trying to store a string which actually contains a backslash followed by an n, and that is being converted to a newline somewhere, then you'll need to post some code to show what you're doing. For example, I could imagine that might happen if you're including the value directly in your SQL statement instead of using parameterized SQL. (Always use parameterized SQL.) So basically, either it's actually not a problem at all, or you should post some code. EDIT: Now we've seen this: I had the same issue when i was storing such things using php i overcame that using mysqli_escape_real_string() It sounds like maybe you are just facing a problem of inappropriate inclusion of values in a SQL statement. If you're using something like: String sql = "INSERT INTO TABLE FOO VALUES ('" + text + "')"; Statement statement = connection.createStatement(); statement.executeUpdate(sql); then you need to stop doing that. You should use: String sql = "INSERT INTO TABLE FOO VALUES (?)"; PreparedStatement statement = connection.prepareStatement(sql); statement.setString(1, text); statement.execute(); (With appropriate code for closing the statement and connection, e.g. the try-with-resources statement in Java 7.) A: \n is a new line character. If you want to store such combination as text you have to escape \ so I guess that you have to store \\n for every \n occurence in targeted string. Escape character can be depandant to DBMS though.
[ "mathematica.stackexchange", "0000181457.txt" ]
Q: How to plot complex eigenvalues of a matrix? I have a matrix , for instance, like this : matrix[a_ ] := {{0, a}, {-a, 1}}; Eigenvalues[matrix[a]] and this give the eigenvalues that depends on a {1/2 (1 - Sqrt[1 - 4 a^2]), 1/2 (1 + Sqrt[1 - 4 a^2])} If I plot this eigenvalues, Plot[Eigenvalues[mat[a, b, q]], {a, -1 , 2}] this just give me the real value. I would like to have the real part of the complex number too. How can I get the real part of the complex eigenvalue? A: You can use ReIm or Re or Im: mat[a_] := {{0, a}, {-a, 1}}; Plot[Evaluate[ReIm @ Eigenvalues[mat[a]]], {a, -1, 2}, PlotLegends->"Expressions"]
[ "stackoverflow", "0017475112.txt" ]
Q: Why `x = x*(1.5f-(xhalf*x*x));` can be a Newton Method iteration? Ok, by far, I guess many people know the famous fast inverse square root (see more on Writing your own square root function and 0x5f3759df) Here is the code float FastInvSqrt(float x) { float xhalf = 0.5f * x; int i = *(int*)&x; // evil floating point bit level hacking i = 0x5f3759df - (i >> 1); // what the fuck? x = *(float*)&i; x = x*(1.5f-(xhalf*x*x)); // one Newton Method iteration return x; } Ok, i do NOT need to know more how magic 0x5f3759df is. What I don't understand is why x*(1.5f-(xhalf*x*x)) is a Newton Method iteration? I tried analyse but just can't get it. So let's assume r is the real number and x is the inverse sqrt of r. 1 / (x^2) = r, then f(x) = r*(x^2)-1 and f'(x) = 2 * r * x So one iteration should be x1 = x - f(x)/f'(x) = x / 2 + 1 / (2 * r * x), right? How comes x * (1.5 - ((r / 2) * x * x))? (note I replaced xhalf with r / 2 here) Edit Ok f(x) = x^2 - 1/r is another form, let me calculate f(x) = x^2 - 1 / r f'(x) = 2 * x So x1 = x - (f(x)/f'(x)) = x - (x^2 -(1 / r))/(2*x) = x / 2 + 1 / (2 * r * x), still it is quite different from the formula used in the code, right? A: Wikipedia says function is (using your variable names): f(x) = 1/x2 - r Then we have: f'(x) = -2/x3 And iteration is: x - f(x)/f'(x) = x - (1/x2 - r)/(-2 / x3) = x + x3 /2 * (1/x2 - r) = x + x/2 - r/2 * x3 = x * (1.5 - r/2 * x * x) And this is what you see in code. A: Newton's method is defined in terms of the iteration xi+1 = xi - f(xi) / f'(xi) (where f'(x) is the first derivative of f(x)). To find the inverse root of r, one needs to find the zero of the function f(x) = x - 1/sqrt(r) (or, equivalently, f(x) = x2 - 1/r). Simply take the derivative, plug it in to the definition of the iteration step, simplify, and you have your answer. Actually, the exact form used in the code comes from using a third equivalent form: f(x) = x-2 - r See this article for the detailed steps of the derivation. It's also derived in the Wikipedia article on fast inverse square root.
[ "stackoverflow", "0055665588.txt" ]
Q: syncronize two objects and apply new values What I want to achieve is basically this: R.mergeDeepRight( { age: 40, contact: { email: 'baa@example.com' }}, { name: 'fred', age: 10, contact: { email: 'moo@example.com' }} ); but without the { name: 'fred' } in the resulting object. Only keys in the first object should apply. A: I would make a reusable function combining mergeDeepRight, pick, and keys, like this: const funkyMerge = (o1, o2) => mergeDeepRight(o1, pick(keys(o1), o2)) console.log(funkyMerge( { age: 40, contact: { email: 'baa@example.com' }}, { name: 'fred', age: 10, contact: { email: 'moo@example.com' }} )) <script src="https://bundle.run/ramda@0.26.1"></script><script> const {mergeDeepRight, pick, keys} = ramda </script>
[ "stackoverflow", "0021621423.txt" ]
Q: How struts property tag works with date value? I have a JSP page where i am getting a Date value from my action class. I am not able to understand how it is handled as: <s:property value="#someDate"/> gives me date 2/7/14 whereas <s:property value="{#someDate}"/> gives me Date as [Wed Feb 7 00:00:00 IST 2014] Can someone tell me how date value is actually handled here, as date is returned in different formats? A: Nice Question. <s:property value="{#someDate}"/> is equal to <s:property value="someDate.toString()"/> or ${someDate} where as <s:property value="someDate"/> is using built in type conversion of xwork2 which uses the SHORT format for the Locale associated with the current request for dates. See Built in Type Conversion Support value="{#someDate}" means value="someDate.toString()" it converts date to date.tosting() that is why you are getting [Wed Feb 7 00:00:00 IST 2014] To handle date formats there is a special tag in struts2 <s:date name="someDate" format="dd/MM/yyyy" /> Prints 17/04/2014 Also see <s:date name="someDate" format="dd/MMM/yyyy" /> Prints 17/Apr/2014 Also there is attibute nice="true" <s:date name="someDate" nice="true" /> Prints 2 days ago
[ "stackoverflow", "0043903374.txt" ]
Q: Immutable.Js - Add new property in Map So let's say that I make a REST API call and receive a JSON in this format: { "plan": { "createdDate": "05/04/2017", "location": { "city": null "state": null } "family": null } } And within in my reducer, make the JSON as an immutable as so: Immutable.Map(Immutable.fromJS(action.json)) Along the way, is it possible to add properties under family? For instance, when I am submitting a form to a server, ideally I like to send something like this: { "plan": { "createdDate": "05/04/2017", "location": { "city": null "state": null } "family": { "father": "Homer", "mother": "Marge", "son": "Bartholomew" } } } Or do I have to initialized first to have those properties under family from the start? A: You can follow this way via mergeDeep of Immutable: const { fromJS } = require('immutable@4.0.0-rc.9') const initialState = fromJS({ "plan": { "createdDate": "05/04/2017", "location": { "city": null, "state": null }, "family": null } }) const newState = initialState.mergeDeep({ "plan": { "family": { "father": "Homer", "mother": "Marge", "son": "Bartholomew" } } }) console.log(newState.toJS()) You will got this result { "plan": { "createdDate": "05/04/2017", "location": { "city": null, "state": null }, "family": { "father": "Homer", "mother": "Marge", "son": "Bartholomew" } } } Hope this can help you for solving this same issue with me, I was succeed!
[ "stackoverflow", "0046822524.txt" ]
Q: change right position depending on class css I have a button that I want to use as a tab on a side bar to start I want it at right: 0; position: absolute; but then when it has the class btnactive I want it to be 320px from the right so right: 320px; position: absolute; should work but the button just goes missing off the page, kind of a simple question cant figure it out thanks a lot or if anyone knows another way.. I have a button that I want to the left of a sidebar that I toggle in and out thats 320px wide A: So after playing around for a while in the dev tools, floating right and then putting a margin-left 320px works perfectly so the code is like this .sidebar-closed{ float: right; } .sidebar-open{ margin-right: 320px; }
[ "askubuntu", "0000001962.txt" ]
Q: How can multiple private keys be used with ssh? I was able to setup ssh to use private/public key authentication. Now I am able to do ssh user@server1 And it logs on with the private key. Now I want to connect to another server and use a different key. How do set it up so ssh user@server1 uses privatekey1 ssh user@server2 and uses privatekey2 A: You can set this up in your ~/.ssh/config file. You would have something like this: Host server1 IdentityFile ~/.ssh/key_file1 Host server2 IdentityFile ~/.ssh/key_file2 man ssh_config is a reference A: There are a few options. Load both keys into your ssh agent using ssh-add. Then both keys will be available when connecting to both servers Create your $HOME/.ssh/config file and create a Host section for server1 and another for server2. In each Host section, add an IdentityFile option pointing to the appropriate private key file
[ "stackoverflow", "0058245349.txt" ]
Q: Continue running ProcessCmdKey even when forms application is not being focused on I have a ProcessCmdKey function in my script and I need it to run even when the application is not being focused on. I am also hiding the application and removing its icon from the taskbar because I want it to run in the background. It also starts up when the computer starts up. A: I ended up using keyboard hooks which were recommended to me by MickyD.
[ "stackoverflow", "0055598410.txt" ]
Q: Typescript declaration Merging, how to unmerge? I have the next Typescript declaration merging: import { Collection, Entity, IEntity, OneToMany, PrimaryKey, Property } from "mikro-orm"; import { ObjectId } from "mongodb"; import { LocationModel } from "./locationModel"; @Entity({ collection: "business" }) export class BusinessModel { @PrimaryKey() public _id!: ObjectId; @Property() public name!: string; @Property() public description!: string; @OneToMany({ entity: () => LocationModel, fk: "business" }) public locations: Collection<LocationModel> = new Collection(this); } export interface BusinessModel extends IEntity<string> { } Now, how can I unmerged them? To get a interface or data type equivalent to: export interface BusinessEntity { _id: ObjectId; name: string; description: string; locations: Collection<LocationModel>; } A: I don't have access to the types/decorators/modules you're using, so if any of the following yields errors you might consider editing the code in the question to be a Minimum, Complete and Verifiable example. You can try to tease apart the types via something like type BusinessEntity = Pick<BusinessModel, Exclude<keyof BusinessModel, keyof IEntity<string>>> but that will only work if IEntity's keys don't overlap with the ones you added to BusinessModel. A better idea would be to capture the type you care about before merging: @Entity({ collection: "business" }) export class BusinessEntity { @PrimaryKey() public _id!: ObjectId; @Property() public name!: string; @Property() public description!: string; @OneToMany({ entity: () => LocationModel, fk: "business" }) public locations: Collection<LocationModel> = new Collection(this); } export class BusinessModel extends BusinessEntity { } export interface BusinessModel extends IEntity<string> { } Hope that helps; good luck!
[ "math.meta.stackexchange", "0000023257.txt" ]
Q: Why are (most) spaces eliminated in \mathrm formatting? Why does this: $\mathrm{The quick, brown fox jumped over the lazy dog.}$ result in this: $\mathrm{The quick, brown fox jumped over the lazy dog.}$ Note that all spaces in my original text, save one, are missing. I have found that spaces are quite useful for separating the words in text. A: If you want to write text in math-mode then use \text{...} or variants thereof for example: $\text{This is some text with default font.}$ $\textrm{This is some text with specified font, which happens to coincide with the default.}$ $\textsf{This is some text in another font.}$ $\textbf{This is some text in bold.}$ $\text{This is some text with default font.}$ $\textrm{This is some text with specified font, which happens to coincide with the default.}$ $\textsf{This is some text in another font.}$ $\textbf{This is some text in bold.}$ The command \mathrm{...} is not for "text" but for letters in a particular font (namely roman) in math mode. Thus, as usual in math mode, space is ignored; if you want some you can specify it explicitly. $\mathrm{Text \ with \ space.\; Good.}$ $\mathrm{Text \ with \ space.\; Good.}$ Needless to say, this is not the way to include some phrase in a mathematical part. There are similar commands for other fonts such as: $\mathsf{Sans}$ $\mathbf{Bold}$ $\mathit{Italic}$ $\mathsf{Sans}$ $\mathbf{Bold}$ $\mathit{Italic}$
[ "scifi.stackexchange", "0000139724.txt" ]
Q: Why did the climate in World War Z go cold? I recently read World War Z, and one question nagged me throughout it- why did the Earth get colder during the Zombie apocalypse? The story suggested that most places were burning, which I thought would lead to a warmer planet, in many ways. A: TL;DR: Fires left to burn unchecked around the world, nuclear weapons detonating in Iran, Pakistan, and China, and oil fields set ablaze in Saudi Arabia, all combine to fill the upper atmosphere with enormous amounts of ash and other particulate matter. This veil of pollution reflects a significant amount of sunlight - i.e., thermal energy, aka heat - back into space before it can warm the earth. As a result, global temperatures decline significantly until the skies clear and things return to normal. Brooks isn't ignoring the science of climate change - he's applying lessons learned from actual observation, and sophisticated computer modeling. In the book: Mundane fires and their impact on the climate: Fire obviously didn't cease to exist when the zombies showed up. Early in the crisis, pitched battles, car crashes, people fleeing homes and businesses in panic, etc, would have led to a far higher number of fires than normal; shortly after everything went to hell, the lack of fire fighters, water pressure to sprinkler systems, etc, would allow these fires to spread unchecked. Throughout the rest of the war, people were forced to fall back on open flames for cooking and heating (and they were still shooting, burning, and blowing up zombies and lots of other stuff), so houses and other shelters were still going up in flames and taking other structures along with them. Many people - like the family that fled to northern Canada - tried to survive in the wilderness, far from population centers; this made accidental wildfires a problem as well. Altogether, the number of fires that grew out of control during the rest of the war would have been a bit lower than in the first stage, but still higher than usual. All that soot and ash goes up into the air, and before it comes back down, some of it reaches the upper atmosphere, where it lingers. While it is up there, it is reflecting sunlight - the planet's primary source of thermal energy (i.e., heat) - back into space before it can warm the surface. The ultimate result, of course, is that the skies grow darker, the temperature drops, winters grow longer and colder, and summers become shorter and cooler. Here's every mention I could find related to changes in the climate, and it's connection to the fires: It was not easy Living, however. These people, no matter what their pre-war occupation or status, were initially put to work as field hands, twelve to fourteen hours a day, growing vegetables in what had once been our state-run sugar plantations. At least the climate was on their side. The temperature was dropping, the skies were darkening. Mother Nature was kind to them. The guards, however, were not. "Be glad you're alive," they'd shout after each slap or kick. ... As with so many other conflicts, our greatest ally was General Winter. The biting cold, lengthened and strengthened by the planet's darkened skies, gave us the time we needed to prepare our homeland for liberation. ... Now he was a chimney sweep. Given that most homes in Seattle had lost their central heat and the winters were now longer and colder, he was seldom idle. "I help keep my neighbors warm," he said proudly. I know it sounds a little too Norman Rockwell, but I hear stories like that all the time. ... What do they say the average temperature's dropped, ten degrees, fifteen in some areas?6 Yeah, we had it real easy, up to our ass in gray snow, knowing that for every five Zacksicles you cracked there'd be at least as many up and at 'em at first thaw. 6. Figures on wartime weather patterns have yet to be officially determined. ... They say eleven million people died that winter, and that's just in North America. That doesn't count the other places: Greenland, Iceland, Scandinavia. I don't want to think about Siberia, all those refugees from southern China, the ones from Japan who'd never been outside a city, and all those poor people from India. That was the first Gray Winter, when the filth in the sky started changing the weather.They say that a part of that filth, I don't know how much, was ash from human remains. ... Even in winter, it's not like everything was safe and snuggly. I was in Army Group North. At first I thought we were golden, you know. Six months out of the year, I wouldn't have to see a live G, eight months actually, given what wartime weather was like. I thought, hey, once the temp drops, we're little more than garbage men: find 'em, Lobo 'em, mark 'em for burial once the ground begins to thaw, no problem. ... It's already starting, slowly but surely. Every day we get a few more registered accounts with American banks, a few more private businesses opening up, a few more points on the Dow. Kind of like the weather. [Now that the war is over] Every year the summer's a little longer, the skies a little bluer. Its getting better. Just wait and see. So abandoned cities, towns, and presumably some undeveloped areas were consumed by fire in the initial chaos, and as infrastructure was left to decay, other conflagrations broke out as well. The immediate result was large amounts of ash thrown into the atmosphere. Nuclear weapons and their impact on the climate: As noted in comments, and in ArgumentBargument's excellent answer, there was also a nuclear exchange between Iran and Pakistan, which would have added to the ash and smoke produced by the more mundane fires. On top of this, nuclear weapons were also used in China's civil war. Even more ash and particulate matter was thrust into the skies. Iran and Pakistan: We created a beast, a nuclear monster that neither side could tame... Tehran, Islamabad, Qom, Lahore, Bandar Abbas, Onnara, Emam Khomeyni, Faisalabad. No one knows how many died in the blasts or would die when the radiation clouds began to spread over our countries, over India, Southeast Asia, the Pacific, over America. ... We heard after reports of the "limited nuclear exchange" between Iran and Pakistan, and we marveled, morbidly, at how we had been so sure that either you, or the Russians, would be the ones to turn the key. There were no reports from China, no illegal or even official government broadcasts. China's civil war: And you decided to end the fighting. We were the only ones who could. Our land-based silos were overrun, our air force was grounded, our two other missile boats had been caught still tied to the piers, watting for orders like good sailors as the dead swarmed through their hatches. Commander Chen informed us that we were the only nuclear asset left in the rebellion's arsenal. Every second we delayed wasted a hundred more lives, a hundred more bullets that could be thrown against the undead. So you fired on your homeland, in order to save it. One last burden to shoulder. The captain must have noticed me shaking the moment before we launched. "My order," he declared, "my responsibility." The missile carried a single, massive, multi-megaton warhead. It was a prototype warhead, designed to penetrate the hardened surface of your NORAD facility in Cheyenne Mountain, Colorado. Ironically, the Politburo's bunker had been designed to emulate Cheyenne Mountain in almost every detail. As we prepared to get under way, Commander Chen informed us that Xilinhot had taken a direct hit. As we slid beneath the surface, we heard that the loyalist forces had surrendered and reunified with the rebels to fight the real enemy The suggestion is that the sudden increase in airborne particulate matter from the initial fires, and the nuclear detonations in Pakistan, Iran, and China, reflected so much sunlight back out into space that temperatures dropped temporarily around the world. All sources of airborne pollution taken as a whole: The cumulative effect of the particulate output of mundane fires and nuclear explosions is most clearly laid out in the following passage, from the account provided by an astronaut who spent much of the war stranded aboard the ISS: There were so many fires, and I don't just mean the buildings, or the forests, or even the oil rigs blazing out of control -bleeding Saudis actually went ahead and did it8 - I mean the campfires as well, what had to be at least a billion of them, tiny orange specks covering the Earth where electric lights had once been. Every day, every night, it seemed like the whole planet was burning. We couldn't even begin to calculate the ash count but we guesstimated it was equivalent to a low-grade nuclear exchange between the United States and former Soviet Union, and that's not including the actual nuclear exchange between Iran and Pakistan. We watched and recorded those as well, the flashes and fires that gave me eye spots for days. Nuclear autumn was already beginning to set in, the graybrown shroud thickening each day. It was like looking down on an alien planet, or on Earth during the last great mass extinction. Eventually conventional optics became useless in the shroud, leaving us with only thermal or radar sensors. Earth's natural face vanished behind a caricature of primary colors. 8 To this day, no one knows why the Saudi royal family ordered the ignition of their kingdom's oil fields. All of the quotes above are from World War Z: An Oral History of the Zombie Wars, by Max Brooks. In real life: This isn't such a strange idea. It has actually happened before - often as a result of massive volcanic activity, and occasionally as a consequence of meteors, asteroids, etc striking the planet. And we have ample evidence that a nuclear war - even a relatively limited, regional conflict - would have similar effects. Volcanoes: The eruption of Mount Tambora in 1815 caused such a significant drop in global temperatures that 1816 is now known as "The Year Without a Summer". Another example is the eruption of Krakatoa: In the year following the 1883 Krakatoa eruption, average Northern Hemisphere summer temperatures fell by as much as 1.2 °C (2.2 °F). Weather patterns continued to be chaotic for years, and temperatures did not return to normal until 1888. The record rainfall that hit Southern California during the “water year” from July 1883 to June 1884 – Los Angeles received 38.18 inches (969.8 mm) and San Diego 25.97 inches (659.6 mm) – has been attributed to the Krakatoa eruption. The Krakatoa eruption injected an unusually large amount of sulfur dioxide (SO2) gas high into the stratosphere, which was subsequently transported by high-level winds all over the planet. This led to a global increase in sulfuric acid (H2SO4) concentration in high-level cirrus clouds. The resulting increase in cloud reflectivity (or albedo) would reflect more incoming light from the sun than usual, and cool the entire planet until the suspended sulfur fell to the ground as acid precipitation. - Wikipedia Meteor impacts: It is also thought that large meteor impacts can cause similar - but much more dramatic - global cooling. A huge meteor collided with Earth 2.5 million years ago, causing a gigantic tsunami that swallowed everything in its path. But according to a new study, published in the Journal of Quaternary Science, the meteor impact may have had a much larger effect on the planet -- it may have ushered in the ice age. "The tsunami alone would have been devastating enough in the short term, but all that material shot so high into the atmosphere could have been enough to dim the sun and dramatically reduce surface temperatures," Goff said. "Earth was already in a gradual cooling phase, so this might have been enough to rapidly accelerate and accentuate the process and kick start the Ice Ages." - IFLS: How a Giant Meteor Caused the Ice Age And: The impact of a medium-sized asteroid would create a 9-mile-wide crater, clogging the atmosphere with large amounts of dust. If the asteroid struck somewhere outside an area like a desert with small amounts of vegetation, the impact would ignite multiple wildfires, sending soot into the protective ozone, says the Apex Tribune. The dust and soot that would fill the atmosphere would reduce the amount of sunlight to reach the surface by 20 percent for the first two years and lead to a drop in precipitation of about 50 percent. "This is due to the lost heating and the lost temperature, so we lose convection; we don't have as many [weather] fronts," Bardeen said. - Weather.com: Earth Could Experience a Mini Ice Age If Hit By a Medium-Size Asteroid, New Study Claims Nuclear war: Computer models suggest that even a relatively small-scale nuclear exchange (involving 100 bombs like the one dropped on Hiroshima) would indeed cause significant, if temporary, global cooling: Even a regional nuclear war could spark "unprecedented" global cooling and reduce rainfall for years, according to U.S. government computer models. Widespread famine and disease would likely follow, experts speculate. To see what climate effects... a regional nuclear conflict might have, scientists from NASA and other institutions modeled a war involving a hundred Hiroshima-level bombs, each packing the equivalent of 15,000 tons of TNT—just 0.03 percent of the world's current nuclear arsenal. The researchers predicted the resulting fires would kick up roughly five million metric tons of black carbon into the upper part of the troposphere, the lowest layer of the Earth's atmosphere. In NASA climate models, this carbon then absorbed solar heat and, like a hot-air balloon, quickly lofted even higher, where the soot would take much longer to clear from the sky. The global cooling caused by these high carbon clouds wouldn't be as catastrophic as a superpower-versus-superpower nuclear winter, but "the effects would still be regarded as leading to unprecedented climate change," research physical scientist Luke Oman said during a press briefing Friday at a meeting of the American Association for the Advancement of Science in Washington, D.C. Earth is currently in a long-term warming trend. After a regional nuclear war, though, average global temperatures would drop by 2.25 degrees F (1.25 degrees C) for two to three years afterward, the models suggest. At the extreme, the tropics, Europe, Asia, and Alaska would cool by 5.4 to 7.2 degrees F (3 to 4 degrees C), according to the models. Parts of the Arctic and Antarctic would actually warm a bit, due to shifted wind and ocean-circulation patterns, the researchers said. After ten years, average global temperatures would still be 0.9 degree F (0.5 degree C) lower than before the nuclear war, the models predict. - National Geographic: Small Nuclear War Could Reverse Global Warming for Years Conclusion: In life as in World War Z, if you suddenly dump enormous amounts of particulate matter into the upper atmosphere, it is likely to cause short-term global cooling, because the dust and ash in the skies reflects heat and light back into space, which prevents the sun from warming the planet. In short, the planet cooled because it was receiving less thermal energy from the sun. This is a different mechanism than global warming via greenhouse gases, because greenhouse gases hold on to heat, whereas the darkened skies from sudden, massive increases in atmospheric particulate matter prevent that heat from entering the atmosphere in the first place. Long term, after the skies clear and the climate recovers from the temporary chill, I imagine that temperatures would resume the increases we see in our own world, due to pre-war greenhouse gas emissions, but global warming would peak and begin to reverse far more quickly than our current projections suggest. This is because the global population has been drastically reduced - we don't know the exact death toll, but it is certainly in the billions of people. The post-war world appears to rely less on fossil fuels and international trade; industry and consumption are still recovering 12 years after the war ended; resources are more scarce than before the crisis. Simply put, with fewer people left on the planet, people aren't causing as much damage as they used to. Life is much simpler and more sustainable in the post-war world. There is less demand for energy production and consumer goods. Damage to industrial infrastructure means less production is possible. The economic downturn caused by the war means people aren't consuming as much of the things that cause greenhouse gas emissions. More centralized populations and less focus on convenience and leisure activities further reduce consumption. As a result, fewer factories are spewing smoke; fewer cars are on the roads; fewer airplanes are in the skies; fewer power plants are burning coal, gas, and oil; fewer buildings are being heated with fossil fuels; fewer cattle and other livestock are being raised and eaten; fewer forests are being logged; and so on. Our collective carbon footprint is a fraction of what it was before the war. A: Pakistan and Iran had engaged in what seems to be all-out nuclear war. I don't have my copy of the book to get supporting quotes, but I would assume that this resulted in a nuclear winter. While I'd recommend reading the Wikipedia article, the synopsis is that when there are a large number of fires (not even necessarily fires caused by nuclear bombs, and there were clearly a lot of non-nuclear fires), the smoke particles produced remain in the atmosphere long enough to reflect a significant amount of heat from the sun, causing hemisphere-wide if not global temperature drops.
[ "stackoverflow", "0011154112.txt" ]
Q: Copy into the system clipboard from local vim on mac It seems like versions of this question have been asked here before, but I haven't been able to glean from them the exact response to what I am looking for. Say I open up a .txt file via vim on my mac machine and I then want to copy a line from that file to be used in another .txt file or in a google search or in terminal during an ssh session. What would be the simplest way to do this? Thanks, EDIT Found a potential duplicate: Vim: copy selection to OS X clipboard. But I am open to improvements! :) A: i'm not sure wether it works for osx too but here on linux i use "+<yank>, there is also "*<yank> see also http://vim.wikia.com/wiki/Copy_an_Entire_Buffer_to_the_Clipboard
[ "stackoverflow", "0004280675.txt" ]
Q: How to make a call to a subclass's member from a base class reference in polymorphic hierarchy I am currently writing a program that models various types of numbers and manages them polymorphically in a Set object (already written and tested). My inheritance relationship is this: Multinumber (all virtual functions, virtual class) inherited by Pairs, Complex, Rational The subclasses all have mostly the same functions with different parameters. The problem that I am running into is in functions like this: Multinumber& Complex::operator=(const Multinumber &rhs) { imag=rhs.imag; real=rhs.real; return *this; } Because I am treating this polymorphically, my return types and parameters all have to be of type Multinumber, in order to override the base class's parameters. However, I am having a terrible time getting this to compile. I am getting a boatload of errors along the lines of: error: 'const class Multinumber' has no member named 'imag' which is true. Multinumber does not have an imag attribute or function. But how can I get the compiler to realize that the Multinumber& rhs will always be Complex, or to treat it as such? Thank you for your help. This is what my superclass looks like: class Multinumber { public: virtual Multinumber& operator+(Multinumber&); virtual Multinumber& operator=(Multinumber&); virtual bool operator==(Multinumber&); virtual string object2string(); virtual Multinumber& makeobject(double, double)=0; }; A: I think you'll have to cast. Try this: Multinumber& Complex::operator=(const Multinumber &rhs){ const Complex & _rhs = dynamic_cast<const Complex &>(rhs); imag=_rhs.imag; real=_rhs.real; return *this; }
[ "ru.stackoverflow", "0000616256.txt" ]
Q: Клонирование репозитория Есть репозиторий. Командой git clone клонировал на другой компьютер. В репозитории есть ветки(пока они в ПР), которые пока не смержены в ветку мастер. Я могу как-то получить доступ к веткам в склонированном репозитории, которые пока в ПР? A: да, конечно. Нужно только знать имя (или угадать его, посмотрев на вывод git branch -a). Просто делаем git checkout <имя ветки> и готово.
[ "stackoverflow", "0004032702.txt" ]
Q: Objective C- How to add digits in a number? How do I add the digits in a particular number for example if the number is 3234 the result should be 3+2+3+4 = 12? A: Something along the lines of this should do it: int val = 3234; int sum = 0; while (val != 0) { sum += (val % 10); val = val / 10; } // Now use sum. For continued adding until you get a single digit: int val = 3234; int sum = val; while (sum > 9) { val = sum; sum = 0; while (val != 0) { sum += (val % 10); val = val / 10; } } // Now use sum. Note that both of these are destructive to the original val value. If you want to preserve it, you should make a copy or do this in a function so the original is kept.
[ "stackoverflow", "0058606140.txt" ]
Q: How to make a existing column "unique" in PowerBI, so I can form a "one-to-many" relationsship? I have 40 tables. One table has 20 rows, and one of the columns have 1385 distinct values. I would like to use this in a relationship with another table. TableName(1385 rows) Column:Name:(1385 distinct values) But when I try to do this in Powerbi/Manage-Relations, it will only accept the option "Many-to-Many" relationship. It reports that none of the column are "Unique". Well, the data in the column is unique. So how can I configure this column to be unique so I can use it in a "One-to-Many" relationship"? Do I have to edit the DAX expression and put the "DISTINCT" keyword in the expression for that column? And How? Now I have: }, {"Columnname", Int64.Type}, { A: what you can try is to perform remove duplicates in that table(i know its already contains distinct values but you can give it a try)... and/or just load the data again.
[ "math.stackexchange", "0003597196.txt" ]
Q: Proving simple inequality with four variables Assume we have four variabes, $ 0 \leq \beta_1, \beta_2, \lambda_1, \lambda_2 \leq 1 $, and that $\beta_1 \geq \beta_2$ and $\lambda_1 \geq \lambda_2$. Then the following inequality holds: $$\beta_1 (\lambda_1 - \sqrt\lambda_1 \sqrt\lambda_2) + \beta_2 (\lambda_2 - \sqrt\lambda_1 \sqrt\lambda_2) \geq 0.$$ How can I prove this analytically? I know it's true from numerical simulation, but I can't figure out how to show it. A: $$\beta_1 (\lambda_1 - \sqrt\lambda_1 \sqrt\lambda_2) + \beta_2 (\lambda_2 - \sqrt\lambda_1 \sqrt\lambda_2) =(\beta_1\sqrt\lambda_1-\beta_2\sqrt\lambda_2)(\sqrt\lambda_1-\sqrt\lambda_2) \geq 0$$
[ "stackoverflow", "0020669504.txt" ]
Q: Which method gets called in the parent activity when the user clicks on Back in the child activity? I have 2 activities in my Android app: A and B. A is the parent of B, as defined in the Android manifest. When stepping through my app with the debugger I've found that when I click on Up in the child activity, B, the onCreate() method of A gets called. But where does control pass to when the user clicks on Back in activity B? Which method of its parent activity, A, gets called? I've read lots of stuff about navigation in Android, Back vs Up, etc., but I can't find an answer to this simple question. (I would like the Back button to behave like Up in my app but I can't get A's screen to update correctly when the user clicks on Back in B.) A: At least onResume() will be called when activity A becomes active again.
[ "stackoverflow", "0058681055.txt" ]
Q: Is it possible to get algorithm.eaSimple to return a logbook that includes all stats from run time? I want to be able to get all my statistics out of the logbook so I can use it for graphical representation. As it stands my logbook only contains the generation numbers and number of evaluations. The algorithm is calculating and outputting avg, std, min, and max, but they do not get returned so I cannot use them. Is there a way I can get these values out of my algorithm? I have tried looking at the documentation for creating records, but what is there either doesn't make sense to me, or pertain to my situation. def main(): pop = toolbox.population(n=300) hof = tools.HallOfFame(1) stats_fit = tools.Statistics(lambda ind: ind.fitness.values) stats_size = tools.Statistics(len) mstats = tools.MultiStatistics(fitness=stats_fit, size=stats_size) # my hope is that the values calculated by these functions show up in my logbook mstats.register("avg", numpy.mean) mstats.register("std", numpy.std) mstats.register("min", numpy.min) mstats.register("max", numpy.max) pop, log = algorithms.eaSimple(pop, toolbox, 0.5, 0.1, 200, stats=mstats, halloffame=hof, verbose=True) print(str(log[0])) # only outputs generations, number of evaluations my output from this looks like this (note I excluded the output from the algorithm that had to do with the tree's size as I didn't think it was necessary and cluttered the output, but it does output that data) gen nevals avg gen max min 0 300 1125.92 0 45318.7 83.1079 1 173 1031.65 1 33883.4 83.1079 2 163 779.317 2 1888.68 83.1079 3 149 901.061 3 33606.2 82.4655 4 165 686.407 4 33883.4 81.8855 5 177 962.785 5 33757 81.8855 6 184 1632.86 6 33885.7 81.8855 7 171 1509.72 7 33856.9 81.8855 8 182 984.048 8 33732.6 81.6701 9 177 1534.63 9 34009.9 81.3255 10 159 1277.39 10 33885.7 80.9722 {'gen': 0, 'nevals': 300} I expect that the final line should include everything else in the log EDIT: digging deeper I have found that this may be a bug. The documentation says that it is supposed to be logged when stats are included here https://deap.readthedocs.io/en/master/api/algo.html it reads "It returns the optimized population and a Logbook with the statistics of the evolution. The logbook will contain the generation number, the number of evaluations for each generation and the statistics if a Statistics is given as argument." I have included statistics but it doesn't seem to be working. A: When you use multiple statistics, you have to specify the chapter of the logbook you want to access. In your example, the statistics have two chapters: fitness and size. Therefore, the last line in your example should be print(log.chapters['fitness'][0]) print(log.chapters['size'][0]) which will output {'avg': 0.5061951303359752, 'std': 0.12547520913281693, 'min': 0.15187521062437034, 'max': 0.9576681760851814, 'gen': 0, 'nevals': 300} {'avg': 5.0, 'std': 0.0, 'min': 5, 'max': 5, 'gen': 0, 'nevals': 300}
[ "salesforce.stackexchange", "0000021356.txt" ]
Q: Access date time in milliseconds from nested soql query This SOQL statement SELECT name, (SELECT From__c, To__c FROM Trip__r) FROM Account limit 1 will return Smith [{"From__c":"2013-11-25T15:15:00.000+0000","To__c":"2013-11-27T15:15:00.000+0000"},{"From__c":"2013-11-27T20:58:00.000+0000","To__c":"2013-11-28T20:58:00.000+0000"}] I need to convert the time from Salesforce datetime onto the millisecond format. How do I achieve that? A: The DateTime comes back ISO8601 formatted. So depending on your language of choice it should be fairly simple to parse them and then reformat as required. E.g. .NET DateTime.Parse("2013-11-27T20:58:00.000+0000"); E.g. Apex DateTime d = (DateTime)JSON.deserialize('2013-11-27T20:58:00.000+0000', DateTime.class);