text
stringlengths
64
89.7k
meta
dict
Q: Field level Validation Rule => "OnSave"? I need an 8 characters length enforcing validator. I created a MaxLength=8 and combined it with a MinLength=8 validation rule. Then I enter "1234567890123' and it's saving, no question asked! It does work if I click the "REVIEW" tab then "Validation". At the very bottom of a long list of schema warnings for each and every field. Our users won't do that. I've been researching quite a bit already. One talk about "Quick Action Bar" that I don't see anywhere, and so on. I just need a simple, text field validation like exist in any html form. You enter data wrong, it displays a message and you can't save. Period. How do you do that? Thanks in advance! A: you missed to add Parameters on your validator Parameters are applied using a QueryString-like list like this: [parameter]=[value]&[parameter]=[value] The “Result” paremeter determines the default result value of a validation. Possible values are: Valid = Green, everything is fine Suggestion = Bright Orange, hmm, take a look at this Warning = Orange, you should do something about this Error = Red, this is an error you know CriticalError = Red, user is warned before saving FatalError = Red, user cannot save item before validator is cleared More informations you can find here. A: As well as using a rules engine based validator, there are also validation fields on the Field template that you can use: The Validation field takes a regex and the ValidationText field can be used for the warning text. Using the following regex: /^.{8,}$/ That makes sure that the content has a minimum length of 8 characters. Now when the content editor tries to save an item that fails that validation, the message will be shown and the user cannot save the item: This can be a simpler setup than rules based validation, although it is limited to what you can do with a single regex statement.
{ "pile_set_name": "StackExchange" }
Q: Android Wear: Is there any reason to use a Time object rather than a Calendar object? Here's what I know, if there's any errors, let me know. Example watch faces, like the analog watch face, in the SDK use a deprecated Time object for managing time. According to the documentation Time was deprecated in level 22 (Android 5.1). Now obviously it still has a lot of life, but in the interests of future proofing code I looked I looked at switching to the Calendar object. I believe both Time and Calendar are fancy wrappers for a long variable. I wrote this benchmark to test their speed. long timeStart = 0; long timeEndcalendarStart = 0; long timeDifference = 0; long calendarEnd = 0; long calendarDifference = 0; for (int index = 0; index < 30000; index++) { timeStart = System.currentTimeMillis(); Time testTime = new Time(); testTime.setToNow(); long mills = testTime.toMillis(false); float seconds = testTime.second; float minutes = testTime.minute; float hours = testTime.hour; timeEndcalendarStart = System.currentTimeMillis(); Calendar testCalendar = Calendar.getInstance(); long cmills = testCalendar.getTimeInMillis(); float cseconds = testCalendar.get(Calendar.SECOND); float cminutes = testCalendar.get(Calendar.MINUTE); float chours = testCalendar.get(Calendar.HOUR); calendarEnd = System.currentTimeMillis(); timeDifference += timeEndcalendarStart - timeStart; calendarDifference += calendarEnd - timeEndcalendarStart; } The benchmark results show Calendar as 2x faster running it on a Moto 360. Switching a test watch face to Calendar shows no memory being leaked in the debugger. So my question is two fold. Is there a problem with my benchmark, or is it indeed faster? If so, what is the advantage of Time, such that they used it in their examples? My hypothesis is that they just used it to make their examples more understandable. Time is a more intuitive name, but I'd like to know if there's a technical reason. A: When the samples were written, the Time class wasn't deprecated yet. We would use Calendar if we wrote them now. Use Calendar.
{ "pile_set_name": "StackExchange" }
Q: php array_intersect don't get the first value Basically, I'm trying to import csv data to my database. Before insert the data to database I want to check whether database has that column (from csv headers) or not. // read csv from file ex: data.csv $reader = \League\Csv\Reader::createFromPath($file); // get first row from csv as headers (email, first_name, last_name etc.) $headers = array_filter(array_map(function($value) { return strtolower(trim($value)); }, $reader->fetchOne())); // get fields from database (email, first_name, last_name, birthdate etc.) $fields = collect($this->fields)->map(function ($field) { return strtolower($field->tag); })->toArray(); // want to check which fields has csv $availableFields = array_intersect($headers, $fields); However when I run the code above, array_intersect not working properly. The output is: $headers : Array ([0] => email [1] => first_name [2] => last_name ) $fields : Array ( [0] => email [1] => first_name [2] => last_name [3] => telephone [4] => gender [5] => birthdate [6] => country ) $availableFields :Array ([1] => first_name [2] => last_name ) var_dump and result is: $headers : array(3) { [0]=> string(8) "email" [1]=> string(10) "first_name" [2]=> string(9) "last_name" } $fields : array(9) { [0]=> string(5) "email" [1]=> string(10) "first_name" [2]=> string(9) "last_name" [3]=> string(9) "telephone" [4]=> string(6) "gender" [5]=> string(9) "birthdate" [6]=> string(7) "country" } A: The trim() function in php cuts off only 6 non-printable characters per default. I think that's your problem because there are more non-printable characters (list of characters). For example: <?php var_dump([trim("EMAIL\x1C")]); trim() allows you to specify a characters mask in the second parameter: <?php trim($binary, "\x00..\x1F"); Instead of using trim(), a regular expression gives more quarantee: <?php // preg_replace('/[\x00-\x1F\x7F]/u', '', $value) $headers = array_filter(array_map(function($value) { return strtolower(preg_replace('/[\x00-\x1F\x7F]/u', '', $value)); }, $reader->fetchOne()));
{ "pile_set_name": "StackExchange" }
Q: Who is working with VS 2010 professional ? IS it stable as 2008? All I want to know is if .NET frameworks 2.0, 3.0 and 3.5 are available in VS 2010 Professional. I have installed VS 2010, but only .NET framework 4.0 is there when making a C# project. Does anyone else have the same problem ?? I am also working on my Final Year Project. I also would like to know if VS 2010 Professional is stable enough to do my project on image processing. Many of my friends are doing their projects on VS 2008. A: Yes. It is as stable. You can target 2.0, 3.5, 4.0 versions of the .NET framework. Project->Properties, Application Tab: Target Framework. (you might need to install version 2.0 and 3.5 of the .NET Framework. I can't tell for sure as these were already installed on my PC before installing VS2010). You can also run VS2008 and VS2010 side-by-side. A: You can target a different framework for your projects in its properties. I have just swritched to 2010 2 months ago and it is stable and the best IDE from MS so far. check out these goodies included in vs2010 Mitch brings a good point that you can run 2008 and 2010 side by side (thats what I have been doing)
{ "pile_set_name": "StackExchange" }
Q: Actual size of NSView Self I just started a brandnew project GrafLaboratory to do some experimenting on drawing in NSView. I added a custom view to the main window and configured it to adopt it´s size when the window changes it´s size. I modified my InitFrameWith to this: - (id)initWithFrame:(NSRect)frame { self = [super initWithFrame:frame]; if (self) { NSRect r = [self bounds]; } return self; } When I start my new app the first time and ask for [self bounds] I get the correct value: {{0, 50}, {600, 450}}. I then change the size of the window by dragging with the mouse. When restarting my app initWithFrame returns the same value: {{0, 50}, {600, 450}}. But I the new changed size. I already tried several things but without success. Any clues what I´m doing wrong? Thanks, Ronald A: The initWithFrame is only relevant when you initialize the object within a frame. If it's a custom UIView with custom drawing, then look at: - (void)drawRect:(NSRect)frame That will get called when setNeedsDisplay is called and/or the view is resized. With some custom views, one thing I've done in initWithFrame is to set the autoresize masks: // subviews autoresize [self setAutoresizesSubviews:YES]; // set resize masks (springs) [self setAutoresizingMask:(NSViewMaxXMargin | NSViewMinXMargin | NSViewMaxYMargin | NSViewMinYMargin | NSViewHeightSizable | NSViewWidthSizable)]; Then in both init and drawRect, I call my layoutViews metod if the rect has changed: - (void)drawRect:(NSRect)frame { ... // called on resize. on init, delegate isn't hooked up so we'll skip if (!NSEqualRects(_prevRect, [self bounds])) { [self layoutViews]; } // stash away rect for comparison so layout view code only happens when the rect changes _prevRect = [self bounds]; My layoutViews has custom layout logic. Hope that helps.
{ "pile_set_name": "StackExchange" }
Q: Improving on server configuration I am trying to improve the performance of a Drupal (6) installation under load. One web server, one db server (MySQL5) both are Single Socket Quad Core Intel Xeon 2.5GHz with 16GB RAM. On the web server, I am running APC to improve PHP's performance. Running a memcached server with 6 bins on the DB server. Using Apache Solr to power search, Solr lives on the DB server as well. The bottleneck appears to be Apache on the web server, as it runs out of memory under the load. No single process appears to be hogging too much of the available system resources. Any input would be greatly appreciated. If there are questions I can answer about the setup, please ask away. Thank you! A: Since we're talking PHP I assume you're using the Apache prefork MPM. Given Rasmus Lerdorf's attitudes on multithreading, you should continue to use Apache prefork or a similar non-threaded setup with another HTTP server (such as nginx). 4 quick wins come to mind. I can't say from OPs original question if this has already been done -- if not, these 4 improvements should bring a substantial improvement. a) Move static file serving (CSS, images, etc) away from your PHP Apache instances. With the Prefork MPM, when you're sending a single image to a user, a whole Apache child with the full PHP runtime is kept occupied to send that single image. This could be a 20-40 MB Apache process occupied for 0.1 to 3 seconds while the user downloads that image -- in the same time that Apache instance could have served tens or hundreds of dynamic pages. Suggestion: Set up a dedicated server for static resources, or use a cheap CDN like Amazon CloudFront. b) Turn off HTTP keepalives to the Apache instance that serves dynamic (Drupal) content. HTTP keepalive is great and has its uses, but again, with keepalives on & Apache prefork MPM a single end user browser will keep 'bloking' (i.e. occupying) an Apache child for lengthy periods. c) Verify that you're sending the proper HTTP headers, especially that static content such as images, CSS etc is cache-able. Otherwise the user's browser will re-downlod this static content on each page view, which is a total waste. Use Yahoo! YSlow, Mark Nottingham's RED or similar tools. d) Set up another web server, and just use plain DNS round robin to distribute load between the two web servers. I assume Drupal can keep session state stored on the MySQL database (most PHP apps can)? If so, then the session store is taken care of, and you can use DNS round robin. DNS round robin is not ideal. It does not handle a failure of a server, it doesn't guarantee perfect load distribution. But it's easy to set up, and usually works well enough for a simple setup with 2 or maybe 3 web-servers.
{ "pile_set_name": "StackExchange" }
Q: Jquery and SQL data table Learning Jquery here and I would like to show my SQL table on my webpage. I have the "shell" of my jquery that matches the SQL table and my web.config is setup correctly but my jquery doesnt load data. Where it says url: 'ConnectionString', I would like for it to point to my table or the web.config file. What can I do here. I need some guidance as this is something Im learning. Thanks <script type='text/javascript'> $(function () { $("#list").jqGrid({ url: 'Default.aspx', datatype: 'xml', mtype: 'GET', colNames: ['Inv No', 'Date', 'Amount', 'Tax', 'Total', 'Notes'], colModel: [ { name: 'ID', index: 'ID', width: 55 }, { name: 'Date', index: 'Date', width: 90 }, { name: 'amount', index: 'amount', width: 80, align: 'right' }, { name: 'tax', index: 'tax', width: 80, align: 'right' }, { name: 'total', index: 'total', width: 80, align: 'right' }, { name: 'note', index: 'note', width: 150, sortable: false } ], pager: '#pager', rowNum: 10, rowList: [10, 20, 30], sortname: 'invid', sortorder: 'desc', viewrecords: true, caption: 'Joshs first grid' }); }); </script> My Aspx part as follows <div class="ui-widget"> <table id="list"></table> <div id="pager"></div> </div> A: You seem to have a misunderstanding of how jQGrid works. It does not talk directly to your database at any point and it makes use of (optional) server-side libraries to format the response your server sends when the plugin requests data. Please take a look at http://www.trirand.net/demoaspnet.aspx for an example of using jQGrid with ASP.NET.
{ "pile_set_name": "StackExchange" }
Q: Getting An Error when trying to create a subcollection in Firestore I am trying to create a node in Google Firebase, and use its unique id to create a Document in Google Firestore of the same name. I'm using Google's PHP Firestore Client: https://github.com/GoogleCloudPlatform/google-cloud-php-firestore And I've read through their documentation: http://googlecloudplatform.github.io/google-cloud-php/#/docs/cloud-firestore/v0.5.1/firestore/writebatch Here is my code: <?php use \Google\Cloud\Firestore\FirestoreClient; use \Google\Cloud\Core\Timestamp; use \Google\Cloud\Firestore\Transaction as FirestoreTransaction; use \grptx\Firebase as FirebaseClient; class FirestoreTest { public function create() { $client = new FirebaseClient(); $database = $client->getDatabase(); $org = array( "acl" => array(), "people" => array() ); $ref = $database->getReference("/clients/")->push($org); $key = $ref->getKey(); $config = array( "projectId" => "xxx", "keyFile" => json_decode(file_get_contents("/xxx/firebase_auth.json"), true) ); $firestore = new FirestoreClient($config); $batch = $firestore->batch(); $collection = $firestore->collection("clients")->document("-LXXXXXX")->collection("trips"); } } And I get this error: Exception 'Google\Cloud\Core\Exception\BadRequestException' with message '{ "message": "Document name \"projects\/xxx-test\/databases\/(default)\/documents\/clients\/\" has invalid trailing \"\/\".", "code": 3, "status": "INVALID_ARGUMENT", "details": [] }' Any help is appreciated. A: This is the error that occurs if you try to get a collection as a document. It's kind of tricky because this can also happen if you try to get a document with the name of empty string in a collection. I don't know PHP, but I would guess that either in your $database->getReference("/clients/")->push($org); call, you were supposed to name a document to push your information to, or in your $firestore->collection("clients")->document("-LXXXXXX")->collection("trips"); call that the document you are trying to get ("-LXXXXXX") has the name empty string. (Of course, this is assuming your document isn't actually named "-LXXXXXX", and you are using that as a substitute for some variable that happens to be equal to ""). For instance, in python this call randomly failed me earlier: db.collection(u'data').document(current_id) with the same error: 'Document name ".../documents/data/" has invalid trailing "/". and will exit.' I scratched my head for a while but that's because the variable current_id is the empty string. Basically, internally Firebase converts it into a long pathname and then tries to get a document or a collection at that pathname depending on what your last call was. This causes an issue if you try to get a document that is named "".
{ "pile_set_name": "StackExchange" }
Q: Does NP = coNP imply the collapse of PH to level 1? It was already asked here whether NP=coNP implies P=NP. I'd like to approach that question from the perspective of the Polynomial-Time Hierarchy. Here is a theorem from Oded Goldreich's "Computational Complexity" (Proposition 3.10): For every $k \ge 1$, if $\Sigma_k = \Pi_k$ then $\Sigma_k = \Sigma_{k+1}$, which in turn implies $PH = \Sigma_k$. Now, since $\Sigma_1=NP$ and $\Pi_1 = coNP$, doesn't it imply that $PH = \Sigma_1$, which ultimately implies $P = NP$? A: No. $PH=NP$ doesn't imply $P=NP$, because $PH$ is not the same class as $P$. Roughly speaking, $PH$ includes $P$, $NP$, $coNP$, and more: $PH$ includes $\Sigma_i$ and $\Pi_i$ for all $i$. Formally, $PH$ is defined as $$PH = \Sigma_0 \cup \Pi_0 \cup \Sigma_1 \cup \Pi_1 \cup \Sigma_2 \cup \Pi_2 \cup \cdots.$$ If $NP=coNP$, then we have $\Sigma_1=\Pi_1$, and by Proposition 3.10, we have $\Sigma_1=\Sigma_2=\Sigma_3 =\cdots=NP$ and $\Pi_1=\Pi_2=\Pi_3=\cdots=coNP=NP$, so $$\begin{align*} PH &= \Sigma_0 \cup \Pi_0 \cup \Sigma_1 \cup \Pi_1 \cup \Sigma_2 \cup \Pi_2 \cup \cdots\\ &= P \cup P \cup NP \cup NP \cup NP \cup NP \cup \cdots\\ &= NP. \end{align*}$$
{ "pile_set_name": "StackExchange" }
Q: Error with malloc while creating memory for list of struct pointers For some reason, while trying to create an array of pointers of a struct called Node, I keep getting an error: Node ret[2] = (struct Node*)malloc(2*sizeof(Node)); error: invalid initializer Can someone please help me with that? A: Node ret[2] = (struct Node*)malloc(2*sizeof(Node)); should probably be: Node *ret = malloc(2 * sizeof(*ret)); That's because you need a pointer to the memory, not an array. With an array, it's initialisation, which would require a braced init list. Note that this only provides memory for the pointers, not the things they point at - they need to be allocated separately if you wish to use them. You'll probably notice two other changes as well: I've removed the cast on the malloc return value. This serves no purpose in C since the void* returned can be implicitly cast to other pointer types. In fact, there are situations where explicit casts can lead to subtle problems. I've used *ret as the variable to get the size rather than the type. This is just habit of mine so that, if I change the type to (for example) tNode, I only have to change it in one place on that line - yes, I'm basically lazy :-) Note that this is just a preference, doing it the original way has no adverse effect on the program itself, just developer maintenance.
{ "pile_set_name": "StackExchange" }
Q: seo url rewrite rule - make last parameter optional This works but always expects the last parameter - I need 'page' to be optional for pagination purposes. RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^([^/]*)/([^/]*)$ /catalogue.php?category=$1&page=$2 [L] I have tried this from a previous stack post but it gives me a 404 error A: You can use: # skip all files and directories from rewrite rules below RewriteCond %{REQUEST_FILENAME} -d [OR] RewriteCond %{REQUEST_FILENAME} -f RewriteRule ^ - [L] RewriteRule ^([^/]+)/?$ /catalogue.php?category=$1 [L] RewriteRule ^([^/]+)/([^/]+)/?$ /catalogue.php?category=$1&page=$2 [L] If it is Ok for you with empty page, and as you use the same page catalogue.php in both cases, you can use: RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^([^/]+)/?([^/]*)$ /catalogue.php?category=$1&page=$2 [L]
{ "pile_set_name": "StackExchange" }
Q: reactjs communicate between components via refs I have 3 components. One parent component and two child components (A,B). The first child component A has a button that triggers a parent components function. The parent has a switch either to display child component B or not. If the child component B shall be visible it becomes mounted. The function child A called from parent now executes a function in component B. I tried to realise it by providing a ref attribute on child component B. But as it is not mounted for a good reason on init this.refs is empty. How can I achieve this without mounting all possible child components B (or later C,D,E) initially. It is important that the onClick event in child A always triggers the referenced events. Here is a quick draft: Can anybody give me a hint to solve my logical problem? A: The following line: The function child A called from parent now executes a function in component B. is strange/ and a no-go area with react: A parent cannot (should not) directly call a function inside a child component. A parent can (should) pass a prop to the child, and then the child can initiate its own function. If I understand correctly, you want to execute the function inside child B to execute when a) component A is clicked AND b) component B is mounted You can achieve this as follows: add a state parameter inside parent, e.g. this.setState(childAClicked: true), most likely inside the callback function inside the parent, called by child A. pass this parameter to child B, e.g. <ChildB clickedA = {this.state.childAClicked} /> inside child B, add a componentDidMount() lifecycle method, which checks this.props.clickedA, and if true, executes your function inside child B if you want to execute the function also after updates to child B, add the same check inside a componentDidUpdate() lifecycle method If you want to execute the function ONLY inside one of the components B, C, D, based on some other parameter, you add this parameter as well to your parent's state, and pass it to other B,C and D components too.
{ "pile_set_name": "StackExchange" }
Q: Как программно свернуть приложение в Android? Здравствуйте! Изучаю Android, пишу код в AndroidStudio. Решил сделать приложение, которое умеет сворачиваться при нажатии на кнопку "Back", или как там ее) В сети ответа на такой банальный вопрос не нашел, тут этого тоже никто не спрашивал. Возможно ли программно свернуть приложение? Заранее благодарен за ответы) A: Не нужно придумывать "сворачивания" приложения. Нет такого. Как только Ваше приложение ушло на задний фон, система его может прибить в любой момент. Если нужно, чтобы по кнопке назад приложение "завершалось" - просто сделайте так, чтобы стек активити был пуст. Система сделает все за Вас сама.
{ "pile_set_name": "StackExchange" }
Q: Proteins: Post translational modification I am a physicist and trying to understand some protein chemistry for a small project. Basically, amino acids combine to form proteins and after forming the primary structure, some chemical modification may occur, such as phosphorylation or glycosylation (post translational modification). In case of the enzyme carbonic anhydrase a zinc ion is added post-translationally as a cofactor. (The amino acid sequence can be seen here (scroll down to 'sequence' title). Is the attachment of zinc regarded as a type of post-translational modification? When carbonic anhydrase is denatured, is the zinc ion released in the medium? Will the amino acid sequence (primary structure) be changed after denaturation? If yes, are amino acids removed after denaturation, if yes, which? I guess Zinc will be removed after denaturation. Is the remaining structure the primary protein structure? A: 1) Is the attachment of zinc regarded as a type of post-translational modification? It is not really considered a post-translational modification because the zinc atom is not covalently bound to the protein. Binding to zinc is adsorption. 2) When carbonic anhydrase is denatured, is the zinc ion released in the medium? Yes, but it depends on the extent of denaturation too. Metal ions can be removed using chelating ligands like EDTA, without actually denaturing the protein. 3) Will the amino acid sequence (primary structure) be changed after denaturation? If yes, are amino acids removed after denaturation, if yes, which? Denaturation does not include cleavage of covalent bonds. There won't be change in the amino acid sequence. 4) I guess Zinc will be removed after denaturation. Is the remaining structure the primary protein structure? Yes; just the polypeptide.
{ "pile_set_name": "StackExchange" }
Q: Using Code Contracts in unit tests Do you think it is advisable to use Code Contracts inside your unit tests? I don't think it is since it is like creating unit tests to test your unit tests. Therefore I would not activate the Code Contracts Static Checking nor the Runtime Checking for a Unit Test project. To clarify, I would like to know, in particular, if you would write Code Contracts code inside your unit tests. A: I think it's a good idea to enable Code Contracts for unit tests, then any contract failures can be caught when the tests are run. However it's usually not useful to do any contract checking in the test methods themselves, except in helper methods used by the test methods.
{ "pile_set_name": "StackExchange" }
Q: How to apply the Borel-Cantelli lemma to the Hausdorff distance between a uniform sample on $[0,1]$ and the aforementioned interval Let $n\in\mathbb Z^+$ and $X_1\ldots X_n$ i.i.d. $\operatorname{Unif}[0,1]$, that is, an independent sample from a uniform distribution on the interval $[0,1]$. I've spent way too much time trying to prove that, for any $\varepsilon\in\mathbb R^+$, $\operatorname{P}\{d_H(\chi_n,[0,1])>\varepsilon\;\text{ i. o.}\}=0.$ The LHS on the previous inequality refers to the Hausdorff distance between the sets $[0, 1]$ and $\chi_n:=\{X_i\}_{i=1}^n$. In addition, by i .o. I mean infinitely often, as usual. I've reduced this to the slightly simpler statement: $\displaystyle\operatorname{P}\left\lbrace\sup_{x\in[0,1]}\min_{i=1\ldots n}|X_i-x|>\varepsilon\;\text{ i. o.}\right\rbrace=0,$ which I also know to be true. So my main goal rn is proving this last claim, which is driving me crazy, although I do I know how to do it if I delete the supremum and use an arbitrary $x\in[0,1]$. I've tried lots of things, which I don't want to disclose for the moment, in order not to "corrupt" your minds. Anyway, if anybody can give me some (explicit) hints, I'd me most grateful, for it's almost sure that I'm not going to figure it out by myself. A: Well, in the end I came up with a rather convoluted way to solve the problem, which basically consists in adapting the proof of theorem 3 in http://sci-hub.cc/10.1239/aap/1086957575, in case anyone's interested. But I still feel that there must be some simple way to do it, probably in the same line of Nate Eldredge's hints.
{ "pile_set_name": "StackExchange" }
Q: Игнорирование символов строки Как в python вывести содержимое txt файла, игнорируя некоторые элементы(например первый и последний)?.Нужно именно не перезаписать, а лишь считать игнорируя определенные элементы. A: n= line[1:-1].rstrip() со 2 до предпаследнего строка начинается с 0 символа например 'hello word' [1:-1] = 'ell wor' [2:-3] = 'llo w' 1ый символ первой строки и последний символ последней строки s1 = 'hello word' s2 = 'hello word3' s3 = 'hello word4' s = s1+s2+s3 s[1:-1] = 'ello wordhello word3hello word' если это все в файле то: myfile=open("myfile.txt") n = '' for line in myfile: n += line.rstrip() print(n[1:-1])
{ "pile_set_name": "StackExchange" }
Q: How to specify a range of values in Excel? I have an excel report that has two columns 'Site Name' and 'Asset IP Address' in it. I have uploaded a sample report here. I need a report that shows me the range IP by site, like this: Assessment Site 1 192.0.2.134 – 192.0.2.201 Assessment Site 2 192.0.2.203 – 192.0.2.250 and so on I have tried using VLOOKUP and CountIF but I am unable to make this work. Any suggestions are most appreciated. Thanks in advance. A: If you want a purely formula-based solution then, assuming you put e.g. Assessment Site 1 in E2, this array formula** in F2: =INDEX($B$2:$B$33,MATCH(MIN(IF($A$2:$A$33=E2,0+SUBSTITUTE($B$2:$B$33,".",""))),IF($A$2:$A$33=E2,0+SUBSTITUTE($B$2:$B$33,".","")),0))&" - "&INDEX($B$2:$B$33,MATCH(MAX(IF($A$2:$A$33=E2,0+SUBSTITUTE($B$2:$B$33,".",""))),IF($A$2:$A$33=E2,0+SUBSTITUTE($B$2:$B$33,".","")),0)) Copying down will give similar results for Sites listed in E3, E4, etc. Regards **Array formulas are not entered in the same way as 'standard' formulas. Instead of pressing just ENTER, you first hold down CTRL and SHIFT, and only then press ENTER. If you've done it correctly, you'll notice Excel puts curly brackets {} around the formula (though do not attempt to manually insert these yourself).
{ "pile_set_name": "StackExchange" }
Q: Java Array index check I have an int array and I have assigned a value from it with a random index to a int variable. I wanted to know if there is a way to check the index from the array that it came from from the variable it was assigned. Random rand = new Random(); private int[] cards = {2, 3, 4, 5, 6, 7, 8, 9, 10}; int a = cards[rand.nextInt(8)]; so I assigned a value from the array to variable a but I want to know if there is a way to check the variable a to see what the index was it came from A: You can store the value of random before the use. int randomValue = rand.nextInt(8); int a = cards[randomValue];
{ "pile_set_name": "StackExchange" }
Q: Acceleration & the non-uniqueness of the unit normal vector to a curve at a point Knowing the equation of a curve in three-dimensional space in the following parametric form $$x=x(u), y=y(u), z=z(u),$$ we can determine the tangent vector $\hat{T}$ at a point $(x,y,z)$ using the formula $$\hat{T}(u)=\frac{\vec{r}^\prime(u)}{\sqrt{x^{\prime2}(u)+y^{\prime2}(u)+z^{\prime2}(u)}}.$$ Having obtained $\hat{T}(u)$, a fair task is to obtain a unit normal vector $\hat{N}(u)$ at that point. But the unit vector $\hat{N}(u)$ does not seem to be unique. The direction of $\hat{N}(u)$ can have any direction on the plane transverse to $\hat{T}(u)$. This troubles me! Let me say why. From kinematics, the instantaneous acceleration of a particle moving along a trajectory $\vec{r}(t)$ are respectively given by $$\vec{a}(t)=\dot{v}(t)\hat{T}(t)+\kappa v^2(t)\hat{N}(t)$$ which tells that acceleration will not be unique unless $\hat{N}(t)$ is uniquely determined. But how is this possible that the acceleration to a given trajectory is not unique? What am I missing? A: $\hat N(t)$ refers to the principal normal; the normal in the direction $\dfrac{d\hat T}{dt}$. More precisely, $$ \hat N(t)=\frac{\frac{d\hat T}{dt}}{\left\lVert\frac{d\hat T}{dt}\right\rVert} $$
{ "pile_set_name": "StackExchange" }
Q: Pass-through Query Ignores incorrect passwords after a successful connection I have script that creates a pass through query using a connection string and a password. It works on first connection attempt: fails until the user enters the correct password. If the connection string is lost or the user needs to renter it for any reason, it will succeed no matter what password is passed through the connection string. I've tried created named queryDefs and removing them, unique and non-unique. If this is the way it has to be, I'll work with it, but I don't like not understanding what's going on, so if anyone has any insight, that would be great. Thanks! Dim db As DAO.Database, qDef As QueryDef, rst As DAO.Recordset Set db = CurrentDb Set qDef = db.CreateQueryDef(vbNullString) With qDef .Connect = connStr .sql = sql .ReturnsRecords = True Set rst = .OpenRecordset(dbOpenSnapshot, dbSQLPassThrough) End With If readAll Then With rst If Not .EOF And Not .BOF Then .MoveLast .MoveFirst End If End With End If Set PassThroughRecordset = rst A: This is by design, connections with user/password are cached as long as Access runs, and server/db stay the same. See here and the linked blog post: Save password for ODBC connection to MS SQL server from MS Access 2007 How to avoid prompting for user id and password in MSAccess 2003
{ "pile_set_name": "StackExchange" }
Q: How to put multiple existing graphs in a same plot? This links explains how to plot multiple graphs in a same overall plot. Now I have three existing graphs, png1, png2, png3. I want a layout like below. How to achieve this? Thank you very much for the answer, please remember to install the packages: install.packages("png") library(png) install.packages("gridExtra") library(gridExtra) After using the gridExtra, I combined three graphs together. However, they had very low resolution. How can I make them at least the same resolution as the original ones? A: You would use the par or layout function. See the examples here: https://www.rdocumentation.org/packages/graphics/versions/3.5.0/topics/layout If you're interested in inserting image files into the plot, you'd use readPNG and rasterImage and/or the grid raster functions. Example: png1 = png::readPNG("png1.png") png2 = png::readPNG("png2.png") png3 = png::readPNG("png3.png") images = list(png1, png2, png3) grobs = lapply(images, grid::rasterGrob) gridExtra::grid.arrange(grobs=grobs)
{ "pile_set_name": "StackExchange" }
Q: Problem with CSS for mobile website I am building this mobile website. If you check it on your mobile browser it should fit in such that there is no horizontal scrolling. (Content should only be vertically stacked). Can someone help me in fixing the CSS of the page. Just let me know what the correct CSS should be so as to auto adjust for different mobile phones. CSS of this page can be found here. Basically, two main components I guess. (body and content). Also, I used this mobile website as a sample. Please refer to its inline CSS by viewing the source of that page. Thanks A: Okay, so it seems that your #content div is actually pushing the boundaries of the screen even on my large firefox browser. In your CSS you have it declared like so: #content{ width:100%; margin: 0; padding: 20px; background: white; -moz-border-radius: 10px; -webkit-border-radius: 10px; } I have confirmed by editing the CSS locally, that your padding is actually pushing the boundaries of the 100% width div, but the good news is that since it's a block level element it already fills all of the room available to it. Try get rid of the "width:100%;" and see if that works for you. It will still display exactly the same, but without those scroll bars. So something like this: #content{ padding: 20px; background: white; -moz-border-radius: 10px; -webkit-border-radius: 10px; }
{ "pile_set_name": "StackExchange" }
Q: Divide by 10 using bit shifts? Is it possible to divide an unsigned integer by 10 by using pure bit shifts, addition, subtraction and maybe multiply? Using a processor with very limited resources and slow divide. A: Editor's note: this is not actually what compilers do, and gives the wrong answer for large positive integers ending with 9, starting with div10(1073741829) = 107374183 not 107374182. It is exact for smaller inputs, though, which may be sufficient for some uses. Compilers (including MSVC) do use fixed-point multiplicative inverses for constant divisors, but they use a different magic constant and shift on the high-half result to get an exact result for all possible inputs, matching what the C abstract machine requires. See Granlund & Montgomery's paper on the algorithm. See Why does GCC use multiplication by a strange number in implementing integer division? for examples of the actual x86 asm gcc, clang, MSVC, ICC, and other modern compilers make. This is a fast approximation that's inexact for large inputs It's even faster than the exact division via multiply + right-shift that compilers use. You can use the high half of a multiply result for divisions by small integral constants. Assume a 32-bit machine (code can be adjusted accordingly): int32_t div10(int32_t dividend) { int64_t invDivisor = 0x1999999A; return (int32_t) ((invDivisor * dividend) >> 32); } What's going here is that we're multiplying by a close approximation of 1/10 * 2^32 and then removing the 2^32. This approach can be adapted to different divisors and different bit widths. This works great for the ia32 architecture, since its IMUL instruction will put the 64-bit product into edx:eax, and the edx value will be the wanted value. Viz (assuming dividend is passed in eax and quotient returned in eax) div10 proc mov edx,1999999Ah ; load 1/10 * 2^32 imul eax ; edx:eax = dividend / 10 * 2 ^32 mov eax,edx ; eax = dividend / 10 ret endp Even on a machine with a slow multiply instruction, this will be faster than a software or even hardware divide. A: Though the answers given so far match the actual question, they do not match the title. So here's a solution heavily inspired by Hacker's Delight that really uses only bit shifts. unsigned divu10(unsigned n) { unsigned q, r; q = (n >> 1) + (n >> 2); q = q + (q >> 4); q = q + (q >> 8); q = q + (q >> 16); q = q >> 3; r = n - (((q << 2) + q) << 1); return q + (r > 9); } I think that this is the best solution for architectures that lack a multiply instruction. A: Of course you can if you can live with some loss in precision. If you know the value range of your input values you can come up with a bit shift and a multiplication which is exact. Some examples how you can divide by 10, 60, ... like it is described in this blog to format time the fastest way possible. temp = (ms * 205) >> 11; // 205/2048 is nearly the same as /10
{ "pile_set_name": "StackExchange" }
Q: Google Music Gapless Playback I've purchased an album in which the songs are mixed together but there is a gap between songs when playing the album in Google Music. I've read that the Android app has support for gapless playback but can't find anything about the website. Does anyone know how to "enable" or fix gapless playback? A: There is no option to enable gapless playback in the web player. I contacted Google support about the matter and got this response: Their is no option for this on the web player, it should be automatic. The person responding proceeded to refer to it as: gape less playback so I don't know if he or she actually has any idea what I'm talking about, given the grammar errors. My experience is that it is indeed automatic, but does not work consistently.
{ "pile_set_name": "StackExchange" }
Q: ASP.NET 5 RC1 Identity Authentication method I can't find anywhere answer on question what is default authentication in ASP.NET 5 RC1, is it token based or cookie based. All i know is if i say app.UseIdentity() in my Startup.cs and i put [Authorize] attribute on my controllers, it is gonna work, but i can't figure out which method it uses. There are so many tutorials for token based authentication for ASP.NET 4.6 but things are different, i can't figure out how to apply that stuff in new ASP.NET 5. A: ASP.NET Identity 3 exclusively relies on cookie authentication (app.UseIdentity() is basically just a wrapper around app.UseCookieAuthentication()). There are already a few SO posts covering token authentication. Here's one: https://stackoverflow.com/a/35310717/542757
{ "pile_set_name": "StackExchange" }
Q: Graphic Design areas for the colour-blind? What areas, if any, of graphic design could a person with color blindness be active in? Can a person who has problems differentiating colours actually work in such a field? A: Ignore the results of a test based on poor scans of printed cards shown on a screen, and go to an optometrist for a proper test if you are concerned. I have some some colour differentiation issues. I worked as a graphic designer for quite a few years and I can't say it was ever an issue. But there's not going to be an absolute answer to this; there are many types and degrees of "colour-blindness". A: This is not an experts opinion, it's just based on my experience and thoughts. When I read your question, I instantly thought of a fantasy painter called Ciruelo ( http://www.dac-editions.com/ - http://en.wikipedia.org/wiki/Ciruelo_Cabral). He is color blind and he has been working on illustration and design for years: Ciruelo was born in Buenos Aires, Argentina, suffering from color blindness. That would not stop Ciruelo who at age 13 enrolled in Instituto Fernando Fader, an art school, where he began his formal studies. He started working as illustrator at age 18 for a graphic advertising company, and soon after began doing comic covers. I imagine he had to find an equilibrium between what he thought was aesthetically pleasing and what other people did, or maybe in his case it was closely related. It might even be that the fact that he was color blind was what made him so famous: his color combinations were not expected or were outside the comfort zone. You could start by doing some research on color blind artists and theory, and then maybe producing some work and show it to professionals and people in general (I'm sure everyone in here will be more than pleased to make a nice thread about it, and it could be very useful for other people) to see what they think. It could help you develop a "safe combinations" palette and reinforce what you already know. Now, about he area.. I work in digital design so I'm not sure about print. I feel websites and apps (and interface in general) has more artistic freedom, but it's up to you, really, if you are determined I think you could work in any area.
{ "pile_set_name": "StackExchange" }
Q: How long can tofu be kept in the fridge after it is opened? How long can tofu be kept in the fridge after its opened? Are there any ways to extend the shelf life of tofu, either before or after opening the package? Can tofu be frozen so that it keeps longer? Does firm or soft tofu last longer in the fridge? A: In my experience, tofu can be kept in the fridge (in it's original packaging) for at least a week, and probably up to two. Once it's been removed from the packaging any that's left over will need to be kept in a container and submerged in water. This should last about a week but probably not much longer. I freeze my tofu regularly. Sometimes I'll buy more than I need and keep one package in the fridge and the rest of it in the freezer. It should last as long as you need it to in the freezer, so long as you aren't intending to keep it for a year or more. Once it starts getting a bit slimy, it's time to throw it out.
{ "pile_set_name": "StackExchange" }
Q: Cordova camera allowEdit with larger targetWidth and targetHeight will crash the app With following code, after image cropping the app crashed, but if I change the targetWidth and height to 600, it works. Any idea? navigator.camera.getPicture($scope.processImageUri, $scope.onFail, { quality: 25, destinationType: Camera.DestinationType.FILE_URI, sourceType: Camera.PictureSourceType.CAMERA, allowEdit: true, encodingType: Camera.EncodingType.JPEG, targetWidth: 712, targetHeight: 712 }); A: I guess you are trying on Android ? If yes then below is the reason. Basically OS is trying to load the image into memory to apply the provided parameters and that causes the crash. I had read somewhere on SO that Android has this issue. Try without providing any parameters if they are not necessary.
{ "pile_set_name": "StackExchange" }
Q: Good Minkowski Theory and Commutative Algebra Books I am not so familiar with the theory of measures which Andre Weil uses to develope the Class Field Theory. However, I am interested in learning algebraic number theory and I recently found that the basic ideas of commutative algebra are not so familiar with me:). Besides, the fundamental notion of algebraic number theory in Neukirch's book Algebraic number theory is the Minkowski Theory which is quite unclear to me. Is there any book except for those of Bourbaki on the topic of commutative algebra and Minkowski theory such that it is friendly to beginners? Thank you very much. A: You might try Pierre Samuel, "Algebraic Number Theory", for a concise introduction with basic treatments of what you are asking about.
{ "pile_set_name": "StackExchange" }
Q: CRUD pattern for urls.py, passing object from URI to view Can the object value be looked up and passed to the generic view? Would the generic views need to be moved to views.py in order to support the object lookup? urls.py urlpatterns = patterns('myapp.views', url(r'^mymodel/create/$', view='mymodel_create', name='mymodel_create'), ) urlpatterns += patterns('django.views.generic', url(r'^(?P<model>\w+)/create/$','create_update.create_object', name='object_create'), url(r'^(?P<model>\w+)/(?P<id>\d+)/update/$', 'create_update.update_object', name='object_update' ), url(r'^(?P<model>\w+)/(?P<id>\d+)/delete/$', 'create_update.delete_object', name='object_delete'), url(r'^(?P<model>\w+)/(?P<object_id>\d+)/$', 'list_detail.object_detail', name='object_detail'), url(r'^(?P<model>\w+)/$','list_detail.object_list', name='object_list'),' ) Example URL's: http://localhost/myapp/thing/create http://localhost/myapp/thing/1 http://localhost/myapp/thing/1/update http://localhost/myapp/thing/1/delete I'd like to use (?P\w+) to find the corresponding Model, 'Thing', but when this code is executed, the following error occurs: object_list() got an unexpected keyword argument 'model' A: Yes, you can do this, and I've done it. The Django generic views don't support it directly. You need to wrap the generic view with your own view that looks up the model and constructs the queryset. Here's an example (showing only the detail view, you can do the others similarly). I've changed your named patterns in the URLconf to use "model" instead of "object", which is clearer naming: in urls.py: url(r'^(?P<model>\w+)/(?P<object_id>\d+)/$', 'my_app.views.my_object_detail', name='object_detail'), in my_app/views.py from django.views.generic.list_detail import object_detail from django.db.models.loading import get_model from django.http import Http404 def get_model_or_404(app, model): model = get_model(app, model) if model is None: raise Http404 return model def my_object_detail(request, model, object_id): model_class = get_model_or_404('my_app', model) queryset = model_class.objects.all() return object_detail(request, queryset, object_id=object_id) If you're clever and want to keep things as DRY as possible, you could create a single wrapper that accepts the generic view function to call as one of its arguments, rather than having a wrapper for create, a wrapper for update, etc.
{ "pile_set_name": "StackExchange" }
Q: How to prevent components from rendering in Flex Is there a way to prevent a component from rendering in Flex (to save memory or processing power)? I tried doing something like: <components:AddNewItemGroup id="addItemGroup" visible="false" enabled="false" horizontalCenter="0" bottom="0" /> I noticed that the component gets rendered but it's just not visible or functional. A: If you want to prevent a component from being rendered, you need to remove it from the display list using the removeChild method in Actionscript.
{ "pile_set_name": "StackExchange" }
Q: GPS data comparison after smoothing I'm trying to compare multiple algorithms that are used to smooth GPS data. I'm wondering what should be the standard way to compare the results to see which one provides better smoothing. I was thinking on a machine learning approach. To crate a car model based on a classifier and check on which tracks provides better behaviour. For the guys who have more experience on this stuff, is this a good approach? Are there other ways to do this? A: Generally, there is no universally valid way for comparing two datasets, since it completely depends on the applied/required quality criterion. For your appoach I was thinking on a machine learning approach. To crate a car model based on a classifier and check on which tracks provides better behaviour. this means that you will need to define your term "better behavior" mathematically. One possible quality criterion for your application is as follows (it consists of two parts that express opposing quality aspects): First part (deviation from raw data): Compute the RMSE (root mean squared error) between the smoothed data and the raw data. This gives you a measure for the deviation of your smoothed track from the given raw coordinates. This means, that the error (RMSE) increases, if you are smoothing more. And it decreases if you are smoothing less. Second part (track smoothness): Compute the mean absolute lateral acceleration that the car will experience along the track (second deviation). This will decrease if you are smoothing more, and it will increase if you are smoothing less. I.e., it behaves in contrary to the RMSE. Result evaluation: (1) Find a sequence of your data where you know that the underlying GPS track is a straight line or where the tracked object is not moving. Note, that for those tracks, the (lateral) acceleration is zero by definition(!). For these, compute RMSE and mean absolute lateral acceleration. The RMSE of appoaches that have (almost) zero acceleration results from measurement inaccuracies! (2) Plot the results in a coordinate system with the RMSE on the x axis and the mean acceleration on the y axis. (3) Pick all approaches that have an RMSE similar to what you found in step (1). (4) From those approaches, pick the one(s) with the smallest acceleration. Those give you the smoothest track with an error explained through measurement inaccuracies! (5) You're done :)
{ "pile_set_name": "StackExchange" }
Q: Gradle configuration to use maven local repository I have Maven and Gradle both installed in my system. By default maven stores the dependency jars in the USER_HOME/.m2/repository and Gradle stores in folder USER_HOME/.gradle/caches/modules-2 respectively. For the same project, I am end up with 2 copies of jars in my system ultimately. Is there any configuration to set up in the gradle at global level so that it uses existing maven repository instead of its own. Thanks in advance. A: You can use mavenLocal() If location of repository must be in other place you can use repositories { maven { url '/path/to/your/repository' } }
{ "pile_set_name": "StackExchange" }
Q: How to add a volume bar like YouTube for iOS? I am almost done with my game in Unity 5. However when the player presses Volume Up/Down, the iOS (version) shows the standard UI to show volume. Android has it's own (looks better on Stock). I want to make my game consistent on either platform and different variations of Android. So I want to recreate how YouTube (for iOS) handles the change in volume. I can't figure this out. Any help would be awesome!!! A: Unity has no functionality to take over physical volume button, especially on iOS. Correct me if I'm wrong.
{ "pile_set_name": "StackExchange" }
Q: JavaScript: Accept Division Function as Argument Into Another Function That Returns New Function --> Returns Quotient I have a function that divides two input arguments: const divide = (x, y) => { return x / y; }; I have a second function that takes the divide function as its input argument and returns a new function. function test(func) { return function(){ return func(); } } const retFunction = test(divide); retFunction(24, 3) I am expecting the returned value to be 8 (24 / 3). But I'm getting a returned output of 'NaN'. What am I doing wrong? A: You need to pass the possible arguments to the function: ...args: const divide = (x, y) => { return x / y; }; function test(func) { return function(...args) { return func(...args); } } const retFunction = test(divide); const result = retFunction(24, 3); console.log(result);
{ "pile_set_name": "StackExchange" }
Q: combine .eml files in a conversation view I have an export of .eml files which has your standard information like to, from, cc, as well as additional metadata fields like messageid, in-reply-to, references, etc. Based on how i understand the eml starndard, i believe I can make use of message-id, in-reply-to and references to create a converation view For example, you have the initial message to Bob MSG-1 message-id: 1 to: Bob text: hello Then Bob replies to Anthony, updating the metadata as follows MSG-2 message-id: 2 in-reply-to: 1 references: 1 to: Anthoy text: howdy Then Anthony replies back to bob, updating the metadata as follows MSG-3 message-id: 4 in-reply-to: 2 references: 1,2 to: Bob text: Let's do this! Is this how it works? A: Yep, that is correct. The only error is that you would not use a ',' between references in the References: header. If you are looking for an explanation of the algorithm used to "thread" these messages into a conversation-like view, you can read about it at https://www.jwz.org/doc/threading.html
{ "pile_set_name": "StackExchange" }
Q: Using mathtext parser to output a svg file Context I'm looking for a simple way to import properly typeset mathematics (with LaTeX) into blender. A solution for this has already been given. But that means getting out of blender, using multiple tools and then going back to blender and importing the whole thing. Blender comes with Python and can import svg I'd like to find an other way and blender has a set of powerful tools based on Python. I was thinking: can I make Python parse some TeX input and then generate a svg (virtual) file inside blender. That would solve the problem. matplotlib "emulates" TeX It is possible to install any Python library and use it inside blender. So this made me think of a possible "hack" of matplotlib. mathtext is a module that provides a parser for strings with TeX-like syntax for mathematical expressions. svg is one of the available "backends". Consider the following snippet. import matplotlib.mathtext as mathtext parser = mathtext.MathTextParser('svg') t = parser.parse(r'$\int_{0}^{t} x^2 dx = \frac{t^3}{3}$') t is a tuple that has all the information needed. But I can't find a way (in the backend api) to convert it to a (virtual) svg file. Any ideas? Thanks A: Matplotlib needs a figure (and currently also a canvas) to actually be able to render anything. So in order to produce an svg file whose only content is a text (a mathtext formula) you still need a figure and a canvas and the text needs to actually reside inside the figure, which can be achieved by fig.text(..). Then you can save the figure to svg via fig.savefig(..). Using the bbox_inches="tight" option ensures the figure to be clipped to the extent of the text. And setting the facecolor to a transparent color removes the figure's background patch. from matplotlib.backends.backend_agg import FigureCanvasAgg from matplotlib.figure import Figure fig = Figure(figsize=(5, 4), dpi=100) canvas = FigureCanvasAgg(fig) fig.text(.5, .5, r'$\int_{0}^{t} x^2 dx = \frac{t^3}{3}$', fontsize=40) fig.savefig("output.svg", bbox_inches="tight", facecolor=(1,1,1,0))
{ "pile_set_name": "StackExchange" }
Q: Tool to export result set from SQL to Insert statements? I would like to export a ad hoc Select query result sets from SQL Server to be exported directly as Insert Statements. I would love to see a Save As option "Insert.." along with the other current available options (csv, txt) when you right-click in SSMS. I am not exporting from an existing physical table and I have no permissions to create new tables so the options to script physical tables are not an option for me. I have to script either from temporary tables or from the result set in the query window. Right now I can export to csv and then import that file into another table but that's time consuming for repetitive work. The tool has to create proper Inserts and understand the data types when it creates values for NULL values. A: Personally, I would just write a select against the table and generate the inserts myself. Piece of cake. For example: SELECT 'insert into [pubs].[dbo].[authors]( [au_id], [au_lname], [au_fname], [phone], [address], [city], [state], [zip], [contract]) values( ''' + [au_id] + ''', ''' + [au_lname] + ''', ''' + [au_fname] + ''', ''' + [phone] + ''', ''' + [address] + ''', ''' + [city] + ''', ''' + [state] + ''', ''' + [zip] + ''', ' + cast([contract] as nvarchar) + ');' FROM [pubs].[dbo].[authors] will produce insert into [pubs].[dbo].[authors]( [au_id], [au_lname], [au_fname], [phone], [address], [city], [state], [zip], [contract]) values( '172-32-1176', 'White', 'Johnson', '408 496-7223', '10932 Bigge Rd.', 'Menlo Park', 'CA', '94025', 1); insert into [pubs].[dbo].[authors]( [au_id], [au_lname], [au_fname], [phone], [address], [city], [state], [zip], [contract]) values( '213-46-8915', 'Green', 'Marjorie', '415 986-7020', '309 63rd St. #411', 'Oakland', 'CA', '94618', 1); ... etc ... A couple pitfalls: Don't forget to wrap your single quotes This assumes a clean database and is not SQL Injection safe. A: take a look at the SSMS Tools Pack add in for SSMS which allows you to do just what you need. A: ATTENTION!!! AS IS. At the start of script you can see example how to use procedure. Of course you can make INSERT expresion if you need or add DataTypes for your required conversion. The script's result is concated SELECT expresions with UNION ALL. Be careful with collation of your data base. I didn't test other collation more than I need. For long lenght fields I recomend use [Save Result As..] in Result grid instead Copy. Bacause you may get cutted script. /* USE AdventureWorks2012 GO IF OBJECT_ID('tempdb..#PersonTbl') IS NOT NULL DROP TABLE #PersonTbl; GO SELECT TOP (100) BusinessEntityID , PersonType , NameStyle , Title , FirstName , MiddleName , LastName , Suffix , EmailPromotion , CONVERT(NVARCHAR(MAX), AdditionalContactInfo) AS [AdditionalContactInfo] , CONVERT(NVARCHAR(MAX), Demographics) AS [Demographics] , rowguid , ModifiedDate INTO #PersonTbl FROM Person.Person EXEC dbo.p_GetTableAsSqlText @table_name = N'#PersonTbl' EXEC dbo.p_GetTableAsSqlText @table_name = N'Person' , @table_owner = N'Person' */ /*********************************************************************************************/ IF OBJECT_ID('dbo.p_GetTableAsSqlText', 'P') IS NOT NULL DROP PROCEDURE dbo.p_GetTableAsSqlText GO CREATE PROCEDURE [dbo].[p_GetTableAsSqlText] @table_name NVARCHAR(384) /*= 'Person'|'#Person'*/ , @database_name NVARCHAR(384) = NULL /*= 'AdventureWorks2012'*/ , @table_owner NVARCHAR(384) = NULL /*= 'Person'|'dbo'*/ /*WITH ENCRYPTION, RECOMPILE, EXECUTE AS CALLER|SELF|OWNER| 'user_name'*/ AS /*OLEKSANDR PAVLENKO p_GetTableAsSqlText ver.2016.10.11.1*/ DECLARE @isTemporaryTable BIT = 0 /*[DATABASE NAME]*/ IF (PATINDEX('#%', @table_name) <> 0) BEGIN SELECT @database_name = DB_NAME(2) /*2 - 'tempdb'*/ , @isTemporaryTable = 1 END ELSE SET @database_name = COALESCE(@database_name, DB_NAME()) /*END [DATABASE NAME]*/ /*[SCHEMA]*/ SET @table_owner = COALESCE(@table_owner, SCHEMA_NAME()) DECLARE @database_nameQuoted NVARCHAR(384) = QUOTENAME(@database_name, '') DECLARE @table_ownerQuoted NVARCHAR(384) = QUOTENAME(@table_owner, '') DECLARE @table_nameQuoted NVARCHAR(384) = QUOTENAME(@table_name, '') DECLARE @full_table_name NVARCHAR(769) /*384 + 1 + 384*/ DECLARE @table_id INT SET @full_table_name = CONCAT(@database_nameQuoted, '.', @table_ownerQuoted, '.', @table_nameQuoted) SET @table_id = OBJECT_ID(@full_table_name) CREATE TABLE #ColumnTbl ( ColumnId INT , ColName sysname COLLATE DATABASE_DEFAULT , TypeId TINYINT , TypeName sysname COLLATE DATABASE_DEFAULT , TypeMaxLength INT ) DECLARE @dynSql NVARCHAR(MAX) = CONCAT(' INSERT INTO #ColumnTbl SELECT ISC.ORDINAL_POSITION AS [ColumnId] , ISC.COLUMN_NAME AS [ColName] , T.system_type_id AS [TypeId] , ISC.DATA_TYPE AS [TypeName] , ISC.CHARACTER_MAXIMUM_LENGTH AS [TypeMaxLength] FROM ', @database_name, '.INFORMATION_SCHEMA.COLUMNS AS [ISC] INNER JOIN ', @database_name, '.sys.objects AS [O] ON ISC.TABLE_NAME = O.name INNER JOIN ', @database_name, '.sys.types AS [T] ON ISC.DATA_TYPE = T.name WHERE ISC.TABLE_CATALOG = "', @database_name, '" AND ISC.TABLE_SCHEMA = "', @table_owner, '" AND O.object_id = ', @table_id) IF (@isTemporaryTable = 0) SET @dynSql = CONCAT(@dynSql, ' AND ISC.TABLE_NAME = "', @table_name, '" ') ELSE SET @dynSql = CONCAT(@dynSql, ' AND ISC.TABLE_NAME LIKE "', @table_name, '%" ') SET @dynSql = REPLACE(@dynSql, '"', '''') EXEC(@dynSql) DECLARE @columnNamesSeparated NVARCHAR(MAX) = SUBSTRING((SELECT ', [' + C.ColName + ']' AS [text()] FROM #ColumnTbl AS [C] ORDER BY C.ColumnId FOR XML PATH('') ), 2, 4000) --SELECT @columnNamesSeparated DECLARE @columnNamesSeparatedWithTypes NVARCHAR(MAX) = SUBSTRING((SELECT '+", " + "CONVERT(' + (CASE C.TypeId WHEN 231 /*NVARCHAR*/ THEN CONCAT(C.TypeName, '(', (CASE WHEN C.TypeMaxLength = -1 THEN 'MAX' ELSE CONVERT(NVARCHAR(MAX), C.TypeMaxLength) END), ')') WHEN 239 /*NCHAR*/ THEN CONCAT(C.TypeName, '(', C.TypeMaxLength, ')') /*WHEN -1 /*XML*/ THEN '(MAX)'*/ ELSE C.TypeName END) + ', "+ COALESCE(' + (CASE C.TypeId WHEN 56 /*INT*/ THEN 'CONVERT(NVARCHAR(MAX), [' + C.ColName + '])' WHEN 40 /*DATE*/ THEN 'N"""" + CONVERT(NVARCHAR(MAX), [' + C.ColName + '], 101) + """"' WHEN 60 /*MONEY*/ THEN 'CONVERT(NVARCHAR(MAX), [' + C.ColName + '])' WHEN 61 /*DATETIME*/ THEN '"""" + CONVERT(NVARCHAR(MAX), [' + C.ColName + '], 21) + """"' WHEN 104 /*BIT*/ THEN 'CONVERT(NVARCHAR(MAX), [' + C.ColName + '])' WHEN 106 /*DECIMAL*/ THEN 'CONVERT(NVARCHAR(MAX), [' + C.ColName + '])' WHEN 127 /*BIGINT*/ THEN 'CONVERT(NVARCHAR(MAX), [' + C.ColName + '])' WHEN 189 /*TIMESTAMP*/ THEN 'N"""" + CONVERT(NVARCHAR(MAX), SUBSTRING([' + C.ColName + '], 1, 8000), 1) + """"' WHEN 241 /*XML*/ THEN '"""" + CONVERT(NVARCHAR(MAX), [' + C.ColName + ']) + """"' ELSE 'N"""" + CONVERT(NVARCHAR(MAX), REPLACE([' + C.ColName + '], """", """""")) + """"' END) + ' , "NULL") + ") AS [' + C.ColName + ']"' + CHAR(10) COLLATE DATABASE_DEFAULT AS [text()] FROM #ColumnTbl AS [C] ORDER BY C.ColumnId FOR XML PATH('') ), 9, 100000) /*SELECT @columnNamesSeparated, @full_table_name*/ DECLARE @dynSqlText NVARCHAR(MAX) = CONCAT(N' SELECT (CASE WHEN ROW_NUMBER() OVER (ORDER BY (SELECT 1 )) = 1 THEN " /*INSERT INTO ', @full_table_name, ' (', @columnNamesSeparated, ' )*/', ' SELECT T.* /*INTO #ResultTbl*/ FROM ( " ELSE "UNION ALL " END) + "SELECT "+ ', @columnNamesSeparatedWithTypes, ' FROM ', @full_table_name) SET @dynSqlText = CONCAT(@dynSqlText, ' UNION ALL SELECT ") AS [T] /*SELECT * FROM #ResultTbl*/ "') SET @dynSqlText = REPLACE(@dynSqlText, '"', '''') --SELECT @dynSqlText AS [XML_F52E2B61-18A1-11d1-B105-00805F49916B] EXEC(@dynSqlText) IF OBJECT_ID('tempdb..#ColumnTbl') IS NOT NULL DROP TABLE #ColumnTbl; GO
{ "pile_set_name": "StackExchange" }
Q: Friendly URL with Apache Mod-Rewrite Been reading about this for a while now and I'm close but struggling with the final hurdle. I have a url like this: site.com/detail/123/some-description/maybe-some-more-description that I want to become site.com/details.php?id=123 I've got this so far RewriteRule detail/(.*)/.*$ details.php?id=$1 which according to this (https://htaccess.madewithlove.be/) results in details.php?id=123/some-text how do I get rid of the some-text on the end? A: Try this: The regex: (.*?detail)\/(\d+)\/.* The replacement: $1.php?id=$2 Which results in site.com/detail.php?id=123. They both can be tested at Regex101. (.*?detail) matches the site base URL with details and captures to the group $1. \/ matches the slash itself (must be escaped). (\d+) matches the number and captures it to the group $2. \/.* matches the rest of the URL and it helps to not include it in the replacement. Edit: Do you mind the difference between detail and details?
{ "pile_set_name": "StackExchange" }
Q: Диаграмма в Андроид Есть ли какие-то средства у Андроида для построение диаграмм? Может библиотеки с подробным описанием? A: Вот наверное самая популярная библиотека MPAndroidChart
{ "pile_set_name": "StackExchange" }
Q: Can I use Cursor Adapter with a GridView in a RecyclerView I am building a picture app with a link to descriptions. Would a GridView RecyclerView with a Cursor adapter be a suitable way to do this as using the Movie database as a source for the movie thumbnails and description data. A: please find cursor adapter implementation in below link I also put code below link , it may help you. Recycler view with cursor adapter First of all CursorAdapter is not designed for use with a RecyclerView. You are trying to hack something in there that would never work right. You can't just call it's methods and expect it to function correctly. See the source. So first things first. We want to use a cursor.. lets separate off this responsibility and create the RecyclerViewCursorAdapter. It's what it says, a CursorAdapter, for a RecyclerView. The details of this are pretty much the same how CursorAdapter works. See its source to see what is the same and what is not. Next, we now have your original class RVAdapter to implement the abstract RecyclerViewCursorAdapter which requires us to implement onCreateViewHolder and our new onBindViewHolder which gives us a Cursor parameter to bind against. The details of these views are the same as your original just tidied up a little. RVAdapter.java import android.content.Context; import android.database.Cursor; import android.net.Uri; import android.support.v7.widget.CardView; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import com.squareup.picasso.Picasso; import java.util.Random; public class RVAdapter extends RecyclerViewCursorAdapter<RVAdapter.ProductViewHolder> { private static final String TAG = RVAdapter.class.getSimpleName(); private final Context mContext; private final Random mRandom; public RVAdapter(Context context, String locationSetting) { super(null); mContext = context; mRandom = new Random(System.currentTimeMillis()); // Sort order: Ascending, by date. String sortOrder = ProductContract.ProductEntry.COLUMN_DATE + " ASC"; Uri productForLocationUri = ProductContract.ProductEntry .buildProductLocationWithStartDate(locationSetting, System.currentTimeMillis()); // Students: Uncomment the next lines to display what what you stored in the bulkInsert Cursor cursor = mContext.getContentResolver() .query(productForLocationUri, null, null, null, sortOrder); swapCursor(cursor); } @Override public ProductViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View view = LayoutInflater.from(parent.getContext()) .inflate(R.layout.item, parent, false); return new ProductViewHolder(view); } @Override protected void onBindViewHolder(ProductViewHolder holder, Cursor cursor) { String imagePath = cursor.getString(ShopFragment.COL_PRODUCT_IMAGE); String price = cursor.getString(ShopFragment.COL_PRODUCT_PRICE); holder.productPrice.setText("US $" + price); int height = mRandom.nextInt(50) + 500; //Download image using picasso library Picasso.with(mContext) .load(imagePath) .resize(500, height) .error(R.drawable.placeholder) .placeholder(R.drawable.placeholder) .into(holder.productPhoto); } public static class ProductViewHolder extends RecyclerView.ViewHolder { CardView cv; TextView productPrice; ImageView productPhoto; ProductViewHolder(View itemView) { super(itemView); cv = (CardView) itemView.findViewById(R.id.cv); productPrice = (TextView) itemView.findViewById(R.id.product_price); productPhoto = (ImageView) itemView.findViewById(R.id.product_photo); } } } RecyclerViewCursorAdapter.java import android.database.Cursor; import android.database.DataSetObserver; import android.support.v7.widget.RecyclerView; import android.view.ViewGroup; /** * RecyclerView CursorAdapter * <p> * Created by Simon on 28/02/2016. */ public abstract class RecyclerViewCursorAdapter<VH extends RecyclerView.ViewHolder> extends RecyclerView.Adapter<VH> { private Cursor mCursor; private boolean mDataValid; private int mRowIDColumn; public RecyclerViewCursorAdapter(Cursor cursor) { setHasStableIds(true); swapCursor(cursor); } public abstract VH onCreateViewHolder(ViewGroup parent, int viewType); protected abstract void onBindViewHolder(VH holder, Cursor cursor); @Override public void onBindViewHolder(VH holder, int position) { if(!mDataValid){ throw new IllegalStateException("this should only be called when the cursor is valid"); } if(!mCursor.moveToPosition(position)){ throw new IllegalStateException("couldn't move cursor to position " + position); } onBindViewHolder(holder, mCursor); } @Override public long getItemId(int position) { if(mDataValid && mCursor != null && mCursor.moveToPosition(position)){ return mCursor.getLong(mRowIDColumn); } return RecyclerView.NO_ID; } @Override public int getItemCount() { if(mDataValid && mCursor != null){ return mCursor.getCount(); } else{ return 0; } } protected Cursor getCursor() { return mCursor; } public void changeCursor(Cursor cursor) { Cursor old = swapCursor(cursor); if(old != null){ old.close(); } } public Cursor swapCursor(Cursor newCursor) { if(newCursor == mCursor){ return null; } Cursor oldCursor = mCursor; if(oldCursor != null){ if(mDataSetObserver != null){ oldCursor.unregisterDataSetObserver(mDataSetObserver); } } mCursor = newCursor; if(newCursor != null){ if(mDataSetObserver != null){ newCursor.registerDataSetObserver(mDataSetObserver); } mRowIDColumn = newCursor.getColumnIndexOrThrow("_id"); mDataValid = true; notifyDataSetChanged(); } else{ mRowIDColumn = -1; mDataValid = false; notifyDataSetChanged(); } return oldCursor; } private DataSetObserver mDataSetObserver = new DataSetObserver() { @Override public void onChanged() { mDataValid = true; notifyDataSetChanged(); } @Override public void onInvalidated() { mDataValid = false; notifyDataSetChanged(); } }; }
{ "pile_set_name": "StackExchange" }
Q: Size of bool in exported C function vs struct vs .Net marshaling I'm not sure if this is a problem, but certainly a curiosity. I have a C DLL that exports a function taking a 32-bit integer and a boolean (stdbool.h). The exported function (stdcall) indicates the parameter list is 8 bytes (4-byte int, 4-byte bool). This C DLL also contains a structure that uses booleans. Checking sizeof(bool) indicates 1-byte booleans. I have a .Net wrapper for this native DLL. When marshaling the structure, I specified for each boolean field UnmanagedType.U1 and all works well, everything is aligned correctly. I only used sequential layout, not explicit nor any offsets nor any packing. My question is, why the apparent disparity in boolean size? A: All function parameters in C that are smaller than "int" are converted to "int" size in the call. This is because each parameter is placed on the stack separately (in most architectures), so they are converted to stack cell size which is usually equal to size of "int". As for structure - nothing is converted. Though we should not forget about alignment in structures. But this is another story.
{ "pile_set_name": "StackExchange" }
Q: Disable form or block cache for anonymous users? I have two forms in Drupal 8 that I am prepopulating values with if a value exists in the query string. $keywords = Xss::filter($this->requestStack->getCurrentRequest()->get('keywords')); $form['keywords'] = [ '#type' => 'textfield', '#maxlength' => 128, '#size' => 64, '#default_value' => Unicode::strlen($keywords) ? $keywords : '', '#prefix' => '<div class="search-box__input js-search-input">', '#suffix' => '</div>', '#required' => TRUE, '#attributes' => [ 'placeholder' => Unicode::strlen($keywords) ? $keywords : t('Search Site'), ] ]; Works great for authenticated users, but for anonymous users, they are always seeing the last term entered, despite the query string having nothing in the URL. Even if I close the browser and come back, the term is still in the input field. I assume it gets cached. The form is being attached as a twig variable to a block containing other content: /** * Implements hook_preprocess_block(). * @param $variables */ function mytheme_preprocess_block(&$variables) { if (isset($variables['elements']['content']['#block_content'])) { $variables['block_content'] = $variables['elements']['content']['#block_content']; } // inject main nav search form to block template for main_nav only if ($variables['elements']['#id'] == 'main_nav') { $variables['main_nav_search_form'] = \Drupal::formBuilder()->getForm('\Drupal\mymodule_search_forms\Form\MainNavSearchForm'); } } Is there a way to change this so that does not happen? Any cache tag I could use? A: What you need need to do, is not to use a cache tag but a cache context. In your specific scenario you want to use url.query_args:keywords. In code that would look like this $form['keywords'] = [ '#cache' => ['contexts' => ['url.query_args:keywords']], ... ]; For reference. Cache tags are used to invalidate cache. Like if a cache element is tagged with node:1 and node with nid 1 is updated, then all cache containing node:1 cache tag is invalidated (other tags are also invalidated). Cache contexts are used if cached element exists in multiple variations based on something like the query arg. What happens is that multiple cache entries are created and they will all be invalidated based on the same logic (cache tags).
{ "pile_set_name": "StackExchange" }
Q: Powershell: How do I query pwdLastSet and have it make sense? I need to get the last password change for a group of account in an Active Directory security group, and I feel like this is something PowerShell should be good at. Right now, I'm already stuck at how to read the pwdLastSet attribute from the AD account I'm looking at. Even running something simple like this: [adsi] "LDAP://cn=user1,ou=Staff,ou=User Accounts,dc=ramalamadingdong,dc=net" | Format-List * gives results for pwdLastSet that appear like this: pwdLastSet : {System.__ComObject} I feel like I'm go about this the wrong way, so what's the best way to query and then format the output (the value is based on the Windows Epoch and not very human readable) of the pwdLastSet attribute? A: The inbuilt AD commandlets that come with Windows 7/Windows Server 2008 R2 can now do this simply enough. On Windows 7 from a Powershell prompt: Import-Module ActiveDirectory Get-ADUser 'user1' -properties PasswordLastSet | Format-List The "PasswordLastSet" atribute appears to be a translated version of the actual "pwdLastSet" attribute. A: You can also do this without a snap-in. I tried this and it worked: PS #> $searcher=New-Object DirectoryServices.DirectorySearcher PS #> $searcher.Filter="(&(samaccountname=user1))" PS #> $results=$searcher.findone() PS #> [datetime]::fromfiletime($results.properties.pwdlastset[0]) Wednesday, June 10, 2009 4:32:08 PM I also get a System.__ComObject for pwdLastSet if I have the user object set like this: $user = [adsi] "LDAP://cn=user1,ou=Staff,ou=User Accounts,dc=ramalamadingdong,dc=net" There should be a way to use [System.__ComObject].InvokeMember() and reflection to get that pwdLastSet value from the $user object, but I haven't been able to get it right. I never did figure it out, so I used the above example and moved on. If you're going to be doing a lot of work with AD (or Exchange or SQL Server) you might want to get the snapin for it and use that. A: There's an easier way. The ADSI object has a method called ConvertLargeIntegerToInt64. Note that it's a method of the ADSI object and not the System.__Comobject that's returned by querying the value of a timestamp attibute, so $user.pwdLastSet.value.ConvertLargeIntegerToInt64() won't work. You need to invoke it as follows: $user.ConvertLargeIntegerToInt64($user.pwdLastSet.value) That will get you the LDAP timestamp, which needs to be converted to a readable date, as explained by Bratch above. This will work for any timestamp attribute value returned by the ADSI provider, and the ConvertLargeIntegerToInt64 method is (I believe) exposed by any object representing a directory entry. Putting it all together, here is how you get the date when the password was last set: $user = [ADSI]'LDAP://cn=someusername,ou=someou,dc=somedomain,dc=com' [datetime]::FromFileTime($user.ConvertLargeIntegerToInt64($user.pwdLastSet.value))
{ "pile_set_name": "StackExchange" }
Q: PowerShell Script to restart the Application Pools of WFEs Need to create a PowerShell script to recycle the Application Pool of my WFE - Dev,Staging & Production servers of my SP 2013 Farm. I tried code mentioned here But somehow as mentioned in the blog, it seems, its applicable to Win Server 2008 only. Also I tried this too: # Load IIS module: Import-Module WebAdministration # Set a name of the site we want to recycle the pool for: $site = "Default Web Site" # Get pool name by the site name: $pool = (Get-Item "IIS:\Sites\$site"| Select-Object applicationPool).applicationPool # Recycle the application pool: Restart-WebAppPool $pool Don't know what I am missing here A: # Load IIS module: Import-Module WebAdministration # Adds registered Microsoft SharePoint PowerShell snap-ins Add-PSSnapin "Microsoft.SharePoint.PowerShell" # Get SharePoint Web Application $app = Get-SPWebApplication http://site/ # Get pool name from web application: $poolName = $app.ApplicationPool.Name # Recycle the application pool: Restart-WebAppPool $poolName
{ "pile_set_name": "StackExchange" }
Q: Looks like this if condition is not working I want a query to be executed IF the following condition is true... but looks like the query is executed anyways. if($post->post_parent = '302'){ // Query goes here } Is this query fine?? I want to executed the query if the parent page of current page is 302. Thanks A: The following solution worked $query2= mysql_query("SELECT * FROM wp_posts WHERE ID='$post->ID' AND post_parent=302"); $numrows2 = mysql_num_rows($query2); if($numrows2 != 0) { // query goes here }
{ "pile_set_name": "StackExchange" }
Q: How to make prediction using tensorflow models? As a newbie to tensorflow, I am using this tutorial from google for binary classification using a simple dense neural network. The slightly annoying thing about this (and a few other) tutorials is they completely gloss over the part of how to actually make a prediction from a dataframe of features, and directly move to model evaluation using some method of the trained model which hides the actual prediction procedure. So basically, I finished the model training, but even after that, I see no way mentioned on how to actually use the model to predict classes of unknown samples. To put concretely, I have a trained model, a pandas dataframe called test, and a list of columnames which correspond to feature names. Based on the variables declared in the tutorial, I tried feature_names=['age', 'sex', 'cp', 'trestbps', 'chol', 'fbs', 'restecg', 'thalach', 'exang', 'oldpeak', 'slope', 'ca', 'thal'] model.predict_proba(x=test[feature_names]) But it is throwing a type error. Basically, I need a function which will give me the classes, or ideally, the softmax probabilities of the classes from the feature frames without the label, because that is how we use any model. A: First, you need to convert the dataframe in numpy array or tf.data dataset that the model understands. For this purpose, the tutorial provides you with a function: # A utility method to create a tf.data dataset from a Pandas Dataframe def df_to_dataset(dataframe, shuffle=True, batch_size=32): dataframe = dataframe.copy() labels = dataframe.pop('target') ds = tf.data.Dataset.from_tensor_slices((dict(dataframe), labels)) if shuffle: ds = ds.shuffle(buffer_size=len(dataframe)) ds = ds.batch(batch_size) return ds test_ds = df_to_dataset(test, shuffle=False, batch_size=batch_size) Then you can get the predictions like this: model.predict_proba(x=test_ds) Take into account that the test-input format should be the same as training-input format, so if you have done any preprocessing (on_hot_encode, standardize, bucketize, etc) to the training dataset, you should do it also to the test dataset Another way, if your dataset is ready for prediction, you can just transform it to a numpy array: model.predict_proba(x=test[feature_names].values)
{ "pile_set_name": "StackExchange" }
Q: Conflict of VPN allocated IP address In my work place, my allocated private IP is 192.168.2.10, and I need to use VPN (PPTP) to another network, which also allocate IP in the same subnet, e.g. (192.168.2.20). What are the best way to get around this problem? I am using Mac. A: If you don't have a way to get either your work network or the network at the other end of your VPN link to renumber to a different private subnet, then you've got a problem because your work Mac will get confused by the subnet conflict between its local subnet and the VPN-remote subnet. A sneaky way to work around that problem might be to shield your Mac from seeing the 192.168.2.0/24 subnet at work, by putting your Mac behind an extra NAT. Take any cheap home gateway router and plug it into your work network in your office. Give it your work-assigned 192.168.2.10 IP address on its WAN port (make sure to tell it about the correct subnet mask and default gateway router for your work network). Configure it to do NAT, and to use some other subnet (say 10.0.1.0/24) on the private side of the NAT. Connect your Mac to the private side of this NAT box, and let it get a 10.0.1.x address. Make sure your Mac has no other wired or wireless connections to your work's 192.168.2.0/24 network. Now your Mac should be able to make the VPN connection.
{ "pile_set_name": "StackExchange" }
Q: Google Analytics - async tracking with two accounts I'm currently testing GAs new async code snippet using two different tracking codes on the same page; _gaq.push( ['_setAccount', 'UA-XXXXXXXX-1'], ['_trackPageview'], ['b._setAccount', 'UA-XXXXXXXX-2'], ['b._trackPageview'] ); Although both codes work, I've noticed that they present inconsistent results. Now, we aren't talking huge differences here, only 1 or 2 visits / day every now and then. However, this site is tiny and 1 or 2 visits equates to a 15% difference in figures. Now, the final site has much more traffic, but my concerns are; will this inconsistancy scale with traffic? assuming not, is a slight variation in recorded stats an accepted norm? A: You can avoid the conflicting cookies by setting a different domain for google analytics. <script type="text/javascript"> //<![CDATA[ var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-NNNN-1']); // primary profile _gaq.push(['_setDomainName', 'www.domain.com']); _gaq.push(['_trackPageview']); _gaq.push(function() { // create the second async tracker _gaq._createAsyncTracker('UA-NNNN-2', 'blogTracker'); }); // secondary profile (this is the default domain setup if not specified) _gaq.push(['blogTracker._setDomainName', 'domain.com']); _gaq.push(['blogTracker._trackPageview']); //]]> </script> This will keep the cookies separate. Note: I am using this setup to track events in a second profile to keep my bounce rate numbers accurate. The second profile tracking code is only used on my blog, thus, is not a complete profile on purpose.
{ "pile_set_name": "StackExchange" }
Q: Ошибка "Use of unassigned local variable" Как исправить? По идее все верно, не пойму что не так. A: Необходимо в любом случае инициализировать переменную перед первым использованием на чтение. Например: double res = 0; Проблема в том, что в вашем коде цикл может и не выполниться ни разу. Если длина массивов будет нулевой, тогда переменная не будет проинициализирована.
{ "pile_set_name": "StackExchange" }
Q: Как зашифровать строку, но чтобы результат был в виде цифр? Есть строки String inp_str = "A0B4FF47YG"; String key = "12345"; Как зашифровать строку, чтобы получились только цифры? Пробовал "ксорить", но "вылезают" буквы. Нужно для защиты: пользователь запускает приложение, считывается ID устройства, шифруется и сообщается разработчику. Разработчик генерирует ответный код, который сохраняется в приложении. Когда надо, приложение дешифрует сохраненный код и сравнивает. A: Заменить каждый символ его номером. A..Z - 00..25, 0..9 - 26..35 И склеить.
{ "pile_set_name": "StackExchange" }
Q: SO link in answer doesn't auto-translate to title When I'm writing an answer in Stack Overflow, and I want to refer to another SO question, I can usually just past the URL into the answer, and it will be displayed as the title. But sometimes this doesn't work correctly. I was editing this answer today, and I pasted the URL http://stackoverflow.com/questions/75752/what-is-the-most-straightforward-way-to-pad-empty-dates-in-sql-results-on-eithe into the answer. In the preview this was shown as the question title, but when I saved the edit, it showed the raw URL rather than the title. It did correctly mark it up as a clickable link. But I had to go back in and paste the title by hand and use the URL as the link target with the link tool. This seems related to Internal link wasn't translated to title but I don't think either of the answers there apply. This also happened a day or two ago. A: Since all the Stack Exchange sites support https://, within the site if you use the URL with https:// it will automatically parse the title. I have modified your answer with https:// and it parsed the title correctly. Please check the revision history.
{ "pile_set_name": "StackExchange" }
Q: setAnimation on textView has no effect I'm working on application, and I have an Activity where I have to show a TextView. Initially the TextView is invisible, but when I have to make it visible I set an animation before. The animation works fine on Alcatel One Touch API 17, HTC One X API 17 and Samsung S3 Neo API 19 but on the Nexus 5 API 23 it still uses the default animation while being visible (fade in). Is there any reason for that to happen? This is the code I use: myTextView.setAnimation(AnimationUtils.loadAnimation(getApplicationContext(), R.anim.come_in_from_left)); myTextView.setVisibility(View.VISIBLE); Edit I just noticed that when im not on debugger the animation don't work at all on all the devices !!! it look like i need to keep my devices connected to ADB !! A: I finally resolve it , there was two issues : First My TextView was inside a RelativeLayout which has a LinearLayout as parent, the attribute andoid:animateLayoutChanges was first mentioned in the RelativeLayout,i moved it inside LinearLayout. Second As mreza sh suggested to me , i replace setAnimation() with startAnimation() and call it after setVisibility() Now it works fine on all devices , even disconnected from the debugger !
{ "pile_set_name": "StackExchange" }
Q: Grow oyster mushrooms in vacuum cleaner bags? I'm giving oyster mushrooms a go, growing in coffee grinds in a plastic bag. Having an air filter in a bag, like the ones in purpose made mushroom bags, is a recommended technique. What if I used a vacuum cleaner bag ? These allow air passage and also filter out small particles. Workable idea ? I bought some that have a synthetic inner layer that I don't think the mushrooms would consume. What about maintaining a good moisture level by just spraying the absorbent bag ? I'm a noob so let me know if these are bad ideas. Thanks. A: Normally you want to sterilize the substrate in a pressure cooker so those mushroom bags are designed to withstand pressure cooking for the 90 minutes required. I suspect a vacuum cleaning bag is both more expensive than the 60c some charge for mushroom bags and not as robust. Coffee grinds are insufficient on their own to grow oyster mushrooms successfully. You need more carbon added to the mix. You need to sterilize coffee grounds as otherwise you'll just grow trichoderma. You don't need to sterilize straw as trichoderma doesn't grow that well on straw and so pasteurization is sufficient. (The same applies to cardboard which can just be boiled.) That leaves enough good bugs alive to combat any pathogens that might want to colonize the straw.
{ "pile_set_name": "StackExchange" }
Q: UISlider thumbTintColor doesn't change on iOS 7 (fine on iOS 6) I have an app that runs perfectly on iOS 6. I've set a blinking effect to a UISlider's thumb this way: -(void)startBlinkingSlider{ isSliderBlinking = YES; isSliderTinted = NO; [self performSelector:@selector(toggleSliderColor) withObject:nil afterDelay:0.2]; } -(void)toggleSliderColor{ if(isSliderBlinking){ if(isSliderTinted){ self.effectAmountSlider.thumbTintColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:1]; }else{ self.effectAmountSlider.thumbTintColor = [UIColor colorWithRed:255 green:0 blue:0 alpha:1]; } isSliderTinted = !isSliderTinted; [self performSelector:@selector(toggleSliderColor) withObject:nil afterDelay:0.2]; } } -(void)stopBlinkingSlider{ isSliderBlinking = NO; isSliderTinted = NO; self.effectAmountSlider.thumbTintColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:1]; } When I call startBlinkingSlider my slider starts blinking red in iOS 6. If I run the same exact app on my iOS 7 device, nothing happens. The slider's thumb retains its original white color. I've set a breakpoint on the line where I set the thumbTintColor. In debugger, here is what I'm getting: (lldb) po self.effectAmountSlider.thumbTintColor error: failed to get API lock (lldb) po self.effectAmountSlider.thumbTintColor UIDeviceRGBColorSpace 0 0 0 1 (lldb) I typed the exact same code and got a weird message in the first one. However, the second result is correct. Then after setting it to red I'm also getting the correct result: (lldb) po self.effectAmountSlider.thumbTintColor UIDeviceRGBColorSpace 1 0 0 1 Even though the debugger shows the correct value, I'm getting no visual change in the slider. It's still white, color doesn't change in any way. I've searched Apple's documents here: https://developer.apple.com/library/ios/documentation/userexperience/conceptual/TransitionGuide/Controls.html It doesn't say anything about UISlider's thumbTintColor not working as iOS 6. It should stay working as expected. I've checked the thread and everything is running on the main thread. toggleSliderColor is always on the main thread so it's not a threading issue. Why is my thumb color not working? Thanks, Can. A: I discovered a workaround. By first calling the 'setThumbImage:forState:' method, the 'thumbTintColor' property will then take effect. [self.slider setThumbImage:[UIImage imageNamed:@"Thumb.png"] forState:UIControlStateNormal]; self.slider.thumbTintColor = [UIColor blackColor]; I tested this on Version 7.0 (463.9.4.2) of iOS Simulator. A: I just so happened to read the iOS 7 UI Transition Guide again this morning, and tripped on a statement under Slider. If EITHER maximumTrackTineColor OR thumbTintColor are nil, then both properties are ignored. So I tried to set all the tint colors, thumb still white. I entered a bug report on this - #15277127 - reference it if you enter your own bug. The more bug reports the more likely Apple will fix it soon. EDIT: Apple duped my bug to another one - this was obviously known a while ago. A: On basis of @aaronsti's answer I found that the following worked for me. Setting thumb-image to nil had no effect. [_slider setThumbImage:[_slider thumbImageForState:UIControlStateNormal] forState:UIControlStateNormal]; _slider.minimumTrackTintColor = minTintColor; _slider.thumbTintColor = thumbTintColor;
{ "pile_set_name": "StackExchange" }
Q: Java - cannot bring the window to front I am trying to execute the following code: SwingUtilities.invokeLater(new Runnable() { public void run() { if (frame.getExtendedState() == Frame.ICONIFIED) frame.setExtendedState(Frame.NORMAL); frame.getGlassPane().setVisible(!frame.getGlassPane().isVisible()); frame.toFront(); frame.repaint(); } }); Unfortunately this does not bring it to the front from behind other windows... Any solutions? A: Per the API documentation for setExtendedState: If the frame is currently visible on the screen (the Window.isShowing() method returns true), the developer should examine the return value of the WindowEvent.getNewState() method of the WindowEvent received through the WindowStateListener to determine that the state has actually been changed. If the frame is not visible on the screen, the events may or may not be generated. In this case the developer may assume that the state changes immediately after this method returns. Later, when the setVisible(true) method is invoked, the frame will attempt to apply this state. Receiving any WindowEvent.WINDOW_STATE_CHANGED events is not guaranteed in this case also. However, there is also a windowDeiconified callback you can hook into on WindowListener: SwingUtilities.invokeLater(new Runnable() { private final WindowListener l = new WindowAdapter() { @Override public void void windowDeiconified(WindowEvent e) { // Window now deiconified so bring it to the front. bringToFront(); // Remove "one-shot" WindowListener to prevent memory leak. frame.removeWindowListener(this); } }; public void run() { if (frame.getExtendedState() == Frame.ICONIFIED) { // Add listener and await callback once window has been deiconified. frame.addWindowListener(l); frame.setExtendedState(Frame.NORMAL); } else { // Bring to front synchronously. bringToFront(); } } private void bringToFront() { frame.getGlassPane().setVisible(!frame.getGlassPane().isVisible()); frame.toFront(); // Note: Calling repaint explicitly should not be necessary. } }); A: I found that the following workaround for toFront() on a JDialog works on Windows 7 (haven't tested other platforms yet): boolean aot = dialog.isAlwaysOnTop(); dialog.setAlwaysOnTop(true); dialog.setAlwaysOnTop(aot); Paul van Bemmelen
{ "pile_set_name": "StackExchange" }
Q: XML web service running on Ubuntu VS Studio 2005 I have developed an application that will need to access a web service. I will be developing the web service. However, the platform will be Ubuntu running Apache Tomcat server. I have 2 questions: 1) Can I deploy a MS XML web service to run on a Ubuntu Server? 2) If I can't. I will have to develop a Java Web Service. However, my application that is written in VS C# 2005 will need to access it will be a windows application. How can my application access a Java Web Service? Many thanks for any advice, A: If you want cross-platform compatibility, you can only deploy .net code that runs under Mono. The best way to check this is to actually develop the code under Mono and use Mono to test it. So, don't use Visual Studio. Sorry. There is no problem with interfacing pieces of code written in two different languages. You can use XMLRPC, a RESTful API, or a proprietary protocol. I'm sure there are other ways for the two to "talk", as well.
{ "pile_set_name": "StackExchange" }
Q: R: Re-order numeric vector by name using custom order I have a a numeric vector and want to re-order by name, using a custom order. x <- sample(1:20, 5) names(x) <- c("feb", "may", "mar", "jan", "apr") x feb may mar jan apr 7 10 5 13 11 As you can see, the vectors are not in month order Desired output I wish to re-order this character vector through month order using the names, i.e. jan, feb, mar, apr, may... How is this possible? note: I am after a method that can be used on all names/character strings, rather than specifically date objects A: We can convert the names of 'x' to factor and settting the levels to the month.abb in lowercase, apply the order and get the 'x' in that order. x[order(factor(names(x), levels=tolower(month.abb)))] jan feb mar apr may 13 7 5 11 10 The conversion to factor with levels specified can be applied to any character vector in a custom order, otherwise, by default, the ordering is based on alphabetical order i.e. x[order(names(x))] Suppose, if want the order to be say, 'jan', 'mar', 'apr', 'may', 'feb', use that as levels in the factor call x[order(factor(names(x), levels = c('jan', 'mar', 'apr', 'may', 'feb')))] As the OP posted another vector in a custom order in the comments x1 <- c(icecream = 3, jelly = 4, fruit = 5) x1[order(factor(names(x1), levels = c("jelly", "fruit", "icecream")))] # jelly fruit icecream # 4 5 3
{ "pile_set_name": "StackExchange" }
Q: innodb transactions and room reservation I'm currently reading a lot about transactions in InnoDB, at this time i only ever used myISAM tables so i'm not very used to all this: Here is my table scheme : CREATE TABLE IF NOT EXISTS `reservations` ( `id_reservation` mediumint(8) unsigned NOT NULL AUTO_INCREMENT, `id_room` mediumint(8) unsigned NOT NULL, `date_from` date NOT NULL, `date_to` date NOT NULL, `cancelled` enum('Y','N') NOT NULL DEFAULT 'N', PRIMARY KEY (`id_reservation`), KEY `id_room` (`id_appartement`) ) ENGINE=InnoDB; Now let's say i want to INSERT a new reservation for room ID 15, from 2012-02-15 to 2012-02-24, here's what I think i should do based on what i read : start transaction : START TRANSACTION; INSERT the row INSERT INTO reservations SET id_room = 15, date_from = '2012-02-15', date_to='2012-02-24', cancelled='N'; check if there is a reservation conflicting with the reservation i just made SELECT * FROM reservations WHERE id_room = 15 AND cancelled = 'N' AND date_from < '2012-02-24' AND date_to > '2012-02-15' AND id_reservation <> LAST_INSERT_ID(); if not, COMMIT; else, ROLLBACK; Problem is, in default isolation mode (REPEATABLE-READ), once i start the transaction, i won't see any other INSERT made outside this very transaction. So what would happen if, just after step 1), another user inserts a conflicting reservation ? Maybe i should use READ-COMMITED in this case? but wouldn't this lead to issues as well ? Thanks for helping ! A: What you have is fine, but you need to add one table and one query to your transaction. The table needs one row for each id_room. You probably already have that table. So, right after START TRANSACTION do: SELECT * FROM room WHERE id_room=15 FOR UPDATE; That will block the next guy trying to put in a reservation for the same room until you either COMMIT or ROLLBACK your transaction, as long as the next guy also uses this FOR UPDATE syntax. http://dev.mysql.com/doc/refman/5.0/en/innodb-locking-reads.html
{ "pile_set_name": "StackExchange" }
Q: How to hide the object of the OLE controler? I'm working with the OLE object using VB6. I use it to play a sound when a certain condition is true. The OLE class is MPlayer. The problem is that I don't want the player to be visible. I know that I can set the Visible property of the OLE control to false, but thats just hides the conrtrol itself, but not the MPlayer itself. I've tried the following: If Something Then ' Starts the music. OLEPlayer.Action = 7 ' Here, which line I should use to hide the MPlayer itself? ' OLEPlayer.Visible = False - hides just the controler, and not its class. ' There is no Visible property to the Class. Else ' Stops the music. oleAlarmSound.Action = 9 End If I've looked everywhere, but since there is a minor support for VB6 in general, and VB6 ole in particular, i've found nothing. A: Use Screen.Width Screen.Height object.Top object.Left to move the object out of the screen area
{ "pile_set_name": "StackExchange" }
Q: Count values of one column per value of second column in dataframe I have this dataframe: dummy_dataset = {'sentences': ['a','b','c','d','e','f'], 'classes': [1,2,1,3,3,2] } dataframe = pd.DataFrame(dummy_dataset) sentences classes 0 a 1 1 b 2 2 c 1 3 d 3 4 e 3 5 f 2 What I am looking for is: output = { 1 : ['a','c'], 2 : ['b','f'], 3: ['d','e'] } I tried with dict method : dict_count = {} for m in range(len(dfg)): if dfg['classes'].iloc[m] not in dict_count: dict_count[dfg['classes'].iloc[m]] = [dfg['sentences'].iloc[m]] else: dict_count[dfg['classes'].iloc[m]].append(dfg['sentences'].iloc[m]) How can I do this with pandas count and groupby method? A: Use groupby on classes column and aggregate as list , then to_dict: dataframe.groupby('classes')['sentences'].agg(list).to_dict() Output: {1: ['a', 'c'], 2: ['b', 'f'], 3: ['d', 'e']}
{ "pile_set_name": "StackExchange" }
Q: For loop (inside while loop) is being ignored I have two for loops inside a while loop but when I execute the program, the while loop just becomes an infinite loop. Here is my code: while (!inFile1.eof()){ for (int row = 0; row < 5, row++;){ for (int column = 0; column < 5, column++;){ getline(inFile1, fileData, (',')); matrix1[row][column] = stoi(fileData); cout << matrix1[row][column]; } } } I'm new to C++ so maybe I have made a silly error but I'd appreciate any help A: You have stray commas in your for loops, which you should replace with semicolons: int row = 0; row < 5; row++; int column = 0; column < 5; column++; Currently the stopping condition is row < 5, row++, which is the same as row++ due to the way in which the comma operator works. Eventually your int will overflow and then you're in undefined behaviour land.
{ "pile_set_name": "StackExchange" }
Q: How to cast an object identified via an interface to the specific object of a Generic class that implements that interface I have the following design of objects and classes. As mentioned in the comments of the method Play(Animal a), I would like to be able to test that a is effectively of type Cat<Big> and cast a accordingly so that I could access the method MethodUniqueToCats(). I am able to get Big via a.GetType().GetGenericArguments()[0]. But, somehow I am failing to make the leap on how to go from Animal to Cat<Big>. I believe that it is possible because Visual Studio is able to determine this info at runtime (checked via debug + breakpoints inside the method Play(Animal a)). interface Animal { } class Cat<T> : Animal { public void MethodUniqueToCats() { } } class Dog<T> : Animal { } class Freetime { private Animal my_animal; public void Play(Animal a) { my_animal = a; Type t = a.GetType().GetGenericArguments()[0]; // I would like to test if the type of 'a' passed to this // method is a Cat and subsequently cast it to a Cat of type 't' // so that I can access 'MethodUniqueToCats()'. // Line below does not work but wondering how to go about: // if (a.GetType().IsAssignableFrom(typeof(Cat<t>)) // How to do the 'casting' } } class MyProgram { public static void Main(string[] args) { Freetime f = new Freetime(); Cat<Big> c = new Cat<Big>(); f.Play(c); } } Thanks in advance. A: If you absolutely want to do it this way (and violate the Liskov Substitution Principle) then the simplest way would be to use an interface for Cat, something like this: interface IAnimal { } interface ICat { void MethodUniqueToCats(); } class Cat<T> : IAnimal, ICat { public void MethodUniqueToCats() { } } And now you can test that your object is a cat like this: IAnimal animal = new Cat<int>(); var cat = animal as ICat; if (cat != null) { cat.MethodUniqueToCats(); } Or if you're lucky enough to be running C# v7 (i.e. Visual Studio 2017), you can do this: if (animal is ICat cat) { cat.MethodUniqueToCats(); }
{ "pile_set_name": "StackExchange" }
Q: Looping over bits in C I'm a C newbie, I want to store input bits to an output array according to the below procedure. input MSB LSB MSB LSB MSB [169,48,0] = 1 0 1 0 1 0 0 1 0 0 1 1 0 0 0 0 0 0 0 0 0 0 0 0 The program should loop over the input data to find- in which byte the start index is present and extract the bits from start index till the end index and store it in the output[ ]. As an example my start index is 4 and it is present in input[0], my end index is 13. So I need to extract from bit position 4 to 13 and place it in output[ ]. What I meant when I said bit position 4 to 13 is that - I need bits[4 - 7] = {0 1 0 0 1} from input[0] and bits[8 - 13] = {1 1 0 0 0 0} from input[1] expected output [9, 48,0] = 0 0 0 0 1 0 0 1 0 0 1 1 0 0 0 0 0 0 0 0 0 0 0 0 I tried to program in C but unfortunately I wasn't successful, the looping over bits is through LSB to MSB. I need to loop over 1st byte and continue to the next byte and repeat till the byte index where the end position is present. #include<stdio.h> int main() { unsigned char input[3] = {169,48,0}; unsigned char output[3]= {0}; int i, start = 4, end = 13; for(i=0; i<3; i++) { output[i] = (input[i] >> (start)) & ((1u << (end)) -1u); printf("%u\n",output[i]); } return 0; } The program loops over all 3 input bytes and stores from bit index 4 to end index of that particular byte i.e 7. output [10, 3, 0] = 0 0 0 0 1 0 1 0 0 0 0 0 0 0 1 1 0 0 0 0 0 0 0 0 I want to check whether my start index is present in input[0] or input[1] or . . . input[n], copy and store from start index to end index(that may be present in any byte position) as per the expected output shown in the beginning. I would be greatfull if you could correct the program logic as I'm new to C. A: Welcome to the forum. I would be greatfull if you could correct the program logic as I'm new to C. Here's a tentative effort. Your main logic is in the following line: output[i] = (input[i] >> (start)) & ((1u << (end)) -1u); This is easier to analyze by simplifying it to the following (and using a temporary unsigned char variable tmp): tmp = input[i] >> start; // (1) tmp &= (1u << end) - 1u; // (2) // etc. It is not clear to me precisely what you are trying to do here. I believe what you should be trying to do is extracting 8-start bits from input[i] and start bits from input[i+1] and placing a logical OR of these values (appropriately shifted) in a temporary variable. If this is so, then my suggestions are the following. In the first line (1) you are shifting the wrong direction: it should be tmp = input[i] << start; The next line (2) is not accomplishing anything. (You are effectively AND'ing with zero.) Also, you should be using | rather than &, and the second operand should be a selection of bits (appropriately shifted) from the next byte. tmp |= input[i+1] >> (8-start); This, then, is the extraction stage. Next would be the insertion stage in the output stream. There are more nuances not discussed above but that gives the general idea. (See below for an implementation which handles more details.) I want to check whether my start index is present in input[0] or input[1] or . . . input[n] For this use int idx = start / 8; // byte index int offset = start % 8; // bit position within byte P.S. Your original question indicated that the offset of the extracted bits could be different in the output stream than in the input stream. Your edits hide that fact, but the implementation below allows for this possibility (a 'transposition'). Possible implementation void transpose_bits(unsigned char *a, unsigned char *b, int start, int end, int dest, size_t array_len) { unsigned char tmp = '\0', tmp2 = '\0'; int offset = 0, idx = 0, len = 0, next_bits = 0; char bitmask = 0x80; len = end - start; while (len > 0) { // Single pass - transpose up to 8 bits ... tmp = tmp2 = '\0'; // Determine the byte index and offset in the input byte array. idx = start / 8; offset = start % 8; tmp = a[idx] << offset; next_bits = offset + len - 8; if (next_bits < 0) { // Don't even need all of current byte => remove trailing bits ... tmp &= bitmask >> (len - 1); } else if (next_bits > 0) { // Need to include part of next byte ... tmp2 = a[idx + 1] & (bitmask >> (next_bits - 1)); tmp |= tmp2 >> (8 - offset); } // Determine byte index and offset in output byte array idx = dest / 8; offset = dest % 8; b[idx] |= tmp >> offset; b[idx + 1] |= tmp << (8 - offset); // Update start position and length for next pass ... if (len > 8) { len -= 8; dest += 8; start += 8; } else len -= len; } } Sample usage: // Extract bits: 'start' and 'dest' are the same. transpose_bits(input, output, 4, 13, 4, 3); // Assume arrays are of length '3' // Transpose bits: 'start' and 'dest' not the same. transpose_bits(input, output, 4, 13, 10, 3); Notes: The char[] arrays must be unsigned (as you have correctly chosen) - as the right shift operator works differently with signed values. You should check the bounds of the arrays (comparing idx against array_len); I have skipped that here for brevity Each iteration in the while() loop of the transpose_bits() function can handle up to 8 bits. By using multiple passes, it can handle an arbitrary number.
{ "pile_set_name": "StackExchange" }
Q: What happens to the uncertainty principle if I just read the Feynman Lectures about the electron gun experiment with two holes in the middle wall. It demonstrates that if we don't look at the electrons while they travel toward the detector there is an interference pattern in the probability curve of the electrons similarly to what happens with waves. But if we try to measure which hole the electron passes through the probability pattern changes and the electrons behave like bullets. At the end of the lecture there is a further experiment this time with a wall with rollers. I don't understand much the details of the latter experiment but it turns out that even in this situation is not possible to break the uncertainty principle. My question is what would happen in the following situation: We have the middle wall but this time the two holes are replaced with two detectors that perform the following actions: retrieve all the information about the electron speed, angle/direction, spin, hole A or B, etc... block the electron shoot another electron or the same electron with the same speed, angle/direction, spin etc... that has been retrieved before it was stopped. This way the new electron has the same properties that would have had the original electron if it was not watched by the machines and it goes on toward the backstop with the movable detector described in the lecture. What is the probability curve of such situation? Will it have interference or not? A: You won't get an interference pattern. This was very nicely explained by @Vivekanand Mohapatra, but there is a more simple reason why. The interference never happens. In the original double slit experiment, you get the interference when the electron's wavefunction crosses both slits and interferes with itself, which causes a change in the probability distribution. But the catch is that when you measure the electron, the wavefunction collapses, and the electron now has a definite position. That is why it behaves like a normal particle and you don't get the pattern. But, in this case, the electron is detected (which means it is measured) before it can cross the slit. So the electron now has a particular, set position (and it behaves like a particle). So even if you can do imperfect cloning, the new electron produced has no wave properties. Because it's path has already been set; and there is no probability distribution for it. So, it cannot interfere with itself and produce the infamous wave patterns.
{ "pile_set_name": "StackExchange" }
Q: What event is fired on page load / hash load I am working in jQuery Mobile 1.3, and I cannot find the appropriate event for this scenario. I have a <div> #show_protocol which houses dynamic content. If the browser is left open at this page, and then is refreshed, no content is displayed (because the form submission that populates it has not occurred). So, I'd like to bind onto an event, check if it's this particular page role <div>, and execute some code if so. I've tried binding to pageshow, pagebeforeload, pageinit, and none seem to work at page load. The code fires when the event is triggered through use of the app, but it is not fired on first page load. Here's what I've tried: $("#show_protocol").on( "pageshow", function(){ // swap in pageinit, pagebeforeload, etc. if ( $(this).hasClass("preload") ) { [..] } else { [..] } }); Have also tried: $(document).on( "hashchange", function(){ And as @Sudhir points out: $(document).on( "pageshow", "#show_protocol", function(){ None of that works. I'm not sure what events JQM fires on browser first load? My HTML is basic, should not affect functionality: <div data-role="page" id="show_protocol">[..]</div> A: Thanks to Sudhir for the .bind() suggestion, I was able to implement like so: $(document).bind('pageinit', function( e ){ var $id = $( e.target ).attr( "id" ); if ( $id == 'show_protocol' ){ // check which page is loading if ( !$("body").hasClass("preload") ) { // check if already loaded $.mobile.changePage( "#protocols" ) // redirect } } $("body").addClass("preload"); });
{ "pile_set_name": "StackExchange" }
Q: Apple Swift compiler for Windows I am looking for an Apple Swift compiler for Windows (running under Windows and producing code for Windows), without having to virtualize any OS. It needs to run at least on Windows 7 x64. A: Silver runs on Windows and allows you to compile Swift code to Java and .NET. Alternatively, you can compile Swift code online in a web browser on any platform, including Windows. Try: RunSwift SwiftStub A: Swift is build on the same LLVM Compiler, Objective-C is build on. (See Wikipedia) So you need an Obj-C environment. And that is a bit complicated, but possible. It would be much easier to build a Virtual Machine or a Hackintosh. And as you can read from this answer, it is not a good Idea coding Obj-C (or Swift) on a PC. A: Swift for Windows now available on Microsoft Codeplex. https://swiftforwindows.codeplex.com/ System Requirement - Visual C++ Redistributable for Visual Studio 2015. Or you can use official swift version on Bash On Ubuntu On Windows 10 (Anniversary Update). Checkout full step-wise guide here - Instal Swift 3.0 on Windows 10 Anniversary Update
{ "pile_set_name": "StackExchange" }
Q: How many symbols are in an alphabet if there are two symbols that mean the same? If you were to define a formal alphabet as the set {a, b}, but also say "a = b," then does the alphabet contain 1 symbol or 2 symbols? On the one hand, it seems like it should contain 2 symbols since they are two distinct symbols syntactically. Semantically, the 2 symbols are the same thing, so the set contains one thing, although the "thing" in mind may not be symbols per se. Note: I'm assuming this is a different issue from token vs symbol distinction, since saying multiple tokens of a symbol doesn't mean there are more than 1 symbol is different from asking if 2 symbols being equal in some sense makes it 1 or 2 symbols. A: Here's an answer I got from user keitamaki on Reddit that seems perfect to me. If your formal alphabet is {a,b}, then "a=b" isn't a string in your formal language (since '=' isn't in your formal alphabet). So if you're saying "a=b", then you're making that statement in the meta-language. And if you literally mean by that that a and b are the same symbol, then yes, your formal alphabet is just {a}. But perhaps the better answer is: "don't do that" :) If you define your formal alphabet as {a,b}, then it is usually understood that a and b are different symbols. If you then go on to say (in the meta-language) that a and b are the same symbol, this isn't an issue of semantics at all (again, because "a=b" doesn't have a semantic meaning inside your formal language, you won't be writing truth tables for "a=b" and you won't be talking about models of that statement because it isn't a statement in your language). It's literally you saying that: "oh, by the way, when I wrote "a" and "b" earlier in my definition, I didn't mean to."
{ "pile_set_name": "StackExchange" }
Q: ProxyPass exception gives me "too many redirects" error I have an application on my server that is for the most part overwriting Apache. Now I want to install PhpMyAdmin on my VPS, it doesn't work (displays directory listing instead of UI), but by asking around on few sites plus some trial and error I realized I'm trying to run PhpMyAdmin through my application (Traccar) instead through Apache. Now back to the topic. I'm on Ubuntu Server 18.04 and I have the following site configuration: Listen 80 <IfModule mod_ssl.c> <VirtualHost *:80> ServerName x.example.com Redirect / https://x.example.com </VirtualHost> <VirtualHost *:443> ServerName x.example.com DocumentRoot /var/www/html ServerAdmin admin@localhost ProxyPass /api/socket ws://localhost:app_port/api/socket ProxyPassReverse /api/socket ws://localhost:app_port/api/socket ProxyPass /phpmyadmin ! ProxyPass / http://localhost:app_port/ ProxyPassReverse / http://localhost:app_port/ SSLEngine on SSLOptions +StrictRequire SSLProtocol TLSv1 ServerAlias x.example.com SSLCertificateFile /etc/letsencrypt/live/x.example.com/fullchain.pem SSLCertificateKeyFile /etc/letsencrypt/live/x.example.com/privkey.pem Include /etc/letsencrypt/options-ssl-apache.conf </VirtualHost> </IfModule> The way I want it to work: If I connect to x.example.com I get redirected to my application. Works properly. If I connect to x.example.com/phpmyadmin I want to receive PhpMyAdmin UI. I receive a "too many redirects" error instead. When I access phpmyadmin directory the rewrite log keeps alternating between these two messages in the server log: [Fri May 10 10:32:38.733370 2019] [rewrite:trace1] [pid 19228] mod_rewrite.c(482): [client xxx.xxx.xxx.xxx:yyyy] xxx.xxx.xxx.xxx - - [x.example.com/sid#7f34cd331cc0][rid#7f34cd2640a0/initial] pass through /phpmyadmin [Fri May 10 10:32:38.767398 2019] [rewrite:trace2] [pid 19228] mod_rewrite.c(482): [client xxx.xxx.xxx.xxx:yyyy] xxx.xxx.xxx.xxx - - [x.example.com/sid#7f34cd331cc0][rid#7f34cd2620a0/initial] init rewrite engine with requested uri /phpmyadmin This is what I receive when I wget to x.example.com/phpmyadmin: --2019-05-10 10:43:19-- https://x.example.com/phpmyadmin Resolving x.example.com (x.example.com)... xxx.xxx.xxx.xxx Connecting to x.example.com (x.example.com)|xxx.xxx.xxx.xxx|:443... connected. HTTP request sent, awaiting response... 301 Moved Permanently Location: https://x.example.com/phpmyadmin [following] --2019-05-10 10:43:19-- https://x.example.com/phpmyadmin Reusing existing connection to x.example.com:443. HTTP request sent, awaiting response... 301 Moved Permanently Location: https://x.example.com/phpmyadmin [following] --2019-05-10 10:43:19-- https://x.example.com/phpmyadmin Reusing existing connection to x.example.com:443. The lines repeat until they reach 20 redirections. If I curl to x.example.com/phpmyadmin I get this: <!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN"> <html> <head> <title>302 Found</title> </head> <body> <h1>Found</h1> <p>The document has moved <a href="https://x.example.comphpmyadmin">here</a>.</p> <hr> <address>Apache/2.4.29 (Ubuntu) Server at x.example.com Port 80</address> </body> </html> A: The answer is incredibly simple. I forgot I left a permament redirect rule in my apache2.conf - this caused the infinite loop. Deleting that line from apache config fixed my problem. Thanks to everyone involved.
{ "pile_set_name": "StackExchange" }
Q: A diffeomorphism between a cylinder and a one-sheeted hyperboloid A cylinder $C=\{(x,y)\in \mathbb{R}^{3}: x^2 +y^2=1 \}$ and a hyperboloid $H=\{(x,y,z)\in \mathbb{R}^{3}: x^2 +y^2 - z^2=1 \}$, my try was to define the functions $F:O\rightarrow H$ and $G:H \rightarrow O$ as $F(x,y,z)=(-x,-y,\sqrt{2(x^2+y^2)})$ and $G(x,y,z)=(x,y,0)$ and so conclude that $O$ and $G$ are diffeomorphic. is this correct or there is gap in my thesis? A: Take : $$\tag{1}(x,y,z) \in H \to (\tfrac{x}{\sqrt{x^2+y^2}},\tfrac{y}{\sqrt{x^2+y^2}},z) \in C$$ and its reciprocal transformation: $$\tag{2}(u,v,z) \in C \to (u\sqrt{1+z^2},v\sqrt{1+z^2},z) \in H$$ Explanation : the intersection of plane $z=z_0$ with : cylinder $C$ is a unit radius circle. one-sheeted hyperboloid $H$ is a circle with radius $\sqrt{1+z_0^2}$ (do you see why ?). Then it remains to map radially one circle onto the other, which is what transformations (1) and (2) are doing.
{ "pile_set_name": "StackExchange" }
Q: Has anyone got a proven recipe to attenuate wi-fi with a Faraday cage? I need to put a domestic wi-fi router in a homemade Faraday cage that will severely attenuate the signal. Has anyone actually DONE this? There is lots of good advice of what should work, but few reports of what actually did work. The nearest, on Youtube, is someone putting the router in three big nested heavy metal trash cans. That works good, but I've got no room for kit that bulky. A great-sounding suggestion is to cover a box in 2 layers of aluminium foil, so there is high capacitance between the two layers. I tried this and it didn't work, maybe because I re-used old foil and it wasn't flat enough. In general aluminium foil is useless - it is like Wile E. Coyote and the Road Runner, the signal just laughs at it. Perforated metal sheet a few mm thick is meant to work. If no answers here that will be my next attempt, but I'd love to know if anyone has actually done this in any way. Many thanks A: A common microwave oven is specifically designed to block the frequency band used by wi-fi, bluetooth, cellular data networks, and various other wireless communication protocols. This is because the microwave oven operates at the same frequency band; that's why microwaves can interfere with wifi. A cheap microwave, or even a non-functional one, is probably the easiest way to get a good Faraday cage of this type. Either put a battery in the microwave with the device, or cut a small hole to feed a power cord through; the hole will cause leakage, but it shouldn't be too much. As for being a proven recipe... Well, the fact that you don't feel hot standing in front of the microwave is evidence enough, no? If you need more, just stick a cell phone in the microwave and try to call it. It won't ring. (as mentioned above, cell phones and wifi use the same frequency band)
{ "pile_set_name": "StackExchange" }
Q: Javascript - get all table -> tr > id values I would like to access all the values of a table tr id field. <table> <tr id="1"></tr> <tr id="2"></tr> <tr id="3"></tr> <tr id="4"></tr> <tr id="5"></tr> </table> What I would like to do is, using a javascript function, get an array and have acess to [1,2,3,4,5] Thank you very much! A: var idArr = []; var trs = document.getElementsByTagName("tr"); for(var i=0;i<trs.length;i++) { idArr.push(trs[i].id); } A: Please keep in mind that HTML ids must start with an alphanumeric character in order to validate, and getElementsByTagName returns a collection, not an array. If what you really want is an array of all your table rows, there's no need to assign an ID to each. Try something like this: <table id="myTable"> <tr><td>foo</td></tr> <tr><td>bar</td></tr> <tr><td>baz</td></tr> </table> var i, tr, temp; tr = []; temp = document.getElementById('myTable').getElementsByTagName('TR'); for (i in temp) { if (temp[i].hasOwnProperty) { tr.push(temp[i]); } }
{ "pile_set_name": "StackExchange" }
Q: Upgrade vim/gvim on Ubuntu 12.04 Ubuntu 12.04 has vim 7.3.429, which has an issue with match() function, because of it I need to upgrade vim and gvim. I need for vim >= 7.3.829 && <= 7.3.1268, or >= 7.4.018 (because of another issue) I tried to look for PPAs, but this one has 7.4.005, which is buggy too (see version requirements above), and this one, which seems fine, but after I've done this: sudo apt-add-repository ppa:dgadomski/vim-daily sudo apt-get update sudo apt-get install vim It returns that vim is already newest version. (my actual Vim version is 7.3.429). Why is that? I also tried to remove vim and install it again, but newly installed version is 7.3.429 again. Then I tried to build it from source, so I've cloned mercurial repo, configured and installed it: cd ~/projects hg clone https://vim.googlecode.com/hg/ vim cd vim/src ./configure --enable-rubyinterp=yes --enable-pythoninterp=yes --enable-gui=gtk2 --with-x --prefix=/opt/vim make sudo checkinstall --pkgname=vim-my-latest So I have vim 7.4.227 in the /opt/vim/bin now, but there's no gvim, and when I start vim and check has('gui') and has('ruby'), both of them return 0. Why is that? I've given --enable-rubyinterp=yes and --enable-gui=gtk2 --with-x. Have I missed something? A: Done, after all. Install libs that are necessary for gui: sudo apt-get install libncurses5-dev libgnome2-dev libgnomeui-dev libgtk2.0-dev libatk1.0-dev libbonoboui2-dev libcairo2-dev libx11-dev libxpm-dev libxt-dev Install lib that is necessary for ruby: sudo apt-get install ruby-dev Clone the repo (here I clone it in ~/projects/vim ) : cd ~/projects hg clone https://vim.googlecode.com/hg/ vim Remove existing vim packages: sudo apt-get remove vim-gtk vim vim-runtime vim-gui-common Build, create deb package and install it: cd ~/projects/vim/src make distclean ./configure --with-features=huge --enable-pythoninterp --enable-rubyinterp --enable-gui=gnome2 --prefix=/usr/local -with-python-config-dir=/usr/lib/python2.7/config make sudo checkinstall --pkgname=vim-my
{ "pile_set_name": "StackExchange" }
Q: Java - Iterate two lists, compare then add to another list I have three lists: listA, listB, listC. listA listB 1,a,tf b,true 2,b,tf a,false 3,c,tf c,true and I would like to have listC to be listA + listB in order of listA (replacing listA's tf with listB's true/false). listC 1,a,false 2,b,true 3,c,true Here's my code Iterator a= listA.iterator(); Iterator b= listB.iterator(); while(a.hasNext()){ while(b.hasNext()){ if(String.valueOf(a.next()).split(",")[1].equals(String.valueOf(b.next()).split(",")[0])){ listC.add(String.valueOf(a.next()).replaceAll("tf", String.valueOf(b.next()).split(",")[1])); } } } With individual iterator-while for listA and listB being split and indexed, it works fine, but when I run the code above, the program just freezes. Any thoughts? A: You're really not far off. Iterators can be confusing and so I tend to avoid them. I can't really see where the infinite loop is in your code - I expected a NullPointerException because you're calling a.next() and b.next() multiple times. If you change your code to remove the iterators, it works fine: List<String> listA = Arrays.asList("1,a,tf", "2,b,tf", "3,c,tf"); List<String> listB = Arrays.asList("b,true", "a,false", "c,true"); List<String> listC = new ArrayList<>(); for(String a : listA) { for (String b : listB) { if (String.valueOf(a).split(",")[1].equals( String.valueOf(b).split(",")[0] ) ) { listC.add(String.valueOf(a).replaceAll("tf", String.valueOf(b).split(",")[1])); } } } System.out.println(listC.toString());
{ "pile_set_name": "StackExchange" }
Q: Calculus exercise - differentiability and $C^1$ functions Show that the function $f(x,y) = |xy|$ is differentiable at $\mathbf{0}$, but is not of $C^1$ in any neighbourhood of $\mathbf{0}$ So a function is differentiable at $\mathbf{0}$ if $\lim\limits_{\mathbf{h} \to 0} \dfrac{f(\mathbf{0} + \mathbf{h}) - f(\mathbf{0}) - Df(\mathbf{0})\mathbf{h}}{|\mathbf{h}|} =0$ So I did $\lim\limits_{\mathbf{h} \to 0} \dfrac{f(\mathbf{h}) - Df(\mathbf{0})\mathbf{h}}{|\mathbf{h}|} =0$ Here I am completely stuck, I have no idea how to evaluate the matrix $Df(\mathbf{0})$, so I can't handle the limit. The book uses a different approach, it argues that $Df(\mathbf{0})$ is $0$ (which makes the algebra a lot easier) and they used the alternative limit quotient where no $\mathbf{h}$ appears, but such a quotient is never even mentioned in my book EDIT1. At some point the book utilizes $|xy| \leq \frac{1}{2}(x^2 +y^2)$. This resembles the AM_GM inequality or is this something else? Or was there some other Lemma that gives rise to this inequality? EDIT2: I want to mention that I handled the last part of the question already, that is showing it is not $C^1$ in any neighbourhood of $\mathbf{0}$. I just computed $f_x(x,y)$ from first principle and concluded the limit does not even exist. The book chose to look at the limit of $f_x(x,y)$ an interval of $0$ - particular $(0,y)$, but I don't think that's necessary A: I will assume we work with the Euclidean norm on $\mathbb{R}^2$: $\|(x,y)\|=\sqrt{x^2+y^2}$. Recall the inequality $2|xy|\leq x^2+y^2$ which holds for every $x,y\in\mathbb{R}$. This follows by developing the obvious inequality $(|x|-|y|)^2\geq 0$. Note that $|xy|\leq x^2+y^2$ would be sufficient to prove our claim below. So for all $(x,y)\neq (0,0)$, we have $$ \frac{|f(x,y)|}{\|(x,y)\|}=\frac{|xy|}{\sqrt{x^2+y^2}}\leq\frac{x^2+y^2}{2\sqrt{x^2+y^2}}=\frac{\sqrt{x^2+y^2}}{2}=\frac{\|(x,y)\|}{2}. $$ Let $L$ denote the null linear map $L(x,y)=0$. The inequality above shows that $$ \lim_{(x,y)\rightarrow(0,0)}\frac{|f(x,y)|}{\|(x,y)\|}=\lim_{(x,y)\rightarrow(0,0)}\frac{|f(x,y)-f(0,0)-L(x,y)|}{\|(x,y)\|}=0. $$ By definition, this proves that $f$ is differentiable at $(0,0)$ with derivative $Df(0)=L=0$. Note: the strategy here is to find a candidate for $Df(0)$, and then to check it satisfies the definition of differentiability. If you can't see what $Df(0)$ is gonna be, you can't get started. Since you say you handled the last part, I'll stop here.
{ "pile_set_name": "StackExchange" }
Q: Initialising char** in c++ I looked at most of related posts but unfortunately I couldn't get a satisfactory answer for my concrete case. I am using a 3rd party library which has a structure with an attribute of char**, which I need to populate. I tried almost everything imaginable that I thought would be valid c++ syntax and would work, however I always get a run-time error trying to assign it. To clarify I should say that the array of strings should take (i assume) names of files. Consider this as our code: char** listOfNames; // belongs to the 3rd party lib - cannot change it listOfNames = // ??? So my question is how to initialize this variable with one or more string file names, eg: "myfile.txt" ? Should also be c++11 compatible. A: I think you should initialize the listOfNames as a dynamic string array and then initialize each element of the array as the following codes: char** listOfNames; // belongs to the 3rd party lib - cannot change it int iNames = 2; // Number of names you need try { // Create listOfNames as dynamic string array listOfNames = new char*[iNames]; // Then initialize each element of the array // Element index must be less than iNames listOfNames[0] = "Hello"; listOfNames[1] = "World"; } catch (std::exception const& e) { std::cout << e.what(); }
{ "pile_set_name": "StackExchange" }
Q: CKEditor usage in commercial used website Yes, i have seen this question before, but i have never found a clear answer, so i'll try it again. I'll explain below why i don't have an answer yet. Can i use the CKeditor for free at the site i'm building. This site is an open website, available for everyone to register, built by me, for a third party. If you want to compare it to something else on the web: i am building facebook for the facebook guys. The facebook site is open for everyone, and they are making a profit of it. Now i've (tried to) read the licences for the CKEditor, but they all seem to care about me modifying the source code, and wether i'm redistributing souce code, and if i make my modifications on the source code public available etc. etc. The point is: i don't care about the source code. If i use the facebook example: if i use a html editor in the facebook site i'm building so members can use html in their profile descriptin, i don't care about the source code of the html editor, i'm not distributing the source code, i'm not redistributing the source code, i' not editing the source code etc., i only use the control in the facebook site hence i deploy the binaries to the server and nothing more. If i can make one more compare: i use it like i use all the .Net binaries: deploy it tto the server, members 'use' the code in the binaries because my code makes use of the binaries, but nothing more, and the source code gets untouched. Also, i am not planning to redistribute the .Net binaries, extend them, make them available for others.. the same is true for the usage of the CKEditor. I did read there is also a commercial licence, which is 'copyleft'. I don't know what they are talking about, i have never seen 'copyleft' on my VS2010, Word, Avast, Resharper etc. licence. Can anyone give me a clue? EDIT: i think you can compare it to the Jquery usage also. I use Jquery on my site, but only use the binaries (so to speak) as is. A: There are three Copyleft licenses for CKEditor as of now. They are GPL LGPL MPL GNU definition of CopyLeft license states Copyleft is a general method for making a program (or other work) free, and requiring all modified and extended versions of the program to be free as well. Which essentially means you cannot edit source of CKEditor and then pawn it off as your own for a price. You are bound to re-distribute it for free forever that way; regardless of how much you have changed the original source code. From what I read from your post, I would dare say you can surely use CKEditor's free version in your site.
{ "pile_set_name": "StackExchange" }
Q: How to correctly make mock methods call original virtual method I want to define for a mocked method the behavior that when it is called in a test, all the EXPECTED_CALL and ON_CALL specific for that test are being checked, but still the original method is being executed after that. A: You can accomplish this by using the delegating-to-real technique, as per Google Mock documentation: You can use the delegating-to-real technique to ensure that your mock has the same behavior as the real object while retaining the ability to validate calls. Here's an example: using ::testing::_; using ::testing::AtLeast; using ::testing::Invoke; class MockFoo : public Foo { public: MockFoo() { // By default, all calls are delegated to the real object. ON_CALL(*this, DoThis()) .WillByDefault(Invoke(&real_, &Foo::DoThis)); ON_CALL(*this, DoThat(_)) .WillByDefault(Invoke(&real_, &Foo::DoThat)); ... } MOCK_METHOD0(DoThis, ...); MOCK_METHOD1(DoThat, ...); ... private: Foo real_; }; ... MockFoo mock; EXPECT_CALL(mock, DoThis()) .Times(3); EXPECT_CALL(mock, DoThat("Hi")) .Times(AtLeast(1)); ... use mock in test ...
{ "pile_set_name": "StackExchange" }
Q: calculating lottery odds for non-descending order This is part of a TopCoder.com algorithm practice question and I cannot wrap my head around it. I am given a lottery format and I need to calculate the odds. One particular format is that the numbers must be in non-descending order. The numbers do not have to be unique, so I can repeat the same number. Example: The "PICK TWO FROM TEN IN ORDER" game means that the first number cannot be greater than the second number. This eliminates 45 possible tickets, leaving us with 55 valid ones. The odds of winning are 1/55. How do I calculate this? A: Since each unordered pair of different numbers can be ordered in two different ways, the number of eliminated tickets is half the number of ordered pairs of different numbers. To count the ordered pairs of different numbers, note that to form such a pair you can first choose one of $n$ numbers, then you can choose one of the remaining $n-1$ numbers. Thus there are $n(n-1)$ such pairs, and half as many eliminated tickets, $n(n-1)/2$. [Edit:] That answer only applies to the case of two numbers. For $k$ non-decreasing numbers out of $n$, think of the numbers as making $n-1$ upward steps from $1$ to $n$. You want to combine these $n-1$ small steps into $k+1$ big steps, one before the first number, $k-1$ from one number to the next and one after the last number. The number of ways to distribute $n-1$ small steps over $k+1$ big steps is $$\binom{(n-1)+(k+1)-1}{(k+1) - 1}=\binom{n+k-1}{k}=\frac{(n+k-1)!}{k!(n-1)!}=\frac{n(n+1)\cdots(n+k-1)}{1\cdot2\cdots(k-1)k}\;.$$
{ "pile_set_name": "StackExchange" }
Q: Case-insensitive str_replace How do I use str_replace but to be case-insensitive when it searches for the string? For example, suppose i want to replace ABcD with a. The resulting command would be $string=str_replace("ABcD","a",$string);. But if there is some string like "abCD" then again I have to use $string=str_replace("abCD","a",$string);. A: Then instead of using str_replace try usingstr_ireplace Its a case insensitive version of str_replace so use it as $string = str_ireplace("ABcD","a",$string);
{ "pile_set_name": "StackExchange" }
Q: Why did the Order bother to guard the Prophecy? (And please, nobody say "Cause Dumbedore asked them to") We know one of the tasks of the Order after its re-creation was to keep safe a weapon Voldemort was after. “What’s he after apart from followers?” Harry asked swiftly. He thought he saw Sirius and Lupin exchange the most fleeting of looks before Sirius said, “Stuff he can only get by stealth.” When Harry continued to look puzzled, Sirius said, “Like a weapon. Something he didn’t have last time.” (Order of the Phoenix, Chapter 5, The Order of the Phoenix) Sturgis Podmore was Imperiused while patrolling around the door behind which it was kept, and Arthur Weasley was attacked there by Nagini (or Voldemort in Nagini). “Your father has been injured in the course of his work for the Order of the Phoenix,” said Dumbledore. [...] “The Ministry wouldn’t want everyone to know a dirty great serpent got —” “Arthur!” said Mrs. Weasley warningly. “— got — er — me,” Mr. Weasley said hastily, [...] “You were guarding it, weren’t you?” said George quietly. “The weapon? The thing You-Know-Who’s after?” “George, be quiet!” snapped Mrs. Weasley. “Anyway,” said Mr. Weasley in a raised voice... (Order of the Phoenix, Chapter 22, St Mungo's Hospital) - “Sturgis Podmore,” said Hermione, breathlessly. “Arrested for trying to get through a door. Lucius Malfoy got him too. I bet he did it the day you saw him there, Harry. Sturgis had Moody’s Invisibility Cloak, right? So what if he was standing guard by the door, invisible, and Malfoy heard him move, or guessed he was there, or just did the Imperius Curse on the off chance that a guard was there? So when Sturgis next had an opportunity — probably when it was his turn on guard duty again — he tried to get into the department to steal the weapon for Voldemort" (Order of the Phoenix, Chapter 26, Seen And Unforeseen) We also learn later that the said weapon was the Prophecy about Voldemort and Harry. Voldemort was after it, because he thought its end would tell him how to destroy Harry. And so, since his return to his body, and particularly since your extraordinary escape from him last year, he has been determined to hear that prophecy in its entirety. This is the weapon he has been seeking so assiduously since his return: the knowledge of how to destroy you. (Order of the Phoenix, Chapter 37, The Lost Prophecy) But let's look at the content of the Prophecy, and what part he already knows of: “THE ONE WITH THE POWER TO VANQUISH THE DARK LORD APPROACHES... BORN TO THOSE WHO HAVE THRICE DEFIED HIM, BORN AS THE SEVENTH MONTH DIES... AND THE DARK LORD WILL MARK HIM AS HIS EQUAL, BUT HE WILL HAVE POWER THE DARK LORD KNOWS NOT... AND EITHER MUST DIE AT THE HAND OF THE OTHER FOR NEITHER CAN LIVE WHILE THE OTHER SURVIVES... THE ONE WITH THE POWER TO VANQUISH THE DARK LORD WILL BE BORN AS THE SEVENTH MONTH DIES...” (Order of the Phoenix, Chapter 37, The Lost Prophecy) - “He heard only the first part, the part foretelling the birth of a boy in July to parents who had thrice defied Voldemort." (Order of the Phoenix, Chapter 37, The Lost Prophecy) The bold parts are already known to Voldemort... and the rest of the prophecy does not really gives him valuable information: Mark him as his equal: OK, that's already done. He'll have a power the Dark Lord knows not: Yep, that's love. But since Voldemort does not know of it, he won't be able to understand this sentence. He will imagine another power, but that won't help him (and he probably already guessed this while planning to kill baby Harry). Either must die at the hand of the other...: Alright, so Voldemort should go and kill Harry then! Oh, but he kind of already wanted to anyway, didn't he? Was preventing Voldemort from hearing the end of the Prophecy worth all the trouble and the risks (one member of the Order lost for 6 months to Azkaban, another heavily wounded and happy not to be dead...)? Why did they bother to do so? A: I think you're dismissing AND THE DARK LORD WILL MARK HIM AS HIS EQUAL a little too quickly. Throughout the books, even after Voldemort is defeated by Harry as a baby, defeated by Harry while inhabiting Quirrel, defeated by Harry in the graveyard, through all of that, Voldemort is still operating under the impression that Harry is nothing, simply a little brat who happened to get lucky (a lot). Perhaps if Voldemort had heard the prophecy and learned that Harry was, in fact, "his equal", he might have considered Harry a more worthy opponent, and would have taken greater care, more careful planning, when it came to arranging his demise. Basically, not knowing that Harry was anything but a fortunate child had the impact of lulling Voldemort into a false sense of security. Or so, perhaps, might Dumbledore have believed. A: Bearing in mind that Dumbledore didn't tell the Order what the prophecy said, they clearly have taken his word for it that it was worth protecting. Whether it really was is debatable. However, Dumbledore would have wanted to prevent Voldemort from hearing the whole thing because Voldemort will be more careful and make his moves slower if he doesn't know what it says, as he was clearly burned the last time he jumped the gun with baby Harry and got himself disembodied. For all he knows, the end of the prophecy said that he would die. While he doesn't know for certain what it says he's likely to avoid all out war on the Order as much as possible. Of course, the flip side is that it meant he was far sneakier for a lot longer and consolidated his power and control of the Ministry etc before making himself known again, whic arguably wasn't in anyone's interest. A: Nowhere in the book is it actually specified that the Order's goal is to prevent Voldemort from attaining the prophecy; as the asker rightly points out, the prophecy would not help Voldemort at all. So why bother? I believe it was possible that the Order's ultimate plan was to force Voldemort and/or his Death Eaters into the open. After all, this was their main problem in the book: nobody believes Voldemort is back. The Order members themselves have no idea where Voldemort is and cannot really do anything against his Death Eaters. The only definite knowledge they have of Voldemort's plans is that he is after the prophecy, so why not surprise him there when he comes after it? After all, they know either Voldemort or Harry has to retrieve it; we know this because Dumbledore says: "And then you saw Rookwood, who worked in the Department of Mysteries before his arrest, telling Voldemort what we had known all along — that the prophecies held in the Ministry of Magic are heavily protected. Only the people to whom they refer can lift them from the shelves without suffering madness." (Order of Phoenix, Chapter 37) Keeping a guard stationed at the Department of Mysteries thus serves the following purposes: It keeps them updated on Voldemort's movements. They'll know from the ways in which Voldemort attempts to retrieve the prophecy the extent of Voldemort's reach, specifically how much power he has within the Ministry, as well as how much information Voldemort has managed to gather. It helps maintain the charade that the prophecy is important. Not only does this keep Voldemort distracted by a fruitless goal, it forces him to potentially make mistakes like the Bode incident that might expose him, and, as long as Voldemort doesn't give up, it will eventually force Voldemort himself to show up at the Ministry once he learns that only he or Harry can retrieve the prophecy. If Voldemort and/or a horde of Death Eaters show up at the Ministry, Fudge will be there to see him/them (which, of course, is what happened when they did). The guard would be able to alert Dumbledore and the rest of the Order, who could show up and hold them off until they can get Fudge to arrive and confront the truth. Ultimately, the Order's goal may very well have been to force Voldemort himself to show up at the Ministry, exposing his revival to the wizarding world at large.
{ "pile_set_name": "StackExchange" }
Q: Is it possible to banish jet-lag with hi-tech sunglasses? The Daily Telegraph (via yesterday’s Independent.ie) carried an article titled “Hi-tech 'sunglasses' could banish jet-lag,” which claimed: Australian sleep researches have developed a set of hi-tech "sunglasses", described as the world's first "time-control" spectacles, which can imitate sunlight patterns. The team, from Flinders University, in Adelaide, say the glasses emit a soft green glow that helps a traveler adapt to changing sleep patterns and time zones in "small steps". It targets a part of the brain that regulates the human body-clock, by sending signals to the rest of the body that help it slowly realise it is in a different area of the world. Are we really towards the goal for banishing jet-lag during travels? I'm skeptical of this claim, so I wonder if there are facts to prove it. A: TL;DR: Yes, they work, but they aren't for sale, and they have competition. The first question to address is whether the claims in the Daily Telegraph match the claims made by the actual researchers. The research team being quoted is the Sleep Research Laboratory in the School of Psychology at Flinders University. The team does indeed make such claims: Research shows that bright light visual stimulation (light which enters the eyes), can change the timing of the body clock and its timing of sleep or awakening signals to the body. Thus, bright light therapy has been used to treat the range of disorders caused by a mis-timed body clock including shift work, jet lag, sleep onset and early morning insomnia mentioned above as well as winter depression (Seasonal Affective Disorder, SAD). [...] Because of their small size and relatively inexpensive components, the LED glasses will be less expensive than the presently marketed light boxes. They suffer none of the handicaps of light boxes listed above. One of their main advantages is that our research has confirmed their body clock re-setting effects which are the basis of treatment for all of the above conditions. [...] At present the LED glasses are still experimental devices. They are not yet commercially available. They cite their own research, such as Wright, H. R., Lack, L. C., & Partridge, K. J. (2001). Light emitting diodes can be used to phase delay the melatonin rhythm. Journal of Pineal Research, 31(4): 350-355. These data suggest the portable LED light source is an effective way of delivering light to phase shift the melatonin rhythm, with the blue/green LED being the more effective of the two LEDs. That research confirms the basis of the technology, but not that it works in a set of glasses. But these researchers are from Flinders University (in Adelaide, South Australia), and so is my BSc degree, so clearly their claims are completely correct! It is the Flinders way! But if you insist on wasting everyone's time by checking that these results have been reproduced independently... Paul MA, Miller JC, Gray G, Buick F, Blazeski S, Arendt J., Circadian phase delay induced by phototherapeutic devices, Aviat Space Environ Med. 2007 Jul;78(7):645-52. In this study 14 subjects were given a range of different phototherapies, including LED spectacles. All phototherapy devices produced melatonin suppression and significant phase delays. Sleepiness was significantly decreased with the light tower, the light visor, and the Litebook. Task performance was only slightly improved with phototherapy. The LED spectacles and light visor caused greater subjective performance impairment, more difficulty viewing the computer monitor and reading printed text than the light tower or the Litebook. The light visor, the Litebook, and the LED spectacles caused more eye discomfort than the light tower. So these scientists from Defence R&D Canada - some random institute that isn't prestigious enough to be based in Adelaide - found that, yes, the LED glasses work, but they aren't the most convenient form-factor for phototherapy.
{ "pile_set_name": "StackExchange" }
Q: JQuery changing css toggles back on mouse release I'm trying to create a fairly simple script which uses links to toggle which div is being displayed. There is a div for each day, and when a corresponding link is clicked, it shows the according div and hides the others. This works, but once you release the mouse it reverts back to the default state. I'm guessing this is something very simple, but I've tried searching around and can't find anything. Here is the code I'm using: Fiddle $(document).ready(function() { var dayDivs = []; var displayDay = 0; loadDayDivs(); adjustDayDisplay(); $('.day-link').mousedown(function() { var linkClicked = $(this).text(); switch (linkClicked) { case "Friday": displayDay = 0; break; case "Saturday": displayDay = 1; break; case "Sunday": displayDay = 2; break; } adjustDayDisplay(); }); function loadDayDivs() { dayDivs[0] = $(".friday-div"); dayDivs[1] = $(".saturday-div"); dayDivs[2] = $(".sunday-div"); } function adjustDayDisplay() { for (var i = 0; i < dayDivs.length; i++) { dayDivs[i].css("cssText", "display: none !important;"); } dayDivs[displayDay].css("cssText", "display: inline !important;"); } }); on jsfiddle I get a strange error which seems to be associated with forms normally. Any help on this would be VERY much appreciated. A: You should change the mouse down event to click event and suppress the click event. This fiddle works $('.day-link').click(function(e) { e.preventDefault(); // New line
{ "pile_set_name": "StackExchange" }
Q: Find files on Windows modified after a given date using the command line I need to search a file on my disk modified after a given date using the command line. For example: dir /S /B WHERE modified date > 12/07/2013 A: The forfiles command worked for me on Windows 7. The article is here: Find files based on modified time Microsoft Technet documentation: Forfiles For the example above: forfiles /P <dir> /S /D +12/07/2013 /P The starting path to search /S Recurse into sub-directories /D Date to search, the "+" means "greater than" or "since" A: You can use PowerShell to do this. Try: Get-ChildItem -Recurse | Where-Object { $_.LastWriteTime -ge "12/27/2016" } A: I was after the size of the files changed and did not have PowerShell. I used the following, but the clue came from other posts: http://www.scotiasystems.com/blog/it-hints-and-tips/quick-way-to-find-recently-changed-files-in-windows and Windows command for file size only set Target=E:\userdata rem Date format is M-D-YYYY set date=12-13-2013 set Filelist=d:\temp\filelist.txt set Sizelist=d:\temp\sizelist%date%.csv echo Target is %Target% echo Start date is %date% echo file list is %Filelist% echo Sizelist is %sizelist% Xcopy %Target% /D:%date% /L /S > %Filelist% echo FileSize (bytes), FileName > %sizelist% For /f "tokens=1 delims=;" %%j in (%Filelist%) do ( call :Size "%%j" ) Goto :EOF :Size @echo off echo %~z1, %1 >> %sizelist%
{ "pile_set_name": "StackExchange" }
Q: Drupal: Inserting fivestar widget in an external php file I have been trying to load fivestar module and show the rating widget of the selected node in an external php file. I have gotten the rating widget displayed on the page but it only displays degraded version of the widget (non-JavaScript, dropdown widget and "Rate" button) I looked into the source code of the page but the javascript for fivestar module was not loaded. I have tried to load javascript using following functions but had no luck: fivestar_add_js(); $path = drupal_get_path('module','fivestar'); drupal_add_js($path.'/js/fivestar.js', 'inline', 'footer'); The following is the code in the php file: //require the bootstrap include require_once 'includes/bootstrap.inc'; //Load Drupal drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL); fivestar_add_css(); // I have used one of the following two functions one at a time to test. fivestar_add_js(); $path = drupal_get_path('module','fivestar'); drupal_add_js($path.'/js/fivestar.js', 'inline', 'footer'); $book = $_GET["book"]; $chap = $_GET["chap"]; $prob = $_GET["prob"]; $string = $book.'/'.$chap.'/'.$prob; $query = "SELECT ctcr.nid FROM content_type_comments_ratings AS ctcr WHERE ctcr.field_problem_value = '".$string."'"; $result=db_query($query); $row = db_fetch_array($result); if(isset($row['nid'])) { $nid = $row['nid']; node_load(FALSE, NULL, TRUE); $fivestar = node_load($nid, NULL, TRUE); if (function_exists('fivestar_widget_form')) print fivestar_widget_form($fivestar); } If you could give me a hint or direct me to some reading on the web, I would appreciate it. Thank you very much in advance. A: By doing all this on an 'external' page/file, you circumvent the Drupal theming system - drupal_add_js() (and fivestar_add_js(), as it is just using that in the end) do not output the script tags themselves, but simply ensure that they will be included in the $scripts variable in page.tpl.php, which is then responsible to print that variables content. As you do not go through the page template, you get no script tags. You could do a print drupal_get_js(); in your external file to output the scripts added via drupal_add_js() as a quick fix, but note that this will output all the default drupal js files as well, which might be more than you need (but might as well contain other scripts needed by fivestar, e.g. jquery). Alternatively, you'll have to create the needed script tags yourself. As for hints on what to read, it is difficult to point you to something particular, but you might want to read up on the theming system in general.
{ "pile_set_name": "StackExchange" }
Q: Moving a part of the code from main class to deal with readability issues I have a "Form1.cs" class where all of the proccessing happens and that file has nearly 2k line of code. I no longer can read it properly. is there a way to move part of the functions to another file? an extension class? I still want to be able to call these functions from main "Form1.cs". And these functions should not have any problems reading public declared variables in main class. using ... namespace myprogram { public partial class Form1 : Form { public void function1() {} public void function2() {} public void function3() {} public void function4() {} } } in the example above - what is the proper way to move function 4 to another file. Is there any other way to deal with the problem maybe? A: Making all of your controls publicly visible from outside the Form, and then just copying code into a separate class and having it access the instance of your Form to manipulate the controls directly will not help you maintain your code. It'll just make things a whole new kind of difficult. What you really want is to move your "business logic", or whatever you want to call it, into a separate class, without moving code that directly touches the UI. (Leave that code in the original Form.) You said you've already got helper classes, and it sounds like you intend to go the partial class route for now, so the following may be unnecessary to reiterate (but here goes anyway...) Assuming your Form currently looks like this: public partial class Form1 : Form { public void function4() { var currentText = MyTextBox.Text; // Do a bunch of stuff that depends on the Text value and even manipulates it MyTextBox.Text = ??? // Some other value } public void SomeOtherFunction() { function4(); } } I'd split out the functionality into a separate class, which accepts parameters from your Form and can pass values back, but absolutely does not directly reference controls on the Form that's calling it. public partial class Form1 : Form { private HelperClass helper; public Form1() { helper = new HelperClass(); } public void SomeOtherFunction() { MyTextBox.Text = helper.Function4(MyTextBox.Text); } } public class HelperClass() { public string Function4(string input) // I need a better name { // Do a bunch of stuff that depends on the input value and even manipulates it return ??? // Some other value, perhaps from the previous stuff you did } } If you need to return multiple values, there are structures for that, such as a Tuple, though beware this can be difficult to maintain as well: public class HelperClass() { public Tuple<int,string> Function4(string input) // I need a better name ;p { // Do a bunch of stuff that depends on the input value and even manipulates it return Tuple.Create(200, "Success!"); } } Or just create another small class, to create an instance of, populate with data, and return back to the calling method in your original Form.
{ "pile_set_name": "StackExchange" }
Q: Create a subtitle for menu items in Silverstripe CMS? Hi I'm using Silverstripe CMS on the "Simple" template. I'm wondering how to create subtitles for the menu items. The current navigation template is like so: <nav class="primary"> <span class="nav-open-button">²</span> <ul> <% loop $Menu(2) %> <li class="$LinkingMode"><a href="$Link" title="$Title.XML">$MenuTitle.XML</a></li> <% end_loop %> </ul> I'm thinking i could somehow edit $Menutitle.XML but how? Also the sub title should be displayed directly under the Title but as the same button. The SubTitle would need to have a different css rule so that it could be smaller. I know that the CMS has an area for me to edit the page titles which become the menu titles, would it be easy to add a subtitle to the admin like that or is there some other easier way? I only need to make a few of them. A: easy thing to do: add a field to the $db array of your Page class: private static $db = array('SubTitle' => 'Varchar(255)'); then add this field in the getCMSFields method in the same file: public function getCMSFields() { $fields = parent::getCMSFields(); $fields->addFieldToTab('Root.Main', TextField::create('SubTitle')); return $fields; } now you can use the variable $SubTitle in your template like so, for example: <li class="$LinkingMode"><a href="$Link" title="$Title.XML">$MenuTitle.XML - $SubTitle</a></li> in case all of this sounds too complex, you should really run through the silverstripe tutorials first, see http://doc.silverstripe.org/framework/en/tutorials/
{ "pile_set_name": "StackExchange" }
Q: Scala how to retrieve xml tag with optional attribute I am trying to get scala xml node tag with attribute. I would like to get just the tag name with attribute and not the child elements. I have this input: <substance-classes> <nucleic-acid-sequence display-name="Nucleic Acid Sequence"> <nucleic-acid-base> <base-symbol>a</base-symbol> <count>295</count> </nucleic-acid-base> <nucleic-acid-base> <base-symbol>c</base-symbol> <count>329</count> </nucleic-acid-base> <nucleic-acid-base> <base-symbol>g</base-symbol> <count>334</count> </nucleic-acid-base> <nucleic-acid-base> <base-symbol>t</base-symbol> <count>268</count> </nucleic-acid-base> </nucleic-acid-sequence> <genbank-information> <genbank-accession-number>EU186063</genbank-accession-number> </genbank-information> </substance-classes> I am trying to replace the contents of <nucleic-acid-sequence> by doing this val newNucleicAcidSequenceNode = <nucleic-acid-sequence>{ myfunction } </nucleic-acid-sequence> But some <nucleic-acid-sequence> has attributes like <nucleic-acid- sequence display-name="Nucleic Acid Sequence">. Since my newNucleicAcidSequenceNode is a hardcoded tag I am losing the attibutes. How do I retain the optional attributes and still pass { myfunction } to <nucleic-acid-sequence> tag? A: So, if I have understood you well: you want to replace just a part of your xml this part are the children of any nucleic-acid-sequence under substance-classes you don't want to lose any attributes of any foresaid nucleic-acid-sequence changing these foresaid children is done by a function ( myFunction) So my answer would be in that case: import scala.xml.{Node, Elem} val myXml: Elem = <substance-classes> <nucleic-acid-sequence display-name="Nucleic Acid Sequence"> <nucleic-acid-base> <base-symbol>a</base-symbol> <count>295</count> </nucleic-acid-base> <nucleic-acid-base> <base-symbol>c</base-symbol> <count>329</count> </nucleic-acid-base> <nucleic-acid-base> <base-symbol>g</base-symbol> <count>334</count> </nucleic-acid-base> <nucleic-acid-base> <base-symbol>t</base-symbol> <count>268</count> </nucleic-acid-base> </nucleic-acid-sequence> <genbank-information> <genbank-accession-number>EU186063</genbank-accession-number> </genbank-information> </substance-classes> def myFunction(children: Seq[Node]) : Seq[Node] = ??? // whatever you want it to be // Here's the replacement: myXml.copy(child = myXml.child.map { case e@Elem(_, "nucleic-acid-sequence", _, _, children@_*) => e.asInstanceOf[Elem].copy(child = myFunction(children)) case other => other }) For instance, myFunction could keep only children which have a count above 300 and could be something like: import scala.util.{ Try, Success } def myFunction(children: Seq[Node]): Seq[Node] = children.collect { case e: Node if Try((e \ "count").text.toInt > 300) == Success(true) => e } In that case, if you replace the unimplemented myFunction in the first snippet by this, the replacement would give: <substance-classes> <nucleic-acid-sequence display-name="Nucleic Acid Sequence"><nucleic-acid-base> <base-symbol>c</base-symbol> <count>329</count> </nucleic-acid-base><nucleic-acid-base> <base-symbol>g</base-symbol> <count>334</count> </nucleic-acid-base></nucleic-acid-sequence> <genbank-information> <genbank-accession-number>EU186063</genbank-accession-number> </genbank-information> </substance-classes> As you can see no attributes of nucleic-acid-sequence is lost and your function has kept two nodes over four for a defined condition. Hope it helps.
{ "pile_set_name": "StackExchange" }
Q: Autoplaying video without sound I just finished reading this article on why autoplaying video is bad http://www.punkchip.com/autoplay-is-bad-for-all-users/. I knew autoplaying was a bad practice but this video gave me good, tangible reasons why its not a best practice. My question, sites like YouTube, KickStarter and ProductHunt DO have autoplaying video, the catch is the audio is muted. I'm working on a site for a client now, more specifically a page in which the client might request the video be autoplayed. Obviously this behavior would not be acceptable on with sound, but how about if I muted the sound by default and provided a volume button like ProductHunt? And just replaced the video with a poster image on mobile? Thoughts? Thanks. A: If you will be using the HTML5 player native to the browser. HTML5 video does provide the ability to mute a video and autoplay it. You simply have to include the 'muted' and 'autoplay' properties in your video tags in addition to the 'controls' property so that users have the ability to play,pause, unmute etc, as an example, the code would look like this: <html> <body> <video width="320" height="240" autoplay controls muted> <source src="movie.mp4" type="video/mp4"> <source src="movie.ogg" type="video/ogg"> Your browser does not support the video tag. </video> <p><strong>Note:</strong> The muted attribute of the video tag is not supported in Internet Explorer 9 and earlier versions.</p> </body> </html>
{ "pile_set_name": "StackExchange" }
Q: Dynamic paint erase paint doesnt work? Ok, I am trying to achieve exactly what this person did with weight painting but with output to material - the circle of "intersection" depends on the proximity of the brush object to canvas, so gets smaller when goes away - Cycles, shade based on proximity to another object's geometry I followed the linked tutorial and it is working for material, however after I move the object away again the paint is still there - I tried checking the Erase Paint option, but this did nothing - How can I make it follow proximity AFTER it touches down? Im in cycles obviously A: On the Canvas there should be Dynamic Paint Advanced options. This includes 'Dry' and 'Dissolve' settings. The 'Dry' allows your 'wetmap' to dry over time whereas the 'Dissolve' setting allows your paint to revert back to its initial colour over a series of framee - in my experience you should only enable one of these two options as the 'Dry' seems to disable 'Dissolve'. Enable 'Dissolve' and set the number of frames to the number of frames you want the paint to remain - if you want it to instantly revert then set it to '1' and uncheck 'Slow'. This should produce something like the following : Note also that the dynamic paint treats timeline frame 1 as a special case where the paint is automatically reset and rendered. If you are on a different frame the dynamic paint will not automatically update in the viewport.
{ "pile_set_name": "StackExchange" }
Q: В течение какого времени происходит обновление цены приложение в каталоге Google Play? В течение какого времени происходит обновление цены приложение в каталоге Google Play после ее изменения в Google Play Console? Я изменил цену - она поменялась в каталоге в течение нескольких минут. Я изменил ее еще раз. Она уже так быстро не поменялась! А прошло уже более часа. Есть какие-то регламенты на эту операцию? A: Update your apps: App updates take some time to be delivered to existing users. If you’ve submitted an update that hasn’t showed up on Google Play, please wait at least 24 hours before contacting our support team. До 24 часов.
{ "pile_set_name": "StackExchange" }
Q: Using center alignment in HTML for e-mail I started writing html for e-mails using tables. Now, for first time I tried to write using divs, but this is causing a problem: I cannot center align everything I used to be able to center. Maby what I wrote is not correct, but this is only way that I find, to be able after writing to copy everything from browser to Gmail. Can someone to tell me how I can center align in this code? If someone can also tell me if there are better ways to write this code I would be happy to recieve criticism and helpful information. P.S: I tried padding, positioning, margin, put height and width, but with these options in most results HALF of my bacground or my background is going off at all. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Untitled Document</title> <style type="text/css"> div#Container { width: 895px; height: 525px; position: absolute; left: 9px; top: 15px; } div#Room { padding-left: 245px; padding-top: 80px; width: 625px; } #Room span { font-family: Times New Roman, Times, serif; font-weight: bold; font-size: 23px; color: #522405; } #D { padding-left: 70px; } #GD { padding-left: 103px; } #GPV { padding-left: 53px; } div#Content { padding-left: 245px; padding-top: 10px; width: 625px; } #Right { position: absolute; left: 872px; top: 222px; } img.Spacer { margin-left: 10px; } div.content { font-family: Arial, Helvetica, sans-serif; color: black; font-size: 17px; font-weight: bold; } .BP { vertical-align: text-top; margin-top: 10px; margin-left: 245px; } .table { vertical-align: text-top; font-family: Arial, Helvetica, sans-serif; font-size: 20px; text-align: center; color: #002b55; margin-left:245px; } .TD { margin-left: 30px; } .adress { font-family: Times New Roman, Times, serif; font-size: 10px; text-align: center; font-weight: bold; color: #100073; } .OOT { font-family: Arial, Helvetica, sans-serif; font-size: 13px; font-weight: bold; color: #100073; text-align:center; } .res { vertical-align: top; padding-left: 25px; } </style> </head> <body> <div> <img style="position: relative;" src="http://i1300.photobucket.com/albums/ag93/dobriyan/E-mail%20-%20Ayara%20Kamala/BK_zpsa93ab347.png" alt="Background" /> </div> <div id="Container"> <div id="Room" > <a href="http://bit.ly/XSyPG5" title="Deluxe" target="_blank" > <img src="http://i1300.photobucket.com/albums/ag93/dobriyan/E-mail%20-%20Ayara%20Kamala/D_zpsf4ea5de8.jpg" border="0px" alt="Deluxe" /> </a> <a href="http://bit.ly/XSyPG5" title="Grand Deluxe" target="_blank" > <img class="Spacer" src="http://i1300.photobucket.com/albums/ag93/dobriyan/E-mail%20-%20Ayara%20Kamala/GD_zpse78278b7.jpg" border="0px" alt="Grand Deluxe" /> </a> <a href="http://bit.ly/XSyPG5" title="Grand Pool Villa" target="_blank" > <img class="Spacer" src="http://i1300.photobucket.com/albums/ag93/dobriyan/E-mail%20-%20Ayara%20Kamala/GPV_zpsb381cd33.jpg" border="0px" alt="Grand Pool Villa" /> </a> <br /> <a href="http://bit.ly/XSyPG5" title="Deluxe" target="_blank" style="text-decoration: none;"><span id="D">Deluxe</span></a> <a href="http://bit.ly/XSyPG5" title="Grand Deluxe" target="_blank" style="text-decoration: none;"><span id="GD">Grand Deluxe</span></a> <a href="http://bit.ly/XSyPG5" title="Grand Pool Villa" target="_blank" style="text-decoration: none;"><span id="GPV">Grand Pool Villa</span></a> </div> <div id="Content" class="content">Situated on a hill, Ayara Kamala offers a beautiful garden and ocean view rooms. The place of the hotel provides quiet, calm and romantic holiday away from all other hotels on Kamala Beach. <br /> <br /> Big size of rooms, king size beds and impressive bathrooms, are making Ayara Kamala perfect selection for couples who are looking for privacy and relaxing holiday. </div> <table class="table" style="border-collapse: separate; border-spacing: 1px;" width="625" border="0"> <tr> <td align="right" style="padding-left: 20px;" width="302"><a href="http://bit.ly/XSyPG5" title="Book Now !"><img src="http://i1300.photobucket.com/albums/ag93/dobriyan/E-mail%20-%20Ayara%20Kamala/BP_zps15c948a1.png" border="0px" alt="Best Rate"/></a></td> <td width="321" valign="top"><table class="TD" style="border-collapse: separate; border-spacing: 0px;" border="0px"> <tr> <td height="30" class="res" align="center"><a href="http://bit.ly/XSyPG5" title="B2B Online Booking"><span>www.b2b.onlyonetour.com</span></a></td> </tr> <tr> <td class="res" height="30" align="center"><span>Tel : (66) 02 - 688 - 8883 </span> </td> </tr> <tr> <td class="res" height="30" align="center"><a href="mailto:[email protected]" title="E-mail Reservation"><span>[email protected]</span></a></td> </tr></table> </td> </tr> </table> <div align="center" id="Right"><a style="text-decoration: none;" href="http://bit.ly/XSyPG5" title="Only One Tour &amp; Travel Group Co., Ltd." target="_blank"><img width="149px" height="90px" src="http://i1300.photobucket.com/albums/ag93/dobriyan/E-mail%20-%20Ayara%20Kamala/logoOOT_zps24c21653.png" border="0px" alt="Logo" /></a> <a style="text-decoration: none;" href="http://bit.ly/XSyPG5" title="Only One Tour &amp; Travel Group Co., Ltd." target="_blank"><span class="OOT">Only One Tour &amp; Travel<br />Group Co., Ltd.</span></a><br /><br /> <a style="text-decoration: none;" href="http://on.fb.me/XXqq56" title="Only One Tour Facebook Page" target="_blank"> <img src="http://i1300.photobucket.com/albums/ag93/dobriyan/E-mail%20-%20Ayara%20Kamala/facebook-logo-png-format-i18_zps83b6a9aa.png" width="145px" height="50px" border="0px" alt="FB"/></a><br /><br /> <span class="adress">2128/9-11 Charoenkung Rd.,</span><br /> <span class="adress">Watprayakrai, Bangkorleam,</span><br /> <span class="adress">10120 Bangkok, Thailand.</span><br /> <a class="adress" href="http://bit.ly/XSyPG5" target="_blank">www.b2b.onlyonetour.com</a><br /> <a class="adress" href="http://on.fb.me/XXqq56" target="_blank">www.onlyonetour.com (offline)</a> </div> </div> </body> </html> A: Now add <div align="center"></div> only for newsletter as like this <div align="center"> <img style="position: relative;" src="http://i1300.photobucket.com/albums/ag93/dobriyan/E-mail%20-%20Ayara%20Kamala/BK_zpsa93ab347.png" alt="Background" /> </div> <div id="Container" align="center"> // your code </div>
{ "pile_set_name": "StackExchange" }
Q: Python sock.listen(...) All the examples I've seen of sock.listen(5) in the python documentation suggest I should set the max backlog number to be 5. This is causing a problem for my app since I'm expecting some very high volume (many concurrent connections). I set it to 200 and haven't seen any problems on my system, but was wondering how high I can set it before it causes problems.. Anyone know? Edit: Here's my accept() loop. while True: try: self.q.put(sock.accept()) except KeyboardInterrupt: break except Exception, e: self.log("ERR %s" % e) A: You don't need to adjust the parameter to listen() to a larger number than 5. The parameter controls how many non-accept()-ed connections are allowed to be outstanding. The listen() parameter has no bearing on the number of concurrently connected sockets, only on the number of concurrent connections which have not been accept()-ed by the process. If adjusting the parameter to listen() has an impact on your code, that is a symptom that too much delay occurs between each call to accept(). You would then want to change your accept() loop such that it has less overhead. In your case, I am guessing that self.q is a python queue, in which case you may want to call self.q.put_nowait() to avoid any possibility of blocking the accept() loop at this call. A: The doc say this socket.listen(backlog) Listen for connections made to the socket. The backlog argument specifies the maximum number of queued connections and should be at least 1; the maximum value is system-dependent (usually 5). Obviously the system value is more than 5 on your system. I don't see why setting it to a larger number would be a problem. Perhaps some memory is reserved for each queued connection. My linux man page has this to say If the backlog argument is greater than the value in /proc/sys/net/core/somaxconn, then it is silently truncated to that value; the default value in this file is 128. In kernels before 2.4.25, this limit was a hard coded value, SOMAXCONN, with the value 128.
{ "pile_set_name": "StackExchange" }
Q: IOS - the 5th and 6th tabBar option In my tabBar app I have a navigation bar at the top of the views. However I have more than 4 tabBars and therefore the TableView with the option to choose the others comes up. Is there anyway to hide the navigation of the first 4 views if an end user decides to change their order? I was kind of thinking something like this, however the if statement in this code is not right. if([[self.tabBarController viewControllers] objectAtIndex:5]) { [_navBar setHidden:YES]; } else { [_navBar setHidden:NO]; } A: Another option you might entertain if you are worried about the user re-ordering your tabs is to create a custom MoreViewController (and have no re-ordering). See this SO answer.
{ "pile_set_name": "StackExchange" }
Q: Retrieving Phone Numbers that are not deleted from the Android Contact List I am trying to retrieve phone numbers from the ContactsContract that are not marked to be deleted. @Override public Loader onCreateLoader(int id, Bundle args) { return new CursorLoader( this, ContactsContract.CommonDataKinds.Phone.CONTENT_URI, new String[]{ ContactsContract.CommonDataKinds.Phone.NUMBER }, ContactsContract.CommonDataKinds.Phone.DELETED + "==0", null, null); } However, I am getting below error: java.lang.RuntimeException: An error occured while executing doInBackground() at android.os.AsyncTask$3.done(AsyncTask.java:304) at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355) at java.util.concurrent.FutureTask.setException(FutureTask.java:222) at java.util.concurrent.FutureTask.run(FutureTask.java:242) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587) at java.lang.Thread.run(Thread.java:818) Caused by: android.database.sqlite.SQLiteException: no such column: deleted (code 1): , while compiling: SELECT DISTINCT data1 FROM view_data data LEFT OUTER JOIN (SELECT data_usage_stat.data_id as STAT_DATA_ID, SUM(data_usage_stat.times_used) as times_used, MAX(data_usage_stat.last_time_used) as last_time_used FROM data_usage_stat GROUP BY data_usage_stat.data_id) as data_usage_stat ON (STAT_DATA_ID=data._id) WHERE (1 AND mimetype_id=5) AND ((deleted==0)) at android.database.DatabaseUtils.readExceptionFromParcel(DatabaseUtils.java:181) at android.database.DatabaseUtils.readExceptionFromParcel(DatabaseUtils.java:137) at android.content.ContentProviderProxy.query(ContentProviderNative.java:421) at android.content.ContentResolver.query(ContentResolver.java:478) at android.content.CursorLoader.loadInBackground(CursorLoader.java:64) at android.content.CursorLoader.loadInBackground(CursorLoader.java:42) at android.content.AsyncTaskLoader.onLoadInBackground(AsyncTaskLoader.java:312) at android.content.AsyncTaskLoader$LoadTask.doInBackground(AsyncTaskLoader.java:69) at android.content.AsyncTaskLoader$LoadTask.doInBackground(AsyncTaskLoader.java:57) at android.os.AsyncTask$2.call(AsyncTask.java:292) at java.util.concurrent.FutureTask.run(FutureTask.java:237) The documentation for ContactsContract.CommonDataKinds.Phone.CONTENT_URI states that the data records will be combined with the associated raw contact and aggregate contact data. But "deleted" is not there. Why and how can I get only the phone numbers that are not deleted? A: The Data URI projection does not have the DELETED column, in any case your query should only retrieve the phone numbers of the contacts which are not deleted. Are you able to get phone numbers of deleted raw contacts?
{ "pile_set_name": "StackExchange" }
Q: AdaCore : importing packages e.g.'Display' can someone advise on how to import the 'Display' packages to GPS community edition? [YouTube: AdaCore Lesson#2]https://youtube.com/watch?v=3jtOFle5K_c A: They are part of the Game_Support library found here.
{ "pile_set_name": "StackExchange" }
Q: Table with clustered index implicitly sorting by unique nonclustered index I have a table that captures the host platform that a user is running on. The table's definition is straightforward: IF OBJECT_ID('[Auth].[ActivityPlatform]', 'U') IS NULL BEGIN CREATE TABLE [Auth].[ActivityPlatform] ( [ActivityPlatformId] [tinyint] IDENTITY(1,1) NOT NULL ,[ActivityPlatformName] [varchar](32) NOT NULL ,CONSTRAINT [PK_ActivityPlatform] PRIMARY KEY CLUSTERED ([ActivityPlatformId] ASC) ,CONSTRAINT [UQ_ActivityPlatform_ActivityPlatformName] UNIQUE NONCLUSTERED ([ActivityPlatformName] ASC) ) ON [Auth]; END; GO The data it stores is enumerated based on a JavaScript method that uses information from their browser (I don't know much more than that, but could find out if needed): When I perform a basic SELECT without an explicit ORDER BY, however, the Execution Plan shows that it is using the UNIQUE NONCLUSTERED index in order to sort instead of the CLUSTERED index. SELECT * FROM [Auth].[ActivityPlatform] When explicitly specifying the ORDER BY, it correctly sorts by ActivityPlatformId. SELECT * FROM [Auth].[ActivityPlatform] ORDER BY [ActivityPlatformId] DBCC SHOWCONTIG('[Auth].[ActivityPlatform]') WITH ALL_LEVELS, TABLERESULTS shows no table fragmentation. What am I missing that could cause for this? I thought so long that the table was created on a clustered index, it should automatically sort by it implicitly without need to specify ORDER BY. What is SQL Server's preference in choosing the UQ? Is there something I need to specify in the table's creation? A: No, sorting is not implicit and should not be relied upon. In fact, in the first tooltip, you can see that it is explicitly stated that Ordered = False. This means SQL Server didn't do anything at all to implement any sorting. What you observe is just what it happened to do, not what it tried to do. If you want to be able to predict a reliable sort order, type out the ORDER BY. Period. What you might observe when you don't add ORDER BY might be interesting, but it cannot be relied upon to behave consistently. In fact in this post, see #3, I show how a query's output can change simply by someone else adding an index. T-SQL Tuesday #56 : Assumptions What is SQL Server's preference in choosing the UQ? The UNIQUE NONCLUSTERED index contains the clustering key, so it is covering for the query. In this case, your table only has two columns, so the clustered and nonclustered indexes contain the same data (just sorted differently). They're both the same size, so the optimizer could choose either. That it chooses the nonclustered index is an implementation detail. I call this a "coin flip."
{ "pile_set_name": "StackExchange" }
Q: aggregate over certain rows between matrices Let's say I have species-habitat abundance matrices sampled in time. I am trying to find a neat way to to aggregate over temporal replicates, creating a single species abundances matrix. # Construct dummy data mat1<-matrix(c(1,3,0,2,0,0,6,0,10,1), ncol=5, nrow=2) mat2<-matrix(c(0,11,0,0,1,0,2,3,7,1), ncol=5, nrow=2) mat3<-matrix(c(2,1,0,0,3,1,1,0,4,0), ncol=5, nrow=2) colnames(mat1) <-c('sp1','sp2','sp3','sp4','sp5') rownames(mat1) <- c('h1','h2') colnames(mat2) <-c('sp1','sp2','sp3','sp4','sp5') rownames(mat2) <- c('h1','h2') colnames(mat3) <-c('sp1','sp2','sp3','sp4','sp5') rownames(mat3) <- c('h1','h2') # Special case when new species occur mat4 <- matrix(c(2,1,0,0,3,1,1,0,4,0,6,3), ncol=6, nrow=2) colnames(mat4) <-c('sp1','sp2','sp3','sp4','sp5','sp6') rownames(mat4) <- c('h1','h2') # Replicate matrices are within a list l.mat<-list(mat1,mat2,mat3,mat4) My first thought was to use apply(margin=2)(but then again, the matices are within a list, lapply?) and colSums but I have not find a way not to sum over rows (habitat) within each matrix, but rather between, as seen below. Also when a new species occur, it should appear in the aggregated matrix # Desired output # Aggregated matrix sp1 sp2 sp3 sp4 sp5 sp6 h1 5 0 7 10 25 6 h2 16 2 2 3 2 3 Any pointers would be very much appreciated, thanks! A: This is pretty direct to do if you use the "reshape2" package: library(reshape2) allMat <- do.call(rbind, lapply(l.mat, melt)) dcast(allMat, X1 ~ X2, fun.aggregate=sum) # X1 sp1 sp2 sp3 sp4 sp5 sp6 # 1 h1 5 0 7 10 25 6 # 2 h2 16 2 2 3 2 3 Or, now that I think of it (since there's a melt method for lists, you can just do: dcast(melt(l.mat), X1 ~ X2, value.var="value", fun.aggregate=sum) If you want to stick with base R, I haven't found anything quite as direct. Here are two ways I came up with that's along the same lines as above: Base option 1 allMat <- do.call(rbind, lapply(l.mat, function(x) cbind(id = rownames(x), stack(data.frame(x))))) xtabs(values ~ id + ind, data = allMat) # ind # id sp1 sp2 sp3 sp4 sp5 sp6 # h1 5 0 7 10 25 6 # h2 16 2 2 3 2 3 Base option 2 allMat <- do.call(rbind, lapply(l.mat, function(x) { cbind(expand.grid(dimnames(x)), value = as.vector(x)) })) allMat xtabs(value ~ Var1 + Var2, allMat) # Var2 # Var1 sp1 sp2 sp3 sp4 sp5 sp6 # h1 5 0 7 10 25 6 # h2 16 2 2 3 2 3
{ "pile_set_name": "StackExchange" }
Q: MVC Route ASP.NET that had custom URL My old asp.net page had this kind of URL localhost/Product/This-Is-The-Name-Of-The-Product/Item123.aspx where the product ID would be 123, which I would get and then pass it along to the routing engine to grab the right data from the database and then display the page. localhost/Product/This-Is-The-Name-Of-The-Product/Item456.aspx would get product id of 456. I'm rewriting the website in MVC and I was wondering if someone could tell me how I would do a route so that it would be backwards compatible and localhost/Product/This-Is-The-Name-Of-The-Product/Item123.aspx would go to localhost/Product/123 I'm using MVC 5 BTW. A: U can use 2 routes together: routes.MapRoute( //for localhost/Product/This-Is-The-Name-Of-The-Product/Item456.aspx name: "", url: "Product/{ProductName}/item{id}.aspx", defaults: new { controller = "Product", action = "Index", id= UrlParameter.Optional } ); routes.MapRoute( //this url for localhost/Product/123 name: "", url: "Product/{id}", defaults: new { controller = "Product", action = "Index", id = UrlParameter.Optional } );
{ "pile_set_name": "StackExchange" }