text
stringlengths
64
81.1k
meta
dict
Q: Wrap XML tags on long list of items? I have a long list of languages and I need to wrap them with XML tags. My list looks like this: Afrikaans Albanian Arabic Azerbaijani Basque Bengali ... and so on. I need to wrap the with <item> tags like this: <item>Afrikaans</item> <item>Albanian</item> <item>Arabic</item> Is there any tool online or in Android Studio? I couldn't find any. A: Assuming that you want to modify the file manually, you can use regular expression and find and replace way. The regular expression is ^(\w+)$ and the replace string <item>\1</item>. This works in Notepad++ You need slightly different replace string in Android studio. It should be '$1' The search expression I provided works if the string is each line does not have spaces at the end. If you have spaces in strings, you can use the expression '^(\w+)(\s*)$'
{ "pile_set_name": "StackExchange" }
Q: Replace R1C1 type formula to a named range formula in Excel-VBA? I have a working VBA code (on Sheet2) that uses a Public Function to do a calculation using data on Sheet1, column B. After I use the FillDown function to get a similar calculation for the rest of the rows. Range("B2").FormulaR1C1 = "=PERSONAL.XLSB!Scoring(Sheet1!RC2)" Range("B2:B2", "A" & Cells(Rows.Count, 1).End(xlUp).Row).FillDown Public Function checks the cell and assigns a score according to the value found. Public Function Scoring(str As String) Dim check As Integer check_str = 0 If str = "US" Then check_str = 1 If check_str = 1 Then Scoring = "1" If check_str = 0 Then Scoring = "0" End Function My goal is to use Named Ranges instead of R1C1 formula style to avoid any complications if the Sheet1 column order is changed. I guess there are possibilities to loop through the named ranges, but are there any simpler ways? The code that would be the simple approach to the issue (just replacing the R1C1 type with a reference to the column in a named range), does not work: Range("B2").Formula = "=PERSONAL.XLSB!Scoring(Sheet1!Range("myRange").Columns(1))" Range("B2:B2", "A" & Cells(Rows.Count, 1).End(xlUp).Row).FillDown A: If the named range has workbook scope, your formula would be: "=PERSONAL.XLSB!Function(INDEX(myRange,0,1))" to refer to the first column of that range. If the name has worksheet scope, then use Sheet1!myRange in the formula. A: This code works with the FillDown: Range("B2").Formula = "=PERSONAL.XLSB!Scoring(INDEX(Sheet!myRange,ROWS($A$1:$A1),1))" Range("B2:B2", "A" & Cells(Rows.Count, 1).End(xlUp).Row).FillDown
{ "pile_set_name": "StackExchange" }
Q: Adding item to keychain using Swift I'm trying to add an item to the iOS keychain using Swift but can't figure out how to type cast properly. From WWDC 2013 session 709, given the following Objective-C code: NSData *secret = [@"top secret" dataWithEncoding:NSUTF8StringEncoding]; NSDictionary *query = @{ (id)kSecClass: (id)kSecClassGenericPassword, (id)kSecAttrService: @"myservice", (id)kSecAttrAccount: @"account name here", (id)kSecValueData: secret, }; OSStatus = SecItemAdd((CFDictionaryRef)query, NULL); Attempting to do it in Swift as follows: var secret: NSData = "Top Secret".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false) var query: NSDictionary = [ kSecClass: kSecClassGenericPassword, kSecAttrService: "MyService", kSecAttrAccount: "Some account", kSecValueData: secret ] yields the error "Cannot convert the expression's type 'Dictionary' to 'DictionaryLiteralConvertible'. Another approach I took was to use Swift and the - setObject:forKey: method on a Dictionary to add kSecClassGenericPassword with the key kSecClass. In Objective-C: NSMutableDictionary *searchDictionary = [NSMutableDictionary dictionary]; [searchDictionary setObject:(id)kSecClassGenericPassword forKey:(id)kSecClass]; In the Objective-C code, the CFTypeRef of the various keychain item class keys are bridged over using id. In the Swift documentation it's mentioned that Swift imports id as AnyObject. However when I attempted to downcast kSecClass as AnyObject for the method, I get the error that "Type 'AnyObject' does not conform to NSCopying. Any help, whether it's a direct answer or some guidance about how to interact with Core Foundation types would be appreciated. EDIT 2 This solution is no longer valid as of Xcode 6 Beta 2. If you are using Beta 1 the code below may work. var secret: NSData = "Top Secret".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false) let query = NSDictionary(objects: [kSecClassGenericPassword, "MyService", "Some account", secret], forKeys: [kSecClass,kSecAttrService, kSecAttrAccount, kSecValueData]) OSStatus status = SecItemAdd(query as CFDictionaryRef, NULL) To use Keychain Item Attribute keys as dictionary keys you have to unwrap them by using either takeRetainedValue or takeUnretainedValue (as appropriate). Then you can cast them to NSCopying. This is because they are CFTypeRefs in the header, which aren't all copyable. As of Xcode 6 Beta 2 however, this causes Xcode to crash. A: You simply need to downcast the literal: let dict = ["hi": "Pasan"] as NSDictionary Now dict is an NSDictionary. To make a mutable one, it's very similar to Objective-C: let mDict = dict.mutableCopy() as NSMutableDictionary mDict["hola"] = "Ben" A: In the xcode 6.0.1 you must do this!! let kSecClassValue = NSString(format: kSecClass) let kSecAttrAccountValue = NSString(format: kSecAttrAccount) let kSecValueDataValue = NSString(format: kSecValueData) let kSecClassGenericPasswordValue = NSString(format: kSecClassGenericPassword) let kSecAttrServiceValue = NSString(format: kSecAttrService) let kSecMatchLimitValue = NSString(format: kSecMatchLimit) let kSecReturnDataValue = NSString(format: kSecReturnData) let kSecMatchLimitOneValue = NSString(format: kSecMatchLimitOne) A: Perhaps things have improved since. On Xcode 7 beta 4, no casting seems to be necessary except when dealing with the result AnyObject?. Specifically, the following seems to work: var query : [NSString : AnyObject] = [ kSecClass : kSecClassGenericPassword, kSecAttrService : "MyAwesomeService", kSecReturnAttributes : true, // return dictionary in result parameter kSecReturnData : true // include the password value ] var result : AnyObject? let err = SecItemCopyMatching(query, &result) if (err == errSecSuccess) { // on success cast the result to a dictionary and extract the // username and password from the dictionary. if let result = result as ? [NSString : AnyObject], let username = result[kSecAttrAccount] as? String, let passdata = result[kSecValueData] as? NSData, let password = NSString(data:passdata, encoding:NSUTF8StringEncoding) as? String { return (username, password) } } else if (status == errSecItemNotFound) { return nil; } else { // probably a program error, // print and lookup err code (e.g., -50 = bad parameter) } To add a key if it was missing: var query : [NSString : AnyObject] = [ kSecClass : kSecClassGenericPassword, kSecAttrService : "MyAwesomeService", kSecAttrLabel : "MyAwesomeService Password", kSecAttrAccount : username, kSecValueData : password.dataUsingEncoding(NSUTF8StringEncoding)! ] let result = SecItemAdd(query, nil) // check that result is errSecSuccess, etc... A few things to point out: your initial problem might have been that str.dataUsingEncoding returns an Optional. Adding '!' or better yet, using an if let to handle nil return, would likely make your code work. Printing out the error code and looking it up in the docs will help a lot in isolating the problem (I was getting err -50 = bad parameter, until I noticed a problem with my kSecClass, nothing to do with data types or casts!).
{ "pile_set_name": "StackExchange" }
Q: Regex specific question and search function on my website dealing with broken links I've been trying to figure out my regex pattern but it doesn't seem to be working for me. Here's what i'm trying to do: I have broken links on my website if someone accidentally gets to a page like so: https://example.com/catalogsearch/result/?q= or https://example.com/catalogsearch/result/ So i'm redirecting them back to my homepage. The problem is now the search is just sending everything back to the homepage. So i'm assuming if there is something after the equals it needs to continue the search.. obviously https://example.com/catalogsearch/result/?q=person but currently i can't figure this out.. Here is my regex that i've been messing with for quite sometime now... still seems to be wrong or something else is wrong with my search. "^/catalogsearch/result((/)|(/\\?)|(/\\?[a-z])|(/\\?[a-z]=))?$" Please forgive me i'm horrible with regex. A: After a lot of discussion, it is concluded that the routes.yaml will consider the url path as a valid route but not the query string part. Hence out of the two examples in the post, you can use "/catalogsearch/result": { to: "https://example.com/", prefix: false } and for other one please change it in nginx config to redirect to homepage or if its not possible then check with magento support on how to incorporate the query string part in routes.yaml file.
{ "pile_set_name": "StackExchange" }
Q: clojure.data.json/write: application of predicate to determine value quoting Suppose I have a simple map, example-map: (def example-map {"a" "b" "c" "d"}) I can use clojure.data.json/write-str to JSON-ify this map as such: (clojure.data.json/write-str example-map) => "{\"a\":\"b\",\"c\":\"d\"}" I would like to apply a predicate to all keys to determine if that key is quoted, even if the output is invalid JSON. The desired function would work as follows: (defn to-quote? [v] (= v "d")) (fictional-write-str example-map :quote-rule to-quote?) => "{\"a\":\"b\",\"c\":d}" Might the optional :value-fn parameter to clojure.data.json/write-json offer what I'm describing? A: write-str works via protocol JSONWriter, which you can extend with, say, clojure.lang.Symbol and have you own way. (ns reagenttest.main (:refer-clojure :exclude (read)) (:require [clojure.data.json :as json])) (defn- write-named [x out] (.print out (name x))) (extend clojure.lang.Symbol json/JSONWriter {:-write write-named}) (prn (json/write-str {"a" 'd "b" "c" "e" :key})) shows "{\"a\":d,\"b\":\"c\",\"e\":\"key\"}"
{ "pile_set_name": "StackExchange" }
Q: Get distinct days from a collection of dates in MongoDB I want to populate a date range picker display with highlighted cells where data exists in my database. I thus need to reduce my collection to an array of dates where records exist e.g. // collection [{ timestamp: ISODate("2020-01-28T20:42:00.000Z"), data: 1, },{ timestamp: ISODate("2020-01-28T18:42:00.000Z"), data: 10, },{ timestamp: ISODate("2020-01-28T15:42:00.000Z"), data: 100, },{ timestamp: ISODate("2020-01-25T15:42:00.000Z"), data: 1000, },{ timestamp: ISODate("2020-01-17T15:42:00.000Z"), data: 10000, }] reduces to: ['2020-01-28', '2020-01-25', '2020-01-17'] The nature of the data stored in my database means that if any data exists on a given date, lots of data exists on that date. It is therefore slow to query the entire collection for a given date range and then reduce the result. Is there a fast(er) way to query a collection to return the distinct set of dates on which data exists? A: As I know you can only get json format result from mongodb query. I could get the following result, which can be easily converted to the string array in javascript code: [ { "_id": "20200125" }, { "_id": "20200117" }, { "_id": "20200128" } ] I used $dateToString aggregation operator inside $project stage. db.collection.aggregate([ { $project: { _id: 0, date: { $dateToString: { format: "%Y%m%d", date: "$timestamp" } } } }, { $group: { _id: "$date" } } ]) Playground
{ "pile_set_name": "StackExchange" }
Q: Add class "copyMe" and enable button, apply the same behavior for checkboxes I've a code where I add a class copyMe and also toggle button enabled if at least one of the checkboxes is changed (checked/unchecked), this is the code behind that behavior: // Enable button #btnAplicarNorma and add copyMe class when any of the checkbox changes $('#resultadoNormaBody').on('change', 'input[type=checkbox]', function () { var $my_checkbox = $(this); var $my_tr = $my_checkbox.closest('tr'); if ($my_checkbox.prop('checked')) { $my_tr.addClass('copyMe'); } var $all_checkboxes = $my_checkbox.closest('tbody').find('input[type=checkbox]'); $all_checkboxes.each(function () { if ($(this).prop('checked')) { $('#btnAplicarNorma').prop('disabled', false); return false; } $('#btnAplicarNorma').prop('disabled', true); }); }); Now I'm trying to apply the same behavior but this time for a checkbox that toggle all checkboxes and I'm doing something wrong since I don't get any set of matches elements on $all_checkboxes var. This is the code I'm trying for this one: // Enable button #btnAplicarNorma and add copyMe class when #toggleCheckboxNorma changes $('#resultadoNorma').on('change', '#toggleCheckboxNorma', function () { var $my_checkbox = $(this); var $all_checkboxes = $my_checkbox.closest('tbody').find('input[type=checkbox]'); console.log($my_checkbox); console.log($all_checkboxes); $all_checkboxes.each(function () { if ($(this).prop('checked')) { $(this).closest('tr').addClass('copyMe'); $('#btnAplicarNorma').prop('disabled', false); return false; } $(this).closest('tr').removeClass('copyMe'); $('#btnAplicarNorma').prop('disabled', true); }); }); I tried also changing this line: var $all_checkboxes = $my_checkbox.closest('tbody').find('input[type=checkbox]'); to this: var $all_checkboxes = $('#resultadoNorma').closest('tbody').find('input[type=checkbox]'); But I got the same, so the idea is when I change #toggleCheckboxNorma all the tr should get the class copyMe and also #btnAplicarNorma should be enable if it's the contrary I should go back and remove the class and also disabled back the button. Here is a fiddle with code example. Take care, in the fiddle all the content is loaded by default but in my code TR are generated dynamically by a Ajax call, what I'm doing wrong? A: I think the problem is your function marcarTodosCheck() is interrupting. Add .trigger("change") after altering the property, as below. Is this your desired result? See example: http://jsfiddle.net/ot96p9mL/5/ function marcarTodosCheck(selChk, tableBody) { $(selChk).on('click', function () { var $toggle = $(this).is(':checked'); $(tableBody).find("input:checkbox").prop("checked", $toggle).trigger("change"); }); $(tableBody).find("input:checkbox").on('click', function () { if (!$(this).is(':checked')) { $(selChk).prop("checked", false).trigger("change"); } else if ($(tableBody).find("input:checkbox").length == $(tableBody).find("input:checkbox:checked").length) { $(selChk).prop("checked", true).trigger("change"); } }); }
{ "pile_set_name": "StackExchange" }
Q: Numpy: improve fancy indexing on arrays Looking for faster fancy indexing for numpy, the code I am running slows down, at np.take(). I tried order=F/C with np.reshape(), no improvement. Python operator works well without the double transpose, but with them is equal to np.take(). p = np.random.randn(3500, 51) rows = np.asarray(range(p.shape[0])) cols = np.asarray([1,2,3,4,5,6,7,8,9,10,15,20,25,30,40,50]) %timeit p[rows][:, cols] %timeit p.take(cols, axis = 1 ) %timeit np.asarray(operator.itemgetter(*cols)(p.T)).T 1000 loops, best of 3: 301 µs per loop 10000 loops, best of 3: 132 µs per loop 10000 loops, best of 3: 135 µs per loop A: A test of several options: In [3]: p[rows][:,cols].shape Out[3]: (3500, 16) In [4]: p[rows[:,None],cols].shape Out[4]: (3500, 16) In [5]: p[:,cols].shape Out[5]: (3500, 16) In [6]: p.take(cols,axis=1).shape Out[6]: (3500, 16) time tests - plain p[:,cols] is fastest. Use a slice where possible. In [7]: timeit p[rows][:,cols].shape 100 loops, best of 3: 2.78 ms per loop In [8]: timeit p.take(cols,axis=1).shape 1000 loops, best of 3: 739 µs per loop In [9]: timeit p[rows[:,None],cols].shape 1000 loops, best of 3: 1.43 ms per loop In [10]: timeit p[:,cols].shape 1000 loops, best of 3: 649 µs per loop I've seen itemgetter used for lists, but not arrays. It's a class that iterates of a set of indexes. These 2 lines are doing the same thing: In [23]: timeit np.asarray(operator.itemgetter(*cols)(p.T)).T.shape 1000 loops, best of 3: 738 µs per loop In [24]: timeit np.array([p.T[c] for c in cols]).T.shape 1000 loops, best of 3: 748 µs per loop Notice that p.T[c] is p.T[c,:] or p[:,c].T. With relatively few cols, and by ignoring advanced indexing with rows, it times close to p[:,cols].
{ "pile_set_name": "StackExchange" }
Q: Gridview paging in ModalPopupExtender strange behaviour I have a modalpopypextender that contains a grid view and I want populate it on button click which does this: protected void btnViewRecipients_Click(object sender, EventArgs e) { ModalPopupExtender1.Show(); BindData(); } Which is straight forward. BindData does this: protected void BindData() { try { SqlCommand sqlCommand = new SqlCommand(); string connectionString = "Data Source=SERVER\\DB1;Initial Catalog=Survey;User ID=abcde;Password=12345;"; using (SqlConnection sqlConnection = new SqlConnection(connectionString)) { sqlCommand = sqlConnection.CreateCommand(); sqlCommand.CommandText = "Select * From [Survey].[dbo].[data]"; SqlDataAdapter sda = new SqlDataAdapter(sqlCommand.CommandText, connectionString); SqlCommandBuilder scb = new SqlCommandBuilder(sda); //Create a DataTable to hold the query results. //Fill the DataTable. sda.Fill(dTable); //Set the DataGridView DataSource. gvRecords.DataSource = dTable; gvRecords.DataBind(); sqlConnection.Close(); } } catch (SqlException ex) { //Console.WriteLine(ex.StackTrace); } } Now this all works good and I get to see the grid with data. I then turned on autopaging and went ahead to create the call gvRecords_PageIndexChanged. I have also turned on EnableSortingAndPagingCallbacks. protected void gvRecords_PageIndexChanging(object sender, GridViewPageEventArgs e) { gvRecords.PageIndex = e.NewPageIndex; gvRecords.DataSource = dTable; gvRecords.DataBind(); } This kinda works very strangely. I noticed that when I click a page number, the table becomes blank and shows me EmptyDataText that I defined earlier. But when I close the ModalPopupExtender and open it again (clicking the button again) it shows me the right page and data! e.g. if I clicked page 3, then get a blank table, now reopening the MPE will show me page 3's contents in a gridview. I guess that's the viewstate stored somewhere but why is it that the gridview will not show me the page right away? I am really stuck at this and failing to understand what I'm missing! Any help appreciated million times, I have searched and searched online for this but maybe it is so trivial and obvious that no one has ever needed to ask!?! A: I got it working finally, I have had to set PopupControlID to upModal, the updatepanel's ID, as opposed to the inner panel. The targetcontrolID also had to point to a hidden button, as many have found you must when working with MPEs... Anyway, here goes: <asp:Button ID="hiddenButton" runat="server" Text="" style="display:none;" /> <ajaxToolkit:ModalPopupExtender ID="ModalPopupExtender1" runat="server" Enabled="True" TargetControlID="hiddenButton" PopupControlID="upModal" BehaviorID="modalbehavior" BackgroundCssClass="modalBackground" OnCancelScript="cancelClick();" CancelControlID="closePopup"> </ajaxToolkit:ModalPopupExtender> <asp:UpdatePanel runat="server" ID="upModal" UpdateMode="Conditional"> <ContentTemplate> <asp:Panel id="pnlPopup" runat="server" class="ModalPanel" > <table cellpadding="5" cellspacing="5" class="topBanner" style="width:100%;"> <tr> <td width="50"> <asp:LinkButton ID="closePopup" runat="server" onclick="LinkButton1_Click" CssClass="ClosePopupCls">Close [x]</asp:LinkButton> </td> <td align="center"> <asp:Label ID="lbl" runat="server" Text="Status"></asp:Label> </td> <td width="25"> </td> </tr> <tr> <td colspan="3"> <asp:GridView ID="gvRecords" runat="server" AllowPaging="True" BackColor="White" EmptyDataText="No Record Found" EnableSortingAndPagingCallbacks="True" ForeColor="GrayText" Height="600" onpageindexchanging="gvRecords_PageIndexChanging" Width="800"> </asp:GridView> </td> </tr> </table> </asp:Panel> </ContentTemplate> </asp:UpdatePanel>
{ "pile_set_name": "StackExchange" }
Q: Is it possible to load an assembly targeting a different .NET runtime version in a new app domain? I've an application that is based on .NET 2 runtime. I want to add a little bit of support for .NET 4 but don't want to (in the short term), convert the whole application (which is very large) to target .NET 4. I tried the 'obvious' approach of creating an application .config file, having this: <startup useLegacyV2RuntimeActivationPolicy="true"> <supportedRuntime version="v4.0" /> </startup> but I ran into some problems that I noted here. I got the idea of creating a separate app domain. To test it, I created a WinForm project targeting .NET 2. I then created a class library targeting .NET 4. In my WinForm project, I added the following code: AppDomainSetup setup = new AppDomainSetup(); setup.ApplicationBase = "path to .NET 4 assembly"; setup.ConfigurationFile = System.Environment.CurrentDirectory + "\\DotNet4AppDomain.exe.config"; // Set up the Evidence Evidence baseEvidence = AppDomain.CurrentDomain.Evidence; Evidence evidence = new Evidence(baseEvidence); // Create the AppDomain AppDomain dotNet4AppDomain = AppDomain.CreateDomain("DotNet4AppDomain", evidence, setup); try { Assembly doNet4Assembly = dotNet4AppDomain.Load( new AssemblyName("MyDotNet4Assembly, Version=1.0.0.0, Culture=neutral, PublicKeyToken=66f0dac1b575e793")); MessageBox.Show(doNet4Assembly.FullName); } finally { AppDomain.Unload(dotNet4AppDomain); } My DotNet4AppDomain.exe.config file looks like this: <startup useLegacyV2RuntimeActivationPolicy="true"> <supportedRuntime version="v4.0" /> </startup> Unfortunately, this throws the BadImageFormatException when dotNet4AppDomain.Load is executed. Am I doing something wrong in my code, or is what I'm trying to do just not going to work? Thank you! A: You target the 2.0 so it is the one loaded in memory... they you ask it to load a 4.0 image... it can't work you need to spin a new Runtime instance of the correct version if you want to do that. The only way to do that may be to Host a second CLR inside your process like explained in Is it possible to host the CLR in a C program? witch became possible with .Net 4.0.
{ "pile_set_name": "StackExchange" }
Q: What is the iHDR process? I've seen references to the iHDR process. I would like to read a quick summary, but I'm not quite interested enough to watch a webinar. What is the basic idea of iHDR? A: Basically, iHDR is a method of blending the bracketed raw images using a variety of masked luminosity layers. As I understand it, it’s a series of steps for blending images, after refining and masking layers in each image, so as to produce results that represent what you saw in the original scene. This is all done manually, without using HDR software, in order that the photographer can just blend the areas of the images that he thinks needs it, rather than get the all over rather flat effect that some software can produce in some hands.
{ "pile_set_name": "StackExchange" }
Q: Stripping duplicate elements in a list of strings in elisp Given a list such as (list "foo" "bar" nil "moo" "bar" "moo" nil "affe") how would I build a new list with the duplicate strings removed, as well as the nils stripped, i.e. (list "foo" "bar" "moo" "affe") The order of the elements needs to be preserved - the first occurence of a string may not be removed. The lists I'm dealing with here are short, so there's no need to use anything like a hash table for the uniqueness check, although doing so certainly wouldn't hurt either. However, using cl functionality is not a viable option. A: Try "Sets and Lists" in the "Lists" section of the Emacs Lisp Reference Manual: (delq nil (delete-dups (list "foo" "bar" nil "moo" "bar" "moo" nil "affe"))) A: The Common Lisp package contains many list manipulation functions, in particular remove-duplicates. (require 'cl) (remove-duplicates (list "foo" "bar" nil "moo" "bar" "moo" nil "affe") :test (lambda (x y) (or (null y) (equal x y))) :from-end t) Yes, I realize you said you didn't want to use cl. But I'm still mentioning this as the right way to do it for other people who might read this thread. (Why is cl not viable for you anyway? It's been shipped with Emacs for about 20 years now, not counting less featured past incarnations.) A: If you use dash.el library, that's all you need: (-distinct (-non-nil '(1 1 nil 2 2 nil 3)) ; => (1 2 3) dash.el is written by Magnar Sveen and it's a great list manipulation library with many functions for all kinds of tasks. I recommend to install it if you write lots of Elisp code. Function -distinct removes duplicate elements in a list, -non-nil removes nil elements. While the above code is sufficient, below I describe an alternative approache, so feel free to ignore the rest of the post. -non-nil was added in version 2.9, so if for some reason you have to use earlier versions, another way to achieve the same is to use -keep with built-in identity function, which just returns whatever it is given: (identity 1) ; => 1. The idea is that -keep keeps only elements, for which the predicate returns true (“non-nil” in Lisp jargon). identity obviously returns non-nil only for whatever values that are not nil: (-distinct (-keep 'identity '(1 1 nil 2 2 nil 3)) ; => (1 2 3)
{ "pile_set_name": "StackExchange" }
Q: ODatabaseException: Database instance is not set in current thread I am new in OrientDB and use orientdb-community-1.7.4 version. I have two projects. Project A is used for manipulation with orientdb database (CRUD operation etc). Project B is a maven project (Liferay portlet) which includes Project A as a dependency. In project B I create new Edge object, which is persisted in database. Then I want to get this object from database: ApplicationContext appC = new ClassPathXmlApplicationContext("ApplicationContext.xml"); OrientDatabaseConnectionManager connMan = (OrientDatabaseConnectionManager) appC.getBean("orientConnectionManager"); OrientGraph graph = connMan.getGraph(); Edge edge = graph.getEdge("#37:20"); But I get this error. When I tried to get Edge object in Project A, I didn't get this error. com.orientechnologies.orient.core.exception.ODatabaseException: Database instance is not set in current thread. Assure to set it with: ODatabaseRecordThreadLocal.INSTANCE.set(db); at com.orientechnologies.orient.core.db.ODatabaseRecordThreadLocal.get(ODatabaseRecordThreadLocal.java:31) at com.orientechnologies.orient.core.id.ORecordId.getRecord(ORecordId.java:293) at com.tinkerpop.blueprints.impls.orient.OrientBaseGraph.getEdge(OrientBaseGraph.java:840) OrientDatabaseConnectionManager.java (Project A) package persistence.graphdb.graphDBConnectionInit; import com.tinkerpop.blueprints.impls.orient.OrientGraph; import com.tinkerpop.blueprints.impls.orient.OrientGraphFactory; /** * Class manages connection to the graph database. * See http://www.orientechnologies.com/docs/1.7.8/orientdb.wiki/Java-Tutorial:-Introduction.html * for the graph database instantiation */ public class OrientDatabaseConnectionManager { private OrientGraphFactory factory; public OrientDatabaseConnectionManager(String path, String name, String pass) { factory = new OrientGraphFactory(path, name, pass).setupPool(1,10); } /** * Method returns graph instance from the factory's pool. * @return */ public OrientGraph getGraph(){ return factory.getTx(); } } ApplicationContext.xml (Project A) <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:util="http://www.springframework.org/schema/util" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.1.xsd"> <context:property-placeholder properties-ref="graphDbProperties"/> <util:properties id="graphDbProperties"> <prop key="orientEmbeddedDbPath">plocal:/Users/and/orientdb-community-1.7.4/databases/graphDb</prop> <prop key="orientName">admin</prop> <prop key="orientPass">admin</prop> </util:properties> <!-- ORIENT DB config --> <bean id="orientConnectionManager" class="persistence.graphdb.graphDBConnectionInit.OrientDatabaseConnectionManager"> <constructor-arg index="0" value="${orientEmbeddedDbPath}"/> <constructor-arg index="1" value="${orientName}"/> <constructor-arg index="2" value="${orientPass}"/> </bean> </beans> A: I think this is a bug in orientdb, because when I tried it on 32-bit Windows 7, it works, but on OS X I get this error. This solution works also on OSX.
{ "pile_set_name": "StackExchange" }
Q: Create a local wireless without internet I would like to create a local wireless without internet. I would like to have the possibility to connect 50 clients and access to a website using a domain name. That means, I need a DNS and DHCP. I sreach on internet an I found a way to achieve that but not totally and i am not sure if it will work and if it is the best way to achieve that. I can maybe have a mini PC (server) with ad hoc network and have the client to connect on the server but: Will it be possible on a connection to assign a ip to the client and set a DNS server ip on the client as the same ip of the server. I found mini PCs but how can I know if the PC will handle a lot of client ? Which network card to choose ? I think also that a router and configure DHCP on it to distribute the IPs but I would like to have one box ready object as a mini PC. I need an advice on the best way to go with what i want to achieve and materials i need to buy and good references. A: For a linux domain controler you will need to install bind to host your own DNS. It's a little involved to set up, but necessary if your network doesn't have a DNS server. If you're using a windows domain controller you will need a server OS (expensive). If you only have 50 clients the DNS resources needed will be small and you could run bind from any old box, even a Raspberry Pi. You will also need a host machine for the "website" a.k.a. an intranet. This can be the same machine as your DNS server, but can be any computer on the network. When all is done you will have your router configured with the IP of your local DNS server. The DNS server will point your local domain to whatever box hosts the intranet website.
{ "pile_set_name": "StackExchange" }
Q: Cake PHP: Containable Behavior or Model Unbind - which is good for Optimizing Query in Cake PHP I'm working on a project based on Cake PHP.On that project recursive = 2 is used and that makes the application slow. Now I need To Optimize Some Query for slow response. For optimizing Query I can Follow two steps: 1. UnbindModel 2. Containable Behavior My Question is When I Should use Containable Behavior and when unbinding Models.I Think I need Some Clear Explanation From Cake PHP Expert. A: You should always be using either Containable or recursive=>'-1' Cache your queries when it's possible (when you're requesting the same data multiple times) Only ask for what you need using the fields parameter Add appropriate indexes to your MySQL database tables Those are just some of the quickest ways to optimizes your queries. There are also ways to optimize queries using bindModel for certain requests, or restructuring your tables in certain ways, but those are very situation-specific.
{ "pile_set_name": "StackExchange" }
Q: Compilar Jar sin librerías externas incluidas Necesito compilar mi proyecto en Java a un .jar mediante un script ANT, pero quisiera que este no tome en cuenta las librerías externas porque me queda muy pesado; sino que estas queden en una carpeta externa al jar, por ejemplo en la carpeta dist/lib. A: Encontré la solución. Cada proyecto java tiene un archivo llamado build.xml allí hay un tag de la siguiente manera: <zipgroupfileset dir="dist/lib" includes="*.jar"/> que le indica al compilador que compile todas la librerías. Entonces comentando esa linea se genera un jar sin librerías (menos pesado). Ahora, para que funcione correctamente debe estar acompañado de la carpeta lib en donde se encuentran todos los jars de las librerías usadas en el proyecto.
{ "pile_set_name": "StackExchange" }
Q: Client side ssl in J2me? How can we implement client side SSL in J2ME? Any available resource or source code?? I want to validate the particular service is accessed by a particular phone. A: The bouncycastle Java libraries have a J2ME version (now called JME) that includes an SSL/TLS api.
{ "pile_set_name": "StackExchange" }
Q: Asking same question for newer version? @underdark wrote, in a much upvoted answer to the somewhat related Dealing with Q&As using deprecated/non-existent PyQGIS API functions?: I'm not a friend of having ten copies of the same question for ten QGIS versions because it makes it impossible to find and maintain answers. Today, Will core functions in QGIS exploit multi-threading?, first asked about QGIS 2.6, was re-asked for QGIS 3.0 as Will core functionality in QGIS 3.0 exploit multi-threading? Irrespective of the current status of the newer question, what do you think should happen to it? A: Even though the well-written, and interesting, new question contains new information, I think what we are trying to achieve is to have a "timeless" question that can nevertheless have multiple answers posted for multiple versions, so that our combined knowledge over time about that question is collected as answers in the same place. Ideally we would start with the "timeless" question that gets asked at a particular version, and then answers relevant to new versions can be added to it. However, once the question has been re-asked, I think the action to take is to: Vote to close the new question as a duplicate of the old Perform any necessary editing to ensure that merging the questions will read as a "timeless" question with multiple answers that each clearly indicates the version(s) it refers to. Merge (or flag a moderator asking them to merge) the new question into the old Suggest the asker change their Accept checkmark to one about the later version, if that is the answer that now helps them the most, so that it may be brought to the top and be read first. For the QGIS 2.6 and 3.0 questions linked at the beginning of this Meta question, I have already performed several small edits, to illustrate how the two Q&As may be made ready to be merged with minimal effort.
{ "pile_set_name": "StackExchange" }
Q: how do i use same sidenav in multiple pages So i created a sidenav on one of my page and its working properly there what i want to do is on another page i want to use that same sidenav. My side nav code: <form id="keyword-form" class="side-nav rt-side-nav"> <div> <center><h5>KEYWORDS</h5></center> <textarea rows="10" cols="50" id="txtarea" class="keyword-text" placeholder="enter comma seperated values for the products" contenteditable="true">{{keywords}}</textarea> </div> <div class="keyword-submit"> <center><button type="submit" class="key-submit btn waves-effect waves-light col m12">SUBMIT</button></center> </div> </form> <a data-activates="keyword-form" class="button-collapse"></a> <div hidden class="keyword"> </div> A: Wrap your navbar code in a template then use that template on each page. See example in the Meteor Todo app tutorial. Or if you are using Iron Router put it in your app body template. Template example: <template name="sidenav"> <form id="keyword-form" class="side-nav rt-side-nav"> <div> <center><h5>KEYWORDS</h5></center> <textarea rows="10" cols="50" id="txtarea" class="keyword-text" placeholder="enter comma seperated values for the products" contenteditable="true">{{keywords}}</textarea> </div> <div class="keyword-submit"> <center><button type="submit" class="key-submit btn waves-effect waves-light col m12">SUBMIT</button></center> </div> </form> <a data-activates="keyword-form" class="button-collapse"></a> <div hidden class="keyword"> </div> </template> Then every time you want to show your sidenav: {{> sidenav}}
{ "pile_set_name": "StackExchange" }
Q: Help need with formatting returned SQL data I've created a table which approximates to this: Fruit | Date Purchased | Amount Purchased ---------------------------------------------- Apples | 01-01-10 | 5 Oranges | 01-01-10 | 7 Apples | 02-01-10 | 3 Oranges | 02-01-10 | 2 etc.... I need to end up with the data in the following format though: Apples ( (01-01-10, 5), (02-01-10, 3) ) Oranges ( (01-01-10, 7), (02-01-10, 2) ) etc... The types of fruit are not fixed - more will be added over time, so this would be need to be taken into account. I've been stuck on this for quite a while now, so any pointers or tips would be really appreciated. A: You can loop through all all your records and add every row to the appropriate array: Something like: $fruits = array(); while ($row = get_new_database_row) /* depends on mysql, mysqli, PDO */ { $fruits[$row['fruit']][] = array($row['date'], $row['amount']); } Edit: Based on your codeigniter comments, you either need result_array() or you need to change $row['fruit'] to $row->fruit, $row['date'] to $row->date, etc.
{ "pile_set_name": "StackExchange" }
Q: Showing $S^2$ and $\overline{Y}$ are independent: seeking a solution to this textbook problem In An Introduction to Generalized Linear Models by Dobson and Barnett, exercise 1.4b&c is as follows: Let $Y_1,...,Y_n$ be independent random variables each with the distribution $N(\mu,\sigma^2)$. Let $\overline{Y}=\frac{1}{n}\sum_{i=1}^{n}Y_i$ and $S^2=\frac{1}{n-1}\sum_{i=1}^{n}(Y_i-\overline{Y})^2$. ... b. Show that $S^2 = \frac{1}{n-1}[\sum_{i=1}^{n}(Y_i-\mu)^2-n(\overline{Y}-\mu)^2]$ c. From (b) it follows that $\sum(Y_i-\mu)^2/\sigma^2 = (n-1)S^2/\sigma^2+[(\overline{Y}-\mu)^2n/\sigma^2]$. How does this allow you to deduce that $\overline{Y}$ and $S^2$ are independent? My problem is that I don't see how the equation in c allows me to answer the question in bold. I'm aware of how to prove the 2 being independent in general (it has been asked before). Moreover, when I look at the solutions they say: (c) and (d) follow from results on p.10 On page 10 the closest thing of use is the chi-square distribution's reproductive property, which isn't an if and only if statement, so I don't think it can be used here. So my question is, how does the equation in c) help to prove independence? A: I'm not sure what the authors have in mind, but the closest solution I can think of using (c) is to apply Cochran's theorem. Have you covered that, or maybe a special case of it? Here's the proof using that: Let $Z_i = \frac{Y_i - \mu}{\sigma}$ so $Z_i \sim \mathcal N(0, 1)$ and $\bar Z \sim \mathcal N(\mu, \sigma^2/n)$. Note that $$ \left(\frac{Y_i - \bar Y}{\sigma}\right)^2 = \left(\frac{Y_i - \mu}{\sigma} - \frac{\bar Y - \mu}{\sigma}\right)^2 = \left(Z_i - \bar Z\right)^2. $$ Now (c) tells us $$ \sum_i Z_i^2 = \sum_i (Z_i - \bar Z)^2 + n\bar Z^2 $$ which we can write as $\newcommand{\one}{\mathbf 1}$ $$ Z^T Z = Z^T \left(I - \frac 1n \one \one^T\right)Z + Z^T\left(\frac 1n \one \one^T\right) Z. $$ $I - \frac 1n \one \one^T + \frac 1n \one \one^T =I$ and both are idempotent so Cochran's theorem lets us conclude that $\sum_i (Y_i - \mu)^2 \perp n(\bar Y - \mu)^2$ and the rest follows. $\square$ Could that be what they're going for?
{ "pile_set_name": "StackExchange" }
Q: Approximate expression under square root Given $x>>1,$ how can the expression \begin{equation} \left(1-\frac{1}{4x^2}\right)^{1/2} \end{equation} be approximated to \begin{equation} \left(1-\frac{1}{8x^2}\right)? \end{equation} A: $$\begin{align} 1-\frac{1}{4x^2} &\approx 1-\frac{1}{4x^2}+\frac{1}{64x^4}\\ &= \left (1-\frac{1}{8x^2}\right)^2 \end{align}$$
{ "pile_set_name": "StackExchange" }
Q: How does the Install Port appear when a girl becomes a Reyvateil? So 3rd Generation Reyvateils are originally born as humans but if their mother was a Reyvateil they may develop into one later in life. From my understanding all Reyvateil have an install port surrounded by a tattoo and since Gathnode Crystals and Life Extending Agents are Physical Objects that get inserted into a Reyvateil with both being somewhat painful this would make it into a hole right? But i can't imagine how this hole appears. does the skin just open up one day? does a Reyvateil have to go under some procedure to have it made (ie. when they get their first Life Extending Agent) or is it a gradual process? A: From the data the Exa_Pico Wikia gathered form the agmes and the Toukoushpere (a segment where characters answered questions sent from users), it seems to be concluded that, after a server mistakenly recognizes a 3rd generation human as a Reyvateil, it begins a long process of correcting what it sees as a somehow ignored Reyvateil that ended up with irregular development, and starts using this human's memories ands senses to develop a soulspace. The process of developing this soulspace takes about ten days, in which the human enters a comatose state. At the end of the process, the human will have awakened as a Reyvateil, with a Install Port appearing in their body. So, the Insatll Port appears automatically, after a girl awakens as a Reyvateil. Unfortunatley, it is not clear of the Install Port is a hole, but from the way it is depicted, the symbol may work as a kind of portal for specific materials (data crystals).
{ "pile_set_name": "StackExchange" }
Q: Zeta regularization vs Dirichlet series Suppose you have a sequence of real numbers, denoted $a_n$. Then the sum of the sequence is $\sum_n a_n$ If this is divergent, we can use zeta regularization to get a sum. We can do this by defining the function $\zeta_A(s) = \sum_n a_n^{-s}$ and then analytically continue to the case where $s=-1$. A different approach is to define the Dirichlet series $A(s) = \sum_n \frac{a_n}{n^s}$ and then analytically continue to the case where $s=0$. $Questions:$ When these two approaches are both defined, are they guaranteed to agree on the result? If not, for which sequences do they agree? If they are compatible, is the second summation method strictly stronger than the first? For instance, it is clear that the first method can't do anything for the series $1+1+1+1+1+...$, whereas the second method yields -1/2, so it is at least as strong as the first. A: For $n \geqslant 1$, let $a_n = n + (-1)^{n-1}$. Then $a_{2n} = 2n-1$ and $a_{2n-1} = 2n$, so $$\sum_{n = 1}^{\infty} \frac{1}{a_n^s} = \zeta(s)$$ for $\operatorname{Re} s > 1$. Thus $\zeta$-regularisation leads to $\zeta(-1)$. And for $\operatorname{Re} s > 2$ we have $$\sum_{n = 1}^{\infty} \frac{a_n}{n^s} = \sum_{n = 1}^{\infty} \frac{1}{n^{s-1}} + \sum_{n = 1}^{\infty} \frac{(-1)^{n-1}}{n^s} = \zeta(s-1) + \eta(s)\,$$ so the analytic continuation of Dirichlet series leads to $\zeta(-1) + \eta(0) = \zeta(-1) + \frac{1}{2}$. These methods are hence not compatible.
{ "pile_set_name": "StackExchange" }
Q: Parent class definition with arguments I was browsing the camping documentation, and I ran into this example for defining a controller: class Digits < R '/nuts/(\d+)' def get(number) "You got here by: /nuts/#{number}" end end It looks like what this class definition is doing is that it's passing a string argument to the R superclass. However, I looked through the camping codebase and I didn't see R defined as a class anymore. It was defined as a method like this: def R(c,*g) p,h=/\(.+?\)/,g.grep(Hash) g-=h raise "bad route" if !u = c.urls.find{|x| break x if x.scan(p).size == g.size && /^#{x}\/?$/ =~ (x=g.inject(x){|x,a| x.sub p,U.escape((a.to_param rescue a))}.gsub(/\\(.)/){$1}) } h.any?? u+"?"+U.build_query(h[0]) : u end and the method to actually handle the route: def /(p); p[0] == ?/ ? @root + p : p end I don't understand exactly how this works, because when I tried to make a class and define a method as a superclass, like this: def doSomething(boo) puts boo end class Someclass < doSomething 'boo' end I get this error: (eval):60: (eval):60: superclass must be a Class (NilClass given) (TypeError) Can someone point me to where in the ruby documentation this feature (using a method as a superclass) is covered? I don't know what to call this feature, so my googling efforts couldn't really find me anything. A: You'll have to return a class from your method: def doSomething(boo) Class.new { define_method(:boo) { boo } } end class SomeClass < doSomething 'boo' end SomeClass.new.boo # => 'boo' You're also looking at the wrong method. Camping has a class method on Controllers called R (that's the one used when defining controllers) and an instance method on Base called R (for generating routes). This is the actual definition: https://github.com/camping/camping/blob/ae5a9fabfbd02ba2361ad8831c15d723d3740b7e/lib/camping-unabridged.rb#L551
{ "pile_set_name": "StackExchange" }
Q: Input range handler doesn't render in Chrome I am working on a tool to preview fonts on a website. For this tool, I want to use <input type="range" /> to change the font size in a textarea. Since I don't like the default WebKit rendering of the slider and the handler, I customized them using CSS. While the page renders fine in Safari, Chrome does not display the slider handle (Sliders on other websites render fine, though). What do I have to change to make it work in Chrome as well? The HTML <input type="range" min="6" max="70" value="22" id="font-1-size" /> The CSS .tester-option.font-size input { -webkit-appearance: none !important; background: #cecece; height: 1px; width: 425px; -webkit-transform: translate3d(0px, 0px, 0px); margin-top: 10px; cursor: pointer; } .tester-option.font-size input::-webkit-slider-thumb { -webkit-appearance: none !important; background: #666; height: 10px; width: 10px; cursor: pointer; -moz-border-radius: 10px; border-radius: 10px; } You can find the live example here: http://fishnation.de/development/26plus/#test-font P.S. I am aware that there is jQuery UI, but I want to replace as few elements as possible. A: Try changing your selector. I used #font-1-size::-webkit-slider-thumb. This worked fine in chrome.
{ "pile_set_name": "StackExchange" }
Q: Como agrupar registros por mês e ano, dentro de uma lista de objetos? ASP NET CORE Estou tentando agrupar os objetos de uma lista por mes ou ano, antes de retornar o mesmo. estou tentando da seguinte maneira e não obtive sucesso. foreach (var item in passList) { pass_obj = new Pass_returnDTO(); pass_obj.pass_date_time = item.pass_date_time.Date; pass_obj.qty_pass = Convert.ToInt32(item.qty_daily_pass); listRegistro.Add(pass_obj); } if (grouper == "ano") { objReturn.registros.GroupBy( d => d.pass_date_time.Year); listPassReturn.Add(objReturn); } else if (grouper == "mes") { objReturn.registros.GroupBy(d => d.pass_date_time.Month); listPassReturn.Add(objReturn); } A: //agrupando registros por ano var lista = objReturn.register.GroupBy(d => d.pass_date_time.ToString("yyyy")) .Select(x => new { Year = x.Key, Sum = x.Sum(item => item.qty_pass) }); //agrupando registros por mês var lista = objReturn.register.GroupBy(d => d.pass_date_time.ToString("yyyy/MM")) .Select(x => new { Month = x.Key, Sum = x.Sum(item => item.qty_pass) });
{ "pile_set_name": "StackExchange" }
Q: In R, Error in order(NULL, integer(0), na.last = TRUE, decreasing = FALSE) : argument 1 is not a vector auditing R programming course(coursera) I've tried reviewing know other solutions and running my code interactively to understand the error, now I'm circling around my own iterations. getting traceback error: Error in order(NULL, integer(0), na.last = TRUE, decreasing = FALSE) : argument 1 is not a vector 6 order(NULL, integer(0), na.last = TRUE, decreasing = FALSE) 5 do.call("order", c(z, na.last = na.last, decreasing = decreasing)) 4 order(complete_data$outcome, complete_data$name) 3 [.data.frame(complete_data, order(complete_data$outcome, complete_data$name), ) at rankhospital.R#60 2 complete_data[order(complete_data$outcome, complete_data$name), ] at rankhospital.R#60 1 rankhospital("TX", "heart failure", 4) My code: rankhospital <- function(state, outcome, num = "best") { ## Read outcome data data <- read.csv("outcome-of-care-measures.csv", colClasses = "character") state_col <- data[ , 7] name_col <- data[ , 2] attack_col <- suppressWarnings(as.numeric(data[ , 11])) failure_col <- suppressWarnings(as.numeric(data[ , 17])) pneumonia_col <- suppressWarnings(as.numeric(data[ , 23])) best_data <- cbind(state_col, name_col, attack_col, failure_col, pneumonia_col) colnames(best_data) <- c("state", "name", "heart attack", "heart failure", "pneumonia") best_data <- as.data.frame(best_data) ## Check that state and outcome are valid list_outcomes <- c("heart attack", "heart failure", "pneumonia") if (!(outcome %in% list_outcomes)) stop("invalid outcome") list_unique_states <- unique(state_col) if (!(state %in% list_unique_states)) stop("invalid state") ## Return hospital name in that state with the given rank ## 30-day death rate state_data <- best_data[best_data$state == state, ] #complete_data <- state_data[complete.cases(state_data[,"outcome"]), ] complete_data <- state_data[!is.na(state_data[state_data$"outcome", ]), ] complete_data <- as.data.frame(complete_data) #have data order the outcome by name, ordered_data <- complete_data[order(complete_data$"outcome", complete_data$name), ] final_data <- ordered_data min_value <- which.min(final_data[, outcome]) max_value <- which.max(final_data[, outcome]) if (num == "best") { as.character(final_data[min_value, 2]) } else if (num == "worst") { as.character(final_data[max_value, 2]) } else {as.character(final_data[num, 2]) } } } When I run the code interactively, line by line with an example line 60 works just fine. A: To select the column, which is in the function argument outcome, use state_data[, outcome], not state_data$"outcome": download.file("https://github.com/Yang-Zhou/computing-for-data-analysis/blob/master/proj2/outcome-of-care-measures.csv?raw=true", tf<-tempfile(fileext = ".csv")) rankhospital <- function(state, outcome, num = "best") { ## Read outcome data data <- read.csv(tf, colClasses = "character") state_col <- data[ , 7] name_col <- data[ , 2] attack_col <- suppressWarnings(as.numeric(data[ , 11])) failure_col <- suppressWarnings(as.numeric(data[ , 17])) pneumonia_col <- suppressWarnings(as.numeric(data[ , 23])) best_data <- cbind(state_col, name_col, attack_col, failure_col, pneumonia_col) colnames(best_data) <- c("state", "name", "heart attack", "heart failure", "pneumonia") best_data <- as.data.frame(best_data) ## Check that state and outcome are valid list_outcomes <- c("heart attack", "heart failure", "pneumonia") if(!(outcome %in% list_outcomes)) stop("invalid outcome") list_unique_states <- unique(state_col) if(!(state %in% list_unique_states)) stop("invalid state") ## Return hospital name in that state with the given rank ## 30-day death rate state_data <- best_data[best_data$state == state, ] #complete_data <- state_data[complete.cases(state_data[,"outcome"]), ] # complete_data <- state_data[!is.na(state_data[state_data$"outcome", ]), ] complete_data <- state_data[!is.na(state_data[, outcome]), ] complete_data <- as.data.frame(complete_data) #have data order the outcome by name, ordered_data <- complete_data[order(complete_data[, outcome], complete_data$name), ] final_data <- ordered_data min_value <- which.min(final_data[, outcome]) max_value <- which.max(final_data[, outcome]) if(num == "best"){ as.character(final_data[min_value, 2]) }else if(num == "worst"){ as.character(final_data[max_value, 2]) }else {as.character(final_data[num, 2]) } } rankhospital("AL", "heart attack")
{ "pile_set_name": "StackExchange" }
Q: Unable to run native C++ application on different machine I wrote a simple 'Hello, world' application in C++ using Visual Studio 2008. I am able to run the app successfully on my local machine. BUt when I copy the exe onto another machine and run, it does not run. It gives the error that 'Application has failed to start because application configuration is incorrect'. The another system does not have Visual Studio installed. What could be the problem? Thanks, Rakesh. A: Probably the CRT DLL is missing. Compile your app using static CRT - /MT (/MTd for debug). More info. In Visual studio go to Project properties > C/C++ > Code Generation > Runtime Library. A: I think you need 1) To install Microsoft Visual C++ 2008 Redistributable Package (x86) 2) Read about manifests and deployment of C++ applications: Scenarios for Deployment Examples, Choosing a Deployment Method
{ "pile_set_name": "StackExchange" }
Q: How do I 'register' local domain names, e.g. just on my home NT domain? I have just set up a small server for testing, using SBS 2003. I have set it up as a domain controller, and my dev machine belongs to that domain. One of the first things I wish to test is a scenario where HTTP requests under many domain names access sub-directories of a single parent site. Both my dev machine and domain controller are both currently set up to use my ISP's DNS, but I think I will need to set the DC up to use the ISP one, and my dev machine to use a DNS on my DC server. Is this a good option? How do I make my dev machine think it is actually accessing 'external' domain names? A: Normally you have one DNS server which resolves all local domain names, and in case of failure it sends request to ISP DNS. So all your dev workstations should have only one DNS server in it's records - your DNS server. There is also different situation when your DNS server can respond only for local domain names. In this case you need add two DNS records to your dev machines - local DNS as primary, ISP DNS as secondary. This depends on how you will configure your DNS server.
{ "pile_set_name": "StackExchange" }
Q: Declare Variable and concat all values of a select I am used to write queries in Sql Server and Oracle but new to MySql. I need to declare a variable and set all the values in a select statement. Here is what I am trying, set @v = '' select @v = @v + column from table group by column select @v If column have column ------ a a c Then the query should return, @v -- ac A: I think you want: select @v := group_concat(distinct column SEPARATOR '') from table; Result: | @v | | --- | | ac | View on DB Fiddle
{ "pile_set_name": "StackExchange" }
Q: How to read Query Parameters key and value javax.persistence.Query Query query = .... query.setParameter("PARAM_1","1") .setParameter("PARAM_2","2") .setParameter("PARAM_3","3") ... ...; I want to get parameters and write Console. Like this; System out ; PARAM_1 - 1 PARAM_2 - 2 PARAM_3 - 3 ... ... A: java.util.Set<Parameter<?>> params = query.getParameters(); for (Parameter p : params) { String paramName = p.getName(); System.out.print(paramName + " - "); System.out.println(query.getParameterValue(paramName)); }
{ "pile_set_name": "StackExchange" }
Q: Android - Implementing Navigation Drawer in Android 2.2 + I wanted to implement the Navigation Drawer given by google at http://developer.android.com/training/implementing-navigation/nav-drawer.html#top. So, i downloaded the sample from there and used the appcompat library from v7 support library. Changed extends Activity for MainActivity to extends ActionBarActivity. And changed everything that was giving error requiring min API Level of 11 to its support library equivalent ( getActionBar() ---> getSupportActionBar(), getFragmentmanger() to getsupportFragmentmanager() ) But now my app is crashing at the first line super.onCreate(savedInstanceState); in the onCreate() method. When i try to debug it gives me the error that source not found and opens the ActivityThread.performLaunchActivity(ActivityThread$ActivityClientRecord, Intent) line: 1953 import java.util.Locale; import android.support.v7.app.ActionBarActivity; import android.app.Activity; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.app.SearchManager; import android.content.Intent; import android.content.res.Configuration; import android.os.Bundle; import android.support.v4.app.ActionBarDrawerToggle; import android.support.v4.view.GravityCompat; import android.support.v4.widget.DrawerLayout; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.ImageView; import android.widget.ListView; import android.widget.Toast; /** * This example illustrates a common usage of the DrawerLayout widget * in the Android support library. * <p/> * <p>When a navigation (left) drawer is present, the host activity should detect presses of * the action bar's Up affordance as a signal to open and close the navigation drawer. The * ActionBarDrawerToggle facilitates this behavior. * Items within the drawer should fall into one of two categories:</p> * <p/> * <ul> * <li><strong>View switches</strong>. A view switch follows the same basic policies as * list or tab navigation in that a view switch does not create navigation history. * This pattern should only be used at the root activity of a task, leaving some form * of Up navigation active for activities further down the navigation hierarchy.</li> * <li><strong>Selective Up</strong>. The drawer allows the user to choose an alternate * parent for Up navigation. This allows a user to jump across an app's navigation * hierarchy at will. The application should treat this as it treats Up navigation from * a different task, replacing the current task stack using TaskStackBuilder or similar. * This is the only form of navigation drawer that should be used outside of the root * activity of a task.</li> * </ul> * <p/> * <p>Right side drawers should be used for actions, not navigation. This follows the pattern * established by the Action Bar that navigation should be to the left and actions to the right. * An action should be an operation performed on the current contents of the window, * for example enabling or disabling a data overlay on top of the current content.</p> */ public class MainActivity extends ActionBarActivity { private DrawerLayout mDrawerLayout; private ListView mDrawerList; private ActionBarDrawerToggle mDrawerToggle; private CharSequence mDrawerTitle; private CharSequence mTitle; private String[] mPlanetTitles; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mTitle = mDrawerTitle = getTitle(); mPlanetTitles = getResources().getStringArray(R.array.planets_array); mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout); mDrawerList = (ListView) findViewById(R.id.left_drawer); // set a custom shadow that overlays the main content when the drawer opens mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START); // set up the drawer's list view with items and click listener mDrawerList.setAdapter(new ArrayAdapter<String>(this, R.layout.drawer_list_item, mPlanetTitles)); mDrawerList.setOnItemClickListener(new DrawerItemClickListener()); // enable ActionBar app icon to behave as action to toggle nav drawer getSupportActionBar().setDisplayHomeAsUpEnabled(true); getSupportActionBar().setHomeButtonEnabled(true); // ActionBarDrawerToggle ties together the the proper interactions // between the sliding drawer and the action bar app icon mDrawerToggle = new ActionBarDrawerToggle( this, /* host Activity */ mDrawerLayout, /* DrawerLayout object */ R.drawable.ic_drawer, /* nav drawer image to replace 'Up' caret */ R.string.drawer_open, /* "open drawer" description for accessibility */ R.string.drawer_close /* "close drawer" description for accessibility */ ) { public void onDrawerClosed(View view) { getSupportActionBar().setTitle(mTitle); supportInvalidateOptionsMenu(); // creates call to onPrepareOptionsMenu() } public void onDrawerOpened(View drawerView) { getSupportActionBar().setTitle(mDrawerTitle); supportInvalidateOptionsMenu(); // creates call to onPrepareOptionsMenu() } }; mDrawerLayout.setDrawerListener(mDrawerToggle); if (savedInstanceState == null) { selectItem(0); } } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.main, menu); return super.onCreateOptionsMenu(menu); } /* Called whenever we call invalidateOptionsMenu() */ @Override public boolean onPrepareOptionsMenu(Menu menu) { // If the nav drawer is open, hide action items related to the content view boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList); menu.findItem(R.id.action_websearch).setVisible(!drawerOpen); return super.onPrepareOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { // The action bar home/up action should open or close the drawer. // ActionBarDrawerToggle will take care of this. if (mDrawerToggle.onOptionsItemSelected(item)) { return true; } // Handle action buttons switch(item.getItemId()) { case R.id.action_websearch: // create intent to perform web search for this planet Intent intent = new Intent(Intent.ACTION_WEB_SEARCH); intent.putExtra(SearchManager.QUERY, getSupportActionBar().getTitle()); // catch event that there's no activity to handle intent if (intent.resolveActivity(getPackageManager()) != null) { startActivity(intent); } else { Toast.makeText(this, R.string.app_not_available, Toast.LENGTH_LONG).show(); } return true; default: return super.onOptionsItemSelected(item); } } /* The click listner for ListView in the navigation drawer */ private class DrawerItemClickListener implements ListView.OnItemClickListener { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { selectItem(position); } } private void selectItem(int position) { // update the main content by replacing fragments Fragment fragment = new PlanetFragment(); Bundle args = new Bundle(); args.putInt(PlanetFragment.ARG_PLANET_NUMBER, position); fragment.setArguments(args); FragmentManager fragmentManager = getSupportFragmentManager(); fragmentManager.beginTransaction().replace(R.id.content_frame, fragment).commit(); // update selected item and title, then close the drawer mDrawerList.setItemChecked(position, true); setTitle(mPlanetTitles[position]); mDrawerLayout.closeDrawer(mDrawerList); } @Override public void setTitle(CharSequence title) { mTitle = title; getSupportActionBar().setTitle(mTitle); } /** * When using the ActionBarDrawerToggle, you must call it during * onPostCreate() and onConfigurationChanged()... */ @Override protected void onPostCreate(Bundle savedInstanceState) { super.onPostCreate(savedInstanceState); // Sync the toggle state after onRestoreInstanceState has occurred. mDrawerToggle.syncState(); } @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); // Pass any configuration change to the drawer toggls mDrawerToggle.onConfigurationChanged(newConfig); } /** * Fragment that appears in the "content_frame", shows a planet */ public static class PlanetFragment extends Fragment { public static final String ARG_PLANET_NUMBER = "planet_number"; public PlanetFragment() { // Empty constructor required for fragment subclasses } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment_planet, container, false); int i = getArguments().getInt(ARG_PLANET_NUMBER); String planet = getResources().getStringArray(R.array.planets_array)[i]; int imageId = getResources().getIdentifier(planet.toLowerCase(Locale.getDefault()), "drawable", getActivity().getPackageName()); ((ImageView) rootView.findViewById(R.id.image)).setImageResource(imageId); getActivity().setTitle(planet); return rootView; } } } Logcat 04-04 00:46:07.531: D/AndroidRuntime(719): Shutting down VM 04-04 00:46:07.531: W/dalvikvm(719): threadid=1: thread exiting with uncaught exception (group=0x409961f8) 04-04 00:46:07.730: E/AndroidRuntime(719): FATAL EXCEPTION: main 04-04 00:46:07.730: E/AndroidRuntime(719): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.slidingmenu/com.example.slidingmenu.MainActivity}: java.lang.IllegalStateException: You need to use a Theme.AppCompat theme (or descendant) with this activity. 04-04 00:46:07.730: E/AndroidRuntime(719): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1955) 04-04 00:46:07.730: E/AndroidRuntime(719): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1980) 04-04 00:46:07.730: E/AndroidRuntime(719): at android.app.ActivityThread.access$600(ActivityThread.java:122) 04-04 00:46:07.730: E/AndroidRuntime(719): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1146) 04-04 00:46:07.730: E/AndroidRuntime(719): at android.os.Handler.dispatchMessage(Handler.java:99) 04-04 00:46:07.730: E/AndroidRuntime(719): at android.os.Looper.loop(Looper.java:137) 04-04 00:46:07.730: E/AndroidRuntime(719): at android.app.ActivityThread.main(ActivityThread.java:4340) 04-04 00:46:07.730: E/AndroidRuntime(719): at java.lang.reflect.Method.invokeNative(Native Method) 04-04 00:46:07.730: E/AndroidRuntime(719): at java.lang.reflect.Method.invoke(Method.java:511) 04-04 00:46:07.730: E/AndroidRuntime(719): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784) 04-04 00:46:07.730: E/AndroidRuntime(719): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551) 04-04 00:46:07.730: E/AndroidRuntime(719): at dalvik.system.NativeStart.main(Native Method) 04-04 00:46:07.730: E/AndroidRuntime(719): Caused by: java.lang.IllegalStateException: You need to use a Theme.AppCompat theme (or descendant) with this activity. 04-04 00:46:07.730: E/AndroidRuntime(719): at android.support.v7.app.ActionBarActivityDelegate.onCreate(ActionBarActivityDelegate.java:108) 04-04 00:46:07.730: E/AndroidRuntime(719): at android.support.v7.app.ActionBarActivityDelegateICS.onCreate(ActionBarActivityDelegateICS.java:57) 04-04 00:46:07.730: E/AndroidRuntime(719): at android.support.v7.app.ActionBarActivity.onCreate(ActionBarActivity.java:98) 04-04 00:46:07.730: E/AndroidRuntime(719): at com.example.slidingmenu.MainActivity.onCreate(MainActivity.java:83) 04-04 00:46:07.730: E/AndroidRuntime(719): at android.app.Activity.performCreate(Activity.java:4465) 04-04 00:46:07.730: E/AndroidRuntime(719): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049) 04-04 00:46:07.730: E/AndroidRuntime(719): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1919) 04-04 00:46:07.730: E/AndroidRuntime(719): ... 11 more Logcat after doing changes in manifest 04-04 00:57:19.443: E/AndroidRuntime(365): FATAL EXCEPTION: main 04-04 00:57:19.443: E/AndroidRuntime(365): android.view.InflateException: Binary XML file line #17: Error inflating class <unknown> 04-04 00:57:19.443: E/AndroidRuntime(365): at android.view.LayoutInflater.createView(LayoutInflater.java:513) 04-04 00:57:19.443: E/AndroidRuntime(365): at com.android.internal.policy.impl.PhoneLayoutInflater.onCreateView(PhoneLayoutInflater.java:56) 04-04 00:57:19.443: E/AndroidRuntime(365): at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:563) 04-04 00:57:19.443: E/AndroidRuntime(365): at android.view.LayoutInflater.inflate(LayoutInflater.java:385) 04-04 00:57:19.443: E/AndroidRuntime(365): at android.view.LayoutInflater.inflate(LayoutInflater.java:320) 04-04 00:57:19.443: E/AndroidRuntime(365): at android.widget.ArrayAdapter.createViewFromResource(ArrayAdapter.java:332) 04-04 00:57:19.443: E/AndroidRuntime(365): at android.widget.ArrayAdapter.getView(ArrayAdapter.java:323) 04-04 00:57:19.443: E/AndroidRuntime(365): at android.widget.AbsListView.obtainView(AbsListView.java:1315) 04-04 00:57:19.443: E/AndroidRuntime(365): at android.widget.ListView.makeAndAddView(ListView.java:1727) 04-04 00:57:19.443: E/AndroidRuntime(365): at android.widget.ListView.fillDown(ListView.java:652) 04-04 00:57:19.443: E/AndroidRuntime(365): at android.widget.ListView.fillFromTop(ListView.java:709) 04-04 00:57:19.443: E/AndroidRuntime(365): at android.widget.ListView.layoutChildren(ListView.java:1580) 04-04 00:57:19.443: E/AndroidRuntime(365): at android.widget.AbsListView.onLayout(AbsListView.java:1147) 04-04 00:57:19.443: E/AndroidRuntime(365): at android.view.View.layout(View.java:7035) 04-04 00:57:19.443: E/AndroidRuntime(365): at android.support.v4.widget.DrawerLayout.onLayout(DrawerLayout.java:767) 04-04 00:57:19.443: E/AndroidRuntime(365): at android.view.View.layout(View.java:7035) 04-04 00:57:19.443: E/AndroidRuntime(365): at android.widget.FrameLayout.onLayout(FrameLayout.java:333) 04-04 00:57:19.443: E/AndroidRuntime(365): at android.view.View.layout(View.java:7035) 04-04 00:57:19.443: E/AndroidRuntime(365): at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1249) 04-04 00:57:19.443: E/AndroidRuntime(365): at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1125) 04-04 00:57:19.443: E/AndroidRuntime(365): at android.widget.LinearLayout.onLayout(LinearLayout.java:1042) 04-04 00:57:19.443: E/AndroidRuntime(365): at android.view.View.layout(View.java:7035) 04-04 00:57:19.443: E/AndroidRuntime(365): at android.widget.FrameLayout.onLayout(FrameLayout.java:333) 04-04 00:57:19.443: E/AndroidRuntime(365): at android.view.View.layout(View.java:7035) 04-04 00:57:19.443: E/AndroidRuntime(365): at android.widget.FrameLayout.onLayout(FrameLayout.java:333) 04-04 00:57:19.443: E/AndroidRuntime(365): at android.view.View.layout(View.java:7035) 04-04 00:57:19.443: E/AndroidRuntime(365): at android.view.ViewRoot.performTraversals(ViewRoot.java:1045) 04-04 00:57:19.443: E/AndroidRuntime(365): at android.view.ViewRoot.handleMessage(ViewRoot.java:1727) 04-04 00:57:19.443: E/AndroidRuntime(365): at android.os.Handler.dispatchMessage(Handler.java:99) 04-04 00:57:19.443: E/AndroidRuntime(365): at android.os.Looper.loop(Looper.java:123) 04-04 00:57:19.443: E/AndroidRuntime(365): at android.app.ActivityThread.main(ActivityThread.java:4627) 04-04 00:57:19.443: E/AndroidRuntime(365): at java.lang.reflect.Method.invokeNative(Native Method) 04-04 00:57:19.443: E/AndroidRuntime(365): at java.lang.reflect.Method.invoke(Method.java:521) 04-04 00:57:19.443: E/AndroidRuntime(365): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868) 04-04 00:57:19.443: E/AndroidRuntime(365): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626) 04-04 00:57:19.443: E/AndroidRuntime(365): at dalvik.system.NativeStart.main(Native Method) 04-04 00:57:19.443: E/AndroidRuntime(365): Caused by: java.lang.reflect.InvocationTargetException 04-04 00:57:19.443: E/AndroidRuntime(365): at android.widget.TextView.<init>(TextView.java:321) 04-04 00:57:19.443: E/AndroidRuntime(365): at java.lang.reflect.Constructor.constructNative(Native Method) 04-04 00:57:19.443: E/AndroidRuntime(365): at java.lang.reflect.Constructor.newInstance(Constructor.java:446) 04-04 00:57:19.443: E/AndroidRuntime(365): at android.view.LayoutInflater.createView(LayoutInflater.java:500) 04-04 00:57:19.443: E/AndroidRuntime(365): ... 35 more 04-04 00:57:19.443: E/AndroidRuntime(365): Caused by: android.content.res.Resources$NotFoundException: File res/drawable-mdpi/abc_ic_ab_back_holo_dark.png from drawable resource ID #0x0 04-04 00:57:19.443: E/AndroidRuntime(365): at android.content.res.Resources.loadDrawable(Resources.java:1714) 04-04 00:57:19.443: E/AndroidRuntime(365): at android.content.res.TypedArray.getDrawable(TypedArray.java:601) 04-04 00:57:19.443: E/AndroidRuntime(365): at android.view.View.<init>(View.java:1885) 04-04 00:57:19.443: E/AndroidRuntime(365): at android.widget.TextView.<init>(TextView.java:327) 04-04 00:57:19.443: E/AndroidRuntime(365): ... 39 more 04-04 00:57:19.443: E/AndroidRuntime(365): Caused by: java.io.FileNotFoundException: res/drawable-mdpi/abc_ic_ab_back_holo_dark.png 04-04 00:57:19.443: E/AndroidRuntime(365): at android.content.res.AssetManager.openNonAssetNative(Native Method) 04-04 00:57:19.443: E/AndroidRuntime(365): at android.content.res.AssetManager.openNonAsset(AssetManager.java:405) 04-04 00:57:19.443: E/AndroidRuntime(365): at android.content.res.Resources.loadDrawable(Resources.java:1706) 04-04 00:57:19.443: E/AndroidRuntime(365): ... 42 more activity_main.xml <!-- Copyright 2013 The Android Open Source Project Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --> <!-- A DrawerLayout is intended to be used as the top-level content view using match_parent for both width and height to consume the full space available. --> <android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/drawer_layout" android:layout_width="match_parent" android:layout_height="match_parent"> <!-- As the main content view, the view below consumes the entire space available using match_parent in both dimensions. --> <FrameLayout android:id="@+id/content_frame" android:layout_width="match_parent" android:layout_height="match_parent" /> <!-- android:layout_gravity="start" tells DrawerLayout to treat this as a sliding drawer on the left side for left-to-right languages and on the right side for right-to-left languages. The drawer is given a fixed width in dp and extends the full height of the container. A solid background is used for contrast with the content view. --> <ListView android:id="@+id/left_drawer" android:layout_width="240dp" android:layout_height="match_parent" android:layout_gravity="start" android:choiceMode="singleChoice" android:divider="@android:color/transparent" android:dividerHeight="0dp" android:background="#111"/> </android.support.v4.widget.DrawerLayout> drawer_list_item.xml <!-- Copyright 2013 The Android Open Source Project Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --> <TextView xmlns:android="http://schemas.android.com/apk/res/android" android:id="@android:id/text1" android:layout_width="match_parent" android:layout_height="wrap_content" android:textAppearance="?android:attr/textAppearanceListItemSmall" android:gravity="center_vertical" android:paddingLeft="16dp" android:paddingRight="16dp" android:textColor="#fff" android:background="?android:attr/activatedBackgroundIndicator" android:minHeight="?android:attr/listPreferredItemHeightSmall"/> fragment_planet.xml <!-- Copyright 2013 The Android Open Source Project Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --> <ImageView xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/image" android:layout_width="match_parent" android:layout_height="match_parent" android:background="#000000" android:gravity="center" android:padding="32dp" /> A: You should use Theme.AppCompat for theme. Please update your theme.xml with and set theme in manifest.xml. theme.xml: <!-- Application theme. --> <style name="AppTheme" parent="@style/Theme.AppCompat"> <!-- All customizations that are NOT specific to a particular API-level can go here. --> </style> manifest.xml: <application android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme"... I suggest you to forget about Android 2.2 :) No one uses it anymore. And please try to clean project. You can not use android:attr/textAppearanceListItemSmall under API14 reference.
{ "pile_set_name": "StackExchange" }
Q: pixel perfect collision + blitting I'm using a blitting engine that uses bitmapData. No display objects. Is there a fast pixel perfect collision detection available for such a game system? I already tried CDK but that didn't work because it assumes you have display objects which my objects don't use. Sometimes my objects are pretty big and hitTest sucks in this case. I already tried circle-to-circle collisions but that didn't do the trick either. Any help or hints? Update: public function renderTile(canvasBitmapData:BitmapData):void { x = nextX; y = nextY; point.x = x; point.y = y; if (animationCount >= animationDelay) { animationCount = 0; if(reverse) { currentTile--; if (currentTile < 1) { currentTile = tilesLength - 1; } } else { currentTile++; if (currentTile == tilesLength) { currentTile = 0; } } } else { animationCount++; } canvasBitmapData.lock(); tileRect.x = int((currentTile % spritesPerRow)) * tileWidth; tileRect.y = int((currentTile / spritesPerRow)) * tileHeight; bitmapData = new BitmapData(tileWidth - oversize, tileHeight - oversize, true, 0x000000); canvasBitmapData.copyPixels(tileSheet, tileRect, point); canvasBitmapData.unlock(); } Calling hitTest: if (player.bitmapData.hitTest(player.point, 255, tempAsteroid.bitmapData, tempAsteroid.point, 255)) Currently the collisions do not work at all. I can fly through my objects and I get absolutely no collisions. I read somewhere that flash player standalone v10.1 had issues with bitmapData.hitTest but I'm using 10.3 so this should be not the problem. A: Can not post comments (yet); so have to do it via answer. It is not very clear how the two code snippets are related. Only thing I see is that in the first code snippet bitmapData gets created, but is not used or filled with anything. So hitTest would always fail I guess, since bitmapData exists of only transparent pixels. Following example shows hitTest seems the way to go though (no idea about speeds): http://www.mikechambers.com/blog/2009/06/24/using-bitmapdata-hittest-for-collision-detection/
{ "pile_set_name": "StackExchange" }
Q: Convert base64 png data to javascript file objects I have two base64 encoded in PNG, and I need to compare them using Resemble.JS I think that the best way to do it is to convert the PNG's into file objects using fileReader. How can I do it? A: Way 1: only works for dataURL, not for other types of url. function dataURLtoFile(dataurl, filename) { var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1], bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n); while(n--){ u8arr[n] = bstr.charCodeAt(n); } return new File([u8arr], filename, {type:mime}); } //Usage example: var file = dataURLtoFile('data:image/png;base64,......', 'a.png'); console.log(file); Way 2: works for any type of url, (http url, dataURL, blobURL, etc...) //return a promise that resolves with a File instance function urltoFile(url, filename, mimeType){ mimeType = mimeType || (url.match(/^data:([^;]+);/)||'')[1]; return (fetch(url) .then(function(res){return res.arrayBuffer();}) .then(function(buf){return new File([buf], filename, {type:mimeType});}) ); } //Usage example: urltoFile('data:image/png;base64,......', 'a.png') .then(function(file){ console.log(file); }) Both works in Chrome and Firefox. A: You can create a Blob from your base64 data, and then read it asDataURL: var img_b64 = canvas.toDataURL('image/png'); var png = img_b64.split(',')[1]; var the_file = new Blob([window.atob(png)], {type: 'image/png', encoding: 'utf-8'}); var fr = new FileReader(); fr.onload = function ( oFREvent ) { var v = oFREvent.target.result.split(',')[1]; // encoding is messed up here, so we fix it v = atob(v); var good_b64 = btoa(decodeURIComponent(escape(v))); document.getElementById("uploadPreview").src = "data:image/png;base64," + good_b64; }; fr.readAsDataURL(the_file); Full example (includes junk code and console log): http://jsfiddle.net/tTYb8/ Alternatively, you can use .readAsText, it works fine, and its more elegant.. but for some reason text does not sound right ;) fr.onload = function ( oFREvent ) { document.getElementById("uploadPreview").src = "data:image/png;base64," + btoa(oFREvent.target.result); }; fr.readAsText(the_file, "utf-8"); // its important to specify encoding here Full example: http://jsfiddle.net/tTYb8/3/ A: Previous answer didn't work for me. But this worked perfectly. Convert Data URI to File then append to FormData
{ "pile_set_name": "StackExchange" }
Q: How to test my Firebird SQL queries I'm in the process of learning SQL, and I need a way of verifying that my SQL queries are valid (i.e. no syntax errors). I also would like to check what results they yield on a test database of my choosing and structure. I'm using embedded firebird in my C# .NET application, so I don't really have any tools to work with. Anyone have any tips? Perhaps there are SQL administrators/query IDEs out there that work with Firebird? A: You can use IBExpert personal or DatabaseWorkbench Lite check also this and this
{ "pile_set_name": "StackExchange" }
Q: Using a variable inside a CDATA string in VB.NET? Suppose that I have a Class with a multiline string like this: Public Class HelpSection ' This process name (Example: 'MyProcess.exe') Public Shared ReadOnly ThisProcess As String = Process.GetCurrentProcess().MainModule.ModuleName Public Shared ReadOnly Syntax As String = <a><![CDATA[ [+] Syntax: ThisProcess (SWITCH)=(VALUE) (IN FILE) ]]></a>.Value End Class And now, when I call the multiline string: Console.WriteLine(HelpSection4.Syntax) It will print this: ThisProcess (SWITCH)=(VALUE) (IN FILE) But I would like to print automatically the ThisProcess variable content (the process name) like this: MyProcess.exe (SWITCH)=(VALUE) (IN FILE) So how I can manage the CDATA literal to set the variable content dynamically? Is this possibly? Maybe a better approach to manage this? (dynamically without hardcoding, keep in mind that it's for generic usage) UPDATE I'm trying to reproduce @Dan-o solution but of course in my case don't works because it's a CDATA literal, then how to escape it or do the necessary modifications?: Dim ProcessName As String = "MyProcess.exe" Dim Help As XElement = <Help> <Process><%= ProcessName %></Process> <Syntax><a><![CDATA[ [+] Syntax: <% ProcessName %> (SWITCH)=(VALUE) (IN FILE) ]]></a></Syntax> </Help> Console.WriteLine(Help.<Process>.Value) Console.WriteLine(Help.<Syntax>.Value) UPDATE 2 In a simple XML file (for example, a .NET code snippet) I use this trick that I've learned time ago to scape a character in a CDATA: <Literal Editable="false"> <ID>cdataend</ID> <ToolTip>Part of the CDATA end tag.</ToolTip> <Default>&gt;</Default> </Literal> Then I could write the > illegal character inside, like this: <Code Language="vb"><a><![CDATA[ something ]]$cdataend$</a>.Value ]]></Code> The thing is that I don't know if that can help me with the variable issue... just I'm trying to give ideas. A: According to MSDN: Dim contactName As String = "Patrick Hines" Dim contact As XElement = <contact> <name><%= contactName %></name> </contact> Console.WriteLine(contact) It should be an extremely simple matter to adapt this to your situation.
{ "pile_set_name": "StackExchange" }
Q: How to find out which cron jobs are currently running? Is this possible to find out which cron jobs are currently running? A: The answer can be found in drupal_cron_run. While it is the case that you can tell if Cron is currently running by calling lock_acquire('cron', ...)), just as Drupal does (don't forget to call lock_release too), Drupal does not in any way set any information about the individual cron hooks that it executes during a cron job. If you need more control over cron job execution, you could always copy the drupal_cron_run function into your own module and modify it to suit. drush_core_cron() does nothing other than call drupal_cron_run, so you could call your own cron function via drush ev 'mymodule_cron_run();' from your crontab. If you did this, you would need to review the implementation of drupal_cron_run on every update of Drupal core, and check for any significant alterations in behavior, so you should only customize cron if it's really important that you do so.
{ "pile_set_name": "StackExchange" }
Q: "Comments can not contain that content"? I tried to comment on this answer, but The System told me "Comments cannot contain that content." Why not!? Can we enable "that content"? A: We've had some persistent Chinese spammers across the network, so we introduced a global block on Chinese characters (on sites where we don't expect such characters to normally appear). Given that the block was only hit 3 times here since introduction and that Brazil has a large Japanese community, I have lifted the block here.
{ "pile_set_name": "StackExchange" }
Q: How do I rename my Git 'master' branch to 'release'? We would like to enforce a new policy for our projects that the master branch now be called the release branch to ensure it is more clear as to how the branch should be used. Naturally, we will have develop and release candidate branches as well. I understand I can rename the master branch locally by simply using the following: git branch -m master release However, that is only locally. Even if I push this up to the remote, the HEAD still points to the remote master branch. I want to get rid of the master branch completely and make the default local branch upon initial clone, be release. How can I achieve this? It seems that since the origin is on a Gitorious server, I get errors deleting the master branch. I'm trying to see now if it is possible to change this so that the default branch is 'release'. A: git checkout -b release master # Create and switch to the release branch git push -u origin release # Push the release branch to the remote and track it git branch -d master # Delete local master git push --delete origin master # Delete remote master git remote prune origin # Delete the remote tracking branch Please note, if you are using GitHub you will need to first change your "default" branch on GitHub after step 3: In your repository on github.com go Settings → Branches → Default Branch. Change it to release and then do the rest of the steps. A: Check out your master branch git checkout master Create your release branch and switch to it: git branch release git checkout release Push that to the server git push origin release Delete the master branch reference on the server git push origin :master Delete the local master branch git branch -d master A: Note: This answer is intended for self-hosted Git servers where you have command line access. Since trying to delete the remote master from a client indeed is not allowed and I do assume forbidding denyDeleteCurrent makes sense, I would not like to change that setting. However, I found that the easiest way to rename your master iff you have command line access to the remote server is to run the rename command directly on remote. This worked for me: Login via SSH to the remote git server Go to the xxx.git folder of your project run: git branch -m master release Now the remote repository uses release as its default branch and any git clone on that repository from any client will check out the release branch by default. It is very helpful also after setting up a bare repository to configure it to your needs.
{ "pile_set_name": "StackExchange" }
Q: How to prove $\operatorname{Tr}(AB) = \operatorname{Tr}(BA)$? there is a similar thread here Coordinate-free proof of $\operatorname{Tr}(AB)=\operatorname{Tr}(BA)$?, but I'm only looking for a simple linear algebra proof. A: Observe that if $A$ and $B$ are $n\times n$ matrices, $A=(a_{ij})$, and $B=(b_{ij})$, then $$(AB)_{ii} = \sum_{k=1}^n a_{ik}b_{ki},$$ so $$ \operatorname{Tr}(AB) = \sum_{j=1}^n\sum_{k=1}^n a_{jk}b_{kj}. $$ Conclude calculating the term $(BA)_{ii}$ and comparing both traces. A: The efficient @hjhjhj57: answer $$\text{Tr}(AB) = \text{Tr}(BA)= \sum a_{ij} b_{ji}$$ Now we can start to understand why if we do a circular permutation of the factors the expression $$\text{Tr}( A_1 A_2 \ldots A_m)$$ does not change, and what is the expression. Assume now $A$,$B$ square. Then certainly $\det(AB) = \det(BA)$, using the multiplicative property of the $\det$. In fact, the matrices $AB$ and $BA$ have the same characteristic polynomial, so in particular the same trace, and the same determinant. A: For any couple $(A,B)$ of $n\times n$ matrices with complex entries, the following identity holds: $$ \operatorname{Tr}(AB) = \operatorname{Tr}(BA).$$ Proof. Assuming $A$ is an invertible matrix, $AB$ and $BA$ share the same characteristic polynomial, since they are conjugated matrices due to $BA = A^{-1}(AB)A$. In particular they have the same trace. Equivalently, they share the same eigenvalues (counted according to their algebraic multiplicity) hence they share the sum of such eigenvalues. On the other hand, if $A$ is a singular matrix then $A_\varepsilon\stackrel{\text{def}}{=} A+\varepsilon I$ is an invertible matrix for any $\varepsilon\neq 0$ small enough. It follows that $\operatorname{Tr}(A_\varepsilon B) = \operatorname{Tr}(B A_\varepsilon)$, and since $\operatorname{Tr}$ is a continuous operator, by considering the limits of both sides as $\varepsilon\to 0$ we get $\operatorname{Tr}(AB)=\operatorname{Tr}(BA)$ just as well.
{ "pile_set_name": "StackExchange" }
Q: How do I explicitly find the norm of $I = \text{Card}(\mathbb{Z}[\sqrt{-d}]/I)?$ Say we have number field $\mathbb{Q}(\sqrt{-d})$, where $d$ is either $1$ or $2$ mod $4$, so ring of integers is $\mathbb{Z}[\sqrt{-d}]$. Suppose we have an ideal of ring of integers $I$. Now, $I$ can be written as$$\mathbb{Z}(a + b\sqrt{-d}) + \mathbb{Z}(e + f\sqrt{-d}),$$where the two basis elements are clearly $\mathbb{Z}$-linearly independent. Given $a$, $b$, $e$, $d$, $f$, how do I explicitly find the norm of $I$, defined to be $$\text{Card}(\mathbb{Z}[\sqrt{-d}]/I)?$$ A: My own method is just to thrash about unsystematically, as suggested by @MooS. But here’s a presystematic approach that might work. Let $J_1$ be the ideal generated by your first quantity $z_1=a+b\sqrt{-d}$ (not merely the integer multiples of $z_1$), and $J_2$ be the ideal generated by $z_2=e+f\sqrt{-d}$. You know the norms of the $J_i$: $J_1$ has norm $a^2+db^2$ and $J_2$ has norm $e^2+df^2$. If you know the decompositions of the rational primes that divide the norms, then you should be able to find the prime decomposition of $J_1$ and $J_2$, and so of $J_1+J_2$. That will tell you the norm.
{ "pile_set_name": "StackExchange" }
Q: facebook invitations through android app I am developing an android app. Is it possible to integrate Facebook invitations into my app? Something like "Rounds app" : https://play.google.com/store/apps/details?id=com.rounds.android because this app contains this function and we are able to invite Facebook friends through it. I searched and all I found was that I can integrate the Facebook invitation function in games. (but "Rounds" app, is not a game) A: Facebook consider all to be apps. You create an app in Facebook developer and you can use it as game or as an application. Create the request as if it was game. I suggest you try this page: Facebook.
{ "pile_set_name": "StackExchange" }
Q: Android InstrumentTest hangs until minimizing the app I just started to look into Android instrumentation tests but have some problems with getting my tests executed. Here is what I tried: Using Android Studio and gradle, I created a simple test class within src/instrumentTest/java/. Here it is: package at.example.test; import android.test.ActivityInstrumentationTestCase2; import android.view.View; import at.example.activity.MainActivity; public class BasicAppTestCase extends ActivityInstrumentationTestCase2<MainActivity> { private MainActivity activity; public BasicAppTestCase() { super(MainActivity.class); } @Override protected void setUp() throws Exception { super.setUp(); activity = getActivity(); } public void testAppHomeButtonExists() { View homeButton = activity.findViewById(android.R.id.home); assertNotNull("Home button does not exist", homeButton); } } Next, I start the test using by right clicking on my project and selecting Run 'All Tests'. Android Studio executes assembleDebug and assembleTest tasks for my project, and installs both apk files onto my test device. Afterwards, the app is successfully started on my test device. The setUp() method is getting executed (I checked this by putting a failing assert into the method as well as using logcat) and then the test execution hangs, showing Running tests... and testAppHomeButtonExists as being currently executed. The test execution won't proceed until I change the activity state by minimizing the app pressing the home button or opening the app switcher. Then the test method testAppHomeButtonExists gets executed and (depending on the methods body) succeeds or fails. Again, I tested this behavior using assert calls and the logcat output. UPDATE: This is what the TestRunner is logging to my device's logcat stream: 11-11 15:34:59.750 24730-24748/at.example.activity I/TestRunner﹕ started: testAppHomeButtonExists(BasicAppTestCase) Up until I stop the app nothing more is logged. After stopping the activity following is logged: 11-11 15:35:05.205 24730-24748/at.example.activity I/TestRunner﹕ finished: testAppHomeButtonExists(BasicAppTestCase) 11-11 15:35:05.205 24730-24748/at.example.activity I/TestRunner﹕ passed: testAppHomeButtonExists(BasicAppTestCase) Am I doing something wrong? Am I missing something? What could cause this behavior? Thanks in advance! A: I have found the problem: I created an infinite invalidation loop inside one of my views onDraw() method. A velociraptor should eat me for using old code without checking it first. This is what the view's drawing method looked like: @Override protected void onDraw(Canvas canvas) { // Get the current location on screen in pixels (left = 0) int[] location = new int[2]; this.getLocationOnScreen(location); // Translate the canvas for the same location as its current offset (resulting in a doubled shift). canvas.translate(location[0], 0); // Now draw the translated content. super.onDraw(canvas); this.invalidate(); } The above drawing method created a "faked parallax effect" of the view's content. The problem was, that although this did not result in a ANR it caused the hosting Activity to never go idle causing my test's getActivity() method not to return as it's implementation waits for an idle activity (meaning the setup completed). The question Android animation causing "Activity idle timeout for History Record" on start up is a similar problem. My quick solution was to defer the invalidate() call to the parent ViewPager. Since my parallax effect needed only to be updated when the position of my page changed I am now using a ViewPager.OnPageChangeListener() that updates child views as soon as they move. This fixes the problem for me! My tests are running now and are fully functional!
{ "pile_set_name": "StackExchange" }
Q: How to prove $dxdy = r dr d \theta$? $x = r \cos \theta$, $y = r \sin \theta$ I got $dx = \cos \theta dr - r \sin \theta d \theta $ $ dy = \sin \theta dr + r \cos \theta d \theta$ How to get $dx dy = r dr d \theta$?? I saw the same question Rigorous proof that $dx dy=r\ dr\ d\theta$. But I am not getting where vectors are coming in to the picture thanks. A: How to get $dx\;dy=r\;dr\;dθ$? I suggest you take a look at Advanced calculus of several variables by C.H. Edwards. In Section 5 of Chapter IV, we can read something like this: The student has undoubtedly seen change of variables formulas such as $$\iint f(x,y)\;dx\;dy=\iint f(r\cos\theta,r\sin\theta)\;r\;dr\;d\theta$$ which result from changes from rectangular coordinates to polar coordinates. The appearance of the factor $r$ in the formula is sometimes "explained" by mythical pictures, such as figure below, in which it is alleged that $dA$ is an "infinitesimal" rectangle with sides $dr$ and $r\;d\theta$, and therefore has area $r \;dr\; d\theta$. In this section we shall give a mathemtaically acceptable explanation of the origin of such factors in the transformation of multiple integrals from one coordinate system to another. EDIT For details about the Edwards approach, I refer the reader to this post. A: A piece of an annulus swept out by a change of angle $\Delta \theta$ and a change of radius $\Delta r$, starting from a point given by $(r,\theta)$, has area $\Delta \theta \int_r^{r+\Delta r} s ds = \Delta \theta \frac{(r+\Delta r)^2-r^2}{2} = \Delta \theta \left ( r \Delta r + \frac{\Delta r^2}{2} \right )$. (This is computed by integrating the length of circular arcs.) As $\Delta r \to 0$ the second term is asymptotically much smaller than the first, which heuristically justifies the change of variables formula. Showing that this procedure, which is equivalent to the more general procedure based on the Jacobian determinant, actually makes integrals do the correct thing takes some more work. The details can be found in a typical undergraduate real analysis text.
{ "pile_set_name": "StackExchange" }
Q: Is a tree proof or natural deduction a semantic method of proof? Peter Schroeder-Heister writes in an article on "Proof-Theoretic Semantics" the following: Proof-theoretic semantics is inherently inferential, as it is inferential activity which manifests itself in proofs. It thus belongs to inferentialism (see Brandom, 2000) according to which inferences and the rules of inference establish the meaning of expressions, in contradistinction to denotationalism, according to which denotations are the primary sort of meaning. Inferentialism and the ‘meaning-as-use’ view of semantics is the broad philosophical framework of proof-theoretic semantics. He also notes: According to Dummett, the logical position of intuitionism corresponds to the philosophical position of anti-realism. The realist view of a recognition independent reality is the metaphysical counterpart of the view that all sentences are either true or false independent of our means of recognizing it. Following Dummett, major parts of proof-theoretic semantics are associated with anti-realism. I previously thought of natural deduction or tree proofs as syntactic proof techniques, however, I wonder if that is accurate given the above. If so, that would seem to leave axiomatic proofs as the only syntactic proof technique. Given proof-theoretic semantics are tree proofs or natural deduction semantic proof techniques? Or does that only apply if one accepts Dummett's anti-realism? Schroeder-Heister, Peter, "Proof-Theoretic Semantics", The Stanford Encyclopedia of Philosophy (Spring 2018 Edition), Edward N. Zalta (ed.), URL = https://plato.stanford.edu/archives/spr2018/entries/proof-theoretic-semantics/. A: According to Frederick Suppe in his entry Axiomatization from A Companion to the Philosophy of Science, syntactical and semantic approaches to axiomatization are both possible formally, semiformally, or informally. What differentiates syntactic versus semantic approaches is the degree by which the axiomatic system is devoid of propositional content. Thus, the logical positivists who started out looking for a syntactic approach for truth, ultimately fell back on observational vocabulary (what Quine calls observational sentences in The Two Dogmas of Science) as a method of formal semantics, such as in Ramsey sentences. From page 9: On semantical approaches one identifies an intended class C of systems or instances, then presents a formal structure S... [such that] S is specified axiomatically, indicating that axiomatization is not the exclusive possession of syntactical approaches. So, as I read this, it is not so much the logical organization of the approach which determines its characterization, but rather how tightly coupled semantic content is to the model. Euclid's Elements is an informal semantic approach because the axioms and postulates of his method clearly have meaning, where as in model theory when a model based on sentential calculus is used to prove Gödel's incompleteness theorems, the meaning of the approach is confined to the abstraction itself. EDIT In this way, natural deduction is semantic because it uses natural language which possess content, as are proof trees because they speak to the meaning of logical operations. I would see this as being complementary to the realist methodology because instead of attacking theories from a structural standpoint divorced from meaning as a mere tool for exploring theory, it actually establishes meaningful explanations of observations? (I'm open to criticism.)
{ "pile_set_name": "StackExchange" }
Q: Cannot find `glutin` in `glium` when using Conrod I am attempting to add a GUI to a small project of mine using Conrod. I have managed to work my way down to 3 compilation errors: error[E0433]: failed to resolve. Could not find `glutin` in `glium` --> src/support/mod.rs:88:53 | 88 | pub fn next(&mut self, events_loop: &mut glium::glutin::EventsLoop) -> Vec<glium::glutin::Event> { | ^^^^^^ Could not find `glutin` in `glium` error[E0433]: failed to resolve. Could not find `glutin` in `glium` --> src/support/mod.rs:88:87 | 88 | pub fn next(&mut self, events_loop: &mut glium::glutin::EventsLoop) -> Vec<glium::glutin::Event> { | ^^^^^^ Could not find `glutin` in `glium` error[E0433]: failed to resolve. Could not find `glutin` in `glium` --> src/support/mod.rs:106:24 | 106 | glium::glutin::ControlFlow::Break | ^^^^^^ Could not find `glutin` in `glium` I've studied the examples that ship with Conrod (particularly the text_edit.rs example) and have successfully compiled and run them. As far as I can tell, they use the same techniques (as my code is directly inspired by their examples), yet does not suffer from the unresolved imports of glutin. Furthermore, I cannot seem to find any reference to glutin in the project directory itself: $> pwd ~/dev/conrod/src $> tree. . ├── backend │ ├── gfx.rs │ ├── glium.rs │ ├── mod.rs │ ├── piston │ │ ├── draw.rs │ │ ├── event.rs │ │ └── mod.rs │ └── winit.rs ├── border.rs ├── color.rs ├── cursor.rs ├── event.rs ├── graph │ ├── algo.rs │ ├── depth_order.rs │ └── mod.rs ├── guide │ ├── chapter_1.rs │ ├── chapter_2.rs │ └── mod.rs ├── image.rs ├── input │ ├── global.rs │ ├── mod.rs │ ├── state.rs │ └── widget.rs ├── label.rs ├── lib.rs ├── position │ ├── matrix.rs │ ├── mod.rs │ ├── range.rs │ └── rect.rs ├── render.rs ├── tests │ ├── global_input.rs │ ├── mod.rs │ ├── ui.rs │ └── widget_input.rs ├── text.rs ├── theme.rs ├── ui.rs ├── utils.rs └── widget ├── bordered_rectangle.rs ├── builder.rs ├── button.rs ├── canvas.rs ├── collapsible_area.rs ├── drop_down_list.rs ├── envelope_editor.rs ├── file_navigator │ ├── directory_view.rs │ └── mod.rs ├── graph │ ├── mod.rs │ └── node.rs ├── grid.rs ├── id.rs ├── list.rs ├── list_select.rs ├── matrix.rs ├── mod.rs ├── number_dialer.rs ├── plot_path.rs ├── primitive │ ├── image.rs │ ├── line.rs │ ├── mod.rs │ ├── point_path.rs │ ├── shape │ │ ├── circle.rs │ │ ├── mod.rs │ │ ├── oval.rs │ │ ├── polygon.rs │ │ ├── rectangle.rs │ │ └── triangles.rs │ └── text.rs ├── range_slider.rs ├── rounded_rectangle.rs ├── scrollbar.rs ├── scroll.rs ├── slider.rs ├── tabs.rs ├── text_box.rs ├── text_edit.rs ├── title_bar.rs ├── toggle.rs └── xy_pad.rs For reference, my Cargo.toml also includes glutin as a dependency: [features] default = ["winit", "glium"] winit = ["conrod/winit"] glium = ["conrod/glium"] [dependencies] conrod = "^0.57" find_folder = "*" glutin = "*" A: I believe this is a misconception about the module structure of conrod and glium. The conrod crate has a number of backend modules, containing utility functions for each of the different backends. conrod::backend::glium is this module for glium, and it contains structures and things useful for using conrod with glium. In your case, however, I think you mistook this module for glium itself. glium is a separate crate from conrod, and you'll need to depend on it much like you depend on glutin. glium does indeed have a glium::conrod property, so if you do pull it in with extern crate glium; rather than using conrod::backend::glium, it should "just work"! You'll need to add some line glium = 0.x in your Cargo.toml as well, but that should be trivial.
{ "pile_set_name": "StackExchange" }
Q: How did Lincoln legitimize the constitutionality of his Emancipation Proclamation? How did he convince the south to legitimize the emancipation proclamation? A: Fairly early in the war Lincoln (actually one of his generals, but he endorsed the measure) took the position that human "property" in a rebellious state could be confiscated by Federal forces upon command, essentially as spoils of war. If the Federal government chose to employ these slaves as labor to help the army, or free them, that was the Federal Government's business. The Emancipation Proclamation legally was viewed as an extension of this principle. It only applied to slaves in the states that were revolting (thus it didn't apply to Union slave states like West Virginia, Maryland, and Kentucky). Of course the states in question didn't recognize Federal authority at the time, so in practice this just meant that if the South were to lose the war eventually, all their slaves would be freed. Effectively, it officially made the war a war to end slavery in the South. But it has often been remarked that the proclamation itself didn't free a single slave. At least not initially.
{ "pile_set_name": "StackExchange" }
Q: Yesod live reload of Hamlet with GHCI instead of GHC? I just heard about Yesod and started reading the book. In the Shakespeare chapter, about 3/4 down, they said... "Reload mode is not available for Hamlet, only for Cassius, Lucius and Julius. There are too many sophisticated features in Hamlet that rely directly on the Haskell compiler and could not feasible be reimplemented at runtime." Does this mean that the server has to get recompiled every time you change the HTML? Would it be any good to use Ghci to do the live compiling, or is that technology already being used at it's peak for Yesod? This software seems like one of the more majestic projects. I really look forward to learning more about Yesod and this style of programming in general! A: I am not sure (a) if you are asking about deploying the application after you change the Hamlet file or (b) if you just need real-time feedback without having to manually recompile during development. Anyways if it is (a): I have not done it myself but I think the answer is yes, you will have to recompile and redeploy. If it is (b): If you use yesod --dev devel to launch your server, it will listen for any changes and automatically recompile. If you refresh the page, changes should be visible or if you have any errors, it will show up in the log. Hope that helps!
{ "pile_set_name": "StackExchange" }
Q: Priority queue with both decrease-key and increase-key operations A Fibonnaci Heap supports the following operations: insert(key, data) : adds a new element to the data structure find-min() : returns a pointer to the element with minimum key delete-min() : removes the element with minimum key delete(node) : deletes the element pointed to by node decrease-key(node) : decreases the key of the element pointed to by node All non-delete operations are $O(1)$ (amortized) time, and the delete operations are $O(\log n)$ amortized time. Are there any implementations of a priority queue which also supportincrease-key(node) in $O(1)$ (amortized) time? A: Assume you have a priority queue that has $O(1)$ find-min, increase-key, and insert. Then the following is a sorting algorithm that takes $O(n)$ time: vector<T> fast_sort(const vector<T> & in) { vector<T> ans; pq<T> out; for (auto x : in) { out.insert(x); } for(auto x : in) { ans.push_back(*out.find_min()); out.increase_key(out.find_min(), infinity); } return ans; }
{ "pile_set_name": "StackExchange" }
Q: CRC16 checksum: HCS08 vs. Kermit vs. XMODEM I'm trying to add CRC16 error detection to a Motorola HCS08 microcontroller application. My checksums don't match, though. One online CRC calculator provides both the result I see in my PC program and the result I see on the micro. It calls the micro's result "XModem" and the PC's result "Kermit." What is the difference between the way those two ancient protocols specify the use of CRC16? A: you can implement 16 bit IBM, CCITT, XModem, Kermit, and CCITT 1D0F using the same basic code base. see http://www.acooke.org/cute/16bitCRCAl0.html which uses code from http://www.barrgroup.com/Embedded-Systems/How-To/CRC-Calculation-C-Code the following table shows how they differ: name polynomial initial val reverse byte? reverse result? swap result? CCITT 1021 ffff no no no XModem 1021 0000 no no no Kermit 1021 0000 yes yes yes CCITT 1D0F 1021 1d0f no no no IBM 8005 0000 yes yes no where 'reverse byte' means that each byte is bit-reversed before processing; 'reverse result' means that the 16 bit result is bit-reversed after processing; 'swap result' means that the two bytes in the result are swapped after processing. all the above was validated with test vectors against http://www.lammertbies.nl/comm/info/crc-calculation.html (if that is wrong, we are all lost...). so, in your particular case, you can convert code for XModem to Kermit by bit-reversing each byte, bit reversing the final result, and then swapping the two bytes in the result. [i believe, but haven't checked or worked out the details, that reversing each byte is equivalent to reversing the polynomial (plus some extra details). which is why you'll see very different explanations in different places for what is basically the same algorithm. also, the approach above is not efficient, but is good for testing. if you want efficient the best thing to do is translate the above to lookup-tables.] edit what i have called CCITT above is documented in the RevEng catalogue as CCITT-FALSE. for more info, see the update to my blog post at the link above. A: My recollection (I used to do modem stuff way back when) is that Kermit processes the bits in each byte of the data using the least significant bit first. Most software CRC implementations (Xmodem, probably) run through the data bytes most significant bit first. When looking at the library source (download it from http://www.lammertbies.nl/comm/software/index.html) used for the CRC Calculation page you linked to, you'll see that XModem uses CRC16-CCITT, the polynomial for which is: x^16 + x^12 + x^5 + 1 /* the '^' character here represents exponentition, not xor */ The polynomial is represented by the bitmap (note that bit 16 is implied) 0x1021 == 0001 0000 0010 0001 binary The Kermit implementation uses: 0x8408 == 1000 0100 0000 1000 binary which is the same bitmap as XModem's, only reversed. The text file that accompanies the library also mentions the following difference for Kermit: Only for CRC-Kermit and CRC-SICK: After all input processing, the one's complement of the CRC is calculated and the two bytes of the CRC are swapped. So it should probably be easy to modify your CRC routine to match the PC result. Note that the source in the CRC library seems to have a pretty liberal license - it might make sense to use it more or less as is (at least the portions that apply for your application).
{ "pile_set_name": "StackExchange" }
Q: D2L Passing ID/Keys in Header instead of Query Params? Is it possible to pass the the ID/keys as an auth header instead of the documented query params? A: Not at this time, no. Currently, the only supported mechanism for authentication with the Valence APIs is the IDKey Auth system passing signatures as query parameters.
{ "pile_set_name": "StackExchange" }
Q: Migrations in Rails Engine? I have multiple rails applications talking to the same backend and I'd like them to share some migrations. I setup a rails engine (with enginex), I can share anything (controllers, views, models,...) but no migrations. I can't make it work ! I tried to create a file db/migrate/my_migration.rb but in my main application if I do : rake db:migrate It doesn't load them. After some googling it appears there was some recent work on this and it seems this has been merge to rails master. I'm with rails 3.0.3 do you see any way to make this work ? Thanks ! A: In rails 3.1, you can do it using this command, give that your engine name is example: # Note that you append _engine to the name rake example_engine:install:migrations A: What i do, is add an InstallGenerator that will add the migrations to the Rails site itself. It has not quite the same behavior as the one you mentioned, but for now, for me, it is good enough. A small how-to: First, create the folder lib\generators\<your-gem-name>\install and inside that folder create a file called install_generator.rb with the following code: require 'rails/generators/migration' module YourGemName module Generators class InstallGenerator < ::Rails::Generators::Base include Rails::Generators::Migration source_root File.expand_path('../templates', __FILE__) desc "add the migrations" def self.next_migration_number(path) unless @prev_migration_nr @prev_migration_nr = Time.now.utc.strftime("%Y%m%d%H%M%S").to_i else @prev_migration_nr += 1 end @prev_migration_nr.to_s end def copy_migrations migration_template "create_something.rb", "db/migrate/create_something.rb" migration_template "create_something_else.rb", "db/migrate/create_something_else.rb" end end end end and inside the lib/generators/<your-gem-name>/install/templates add your two files containing the migrations, e.g. take the one named create_something.rb : class CreateAbilities < ActiveRecord::Migration def self.up create_table :abilities do |t| t.string :name t.string :description t.boolean :needs_extent t.timestamps end end def self.down drop_table :abilities end end Then, when your gem is added to some app, you can just do rails g <your_gem_name>:install and that will add the migrations, and then you can just do rake db:migrate. Hope this helps. A: Under 3.1, you can share migrations, without installing them, by altering config/application.rb to do something like this: # Our migrations live exclusively w/in the Commons project config.paths['db/migrate'] = Commons::Engine.paths['db/migrate'].existent
{ "pile_set_name": "StackExchange" }
Q: How to multiple join with MySQL? Let's say I have three tables in a straight OneToMany relationships. grandparent TABLE ----------------- id PK AI parent TABLE ----------------- id PK AI grandparent_id FK ManyToOne NOT NULL child TABLE ----------------- id PK AI parent_id FK ManyToOne NOT NULL When I want to select parents and grandparents while selecting children, which of following two queries right? SELECT * FROM child AS c INNER JOIN (parent AS p INNER JOIN grandparent AS g ON p.grandparent_id = g.id) ON c.parent_id = p.id SELECT * FROM child AS c INNER JOIN parent AS p ON c.parent_id = p.id INNER JOIN grandparent AS g ON p.grandparent_id = g.id Are they same both internally and outernally? A: I would left join, twice, from grandparents to parents and then to children. The motivation behind this is that not all ancestors may have had children, yet you might want to still include them in your report. SELECT t1.ID AS grandparent_id CASE WHEN t2.ID IS NOT NULL THEN CAST(t2.ID AS VARCHAR) ELSE 'NA' END AS parent_id, CASE WHEN t3.ID IS NOT NULL THEN CAST(t3.ID AS VARCHAR) ELSE 'NA' END AS child_id FROM grandparent t1 LEFT JOIN parent t2 ON t1.ID = t2.grandparent_id LEFT JOIN child t3 ON t2.ID = t3.parent_id ORDER BY t1.ID, t2.ID, t3.ID;
{ "pile_set_name": "StackExchange" }
Q: Comparing Simple Sounds - What is the Closest Frequency I have a rather interesting problem to solve. I want to take a very simple sound (one note played on the piano) and try to process it in such a way that I can print out which note is most likely being played. From some googling and searching I have come across the fast fourier transform but am not entirely sure how I would use this to analyze data from a wav file. Another thought I had was that a note should be more or less the same each time it is played. If that is the case could a percentage match on two wav files turned into byte arrays be of any use? Thoughts and ideas would be much appreciated. A: The FFT is a much better option than comparing two WAVs. The FFT will produce a frequency spectrum, and since the piano produces a relatively pure tone, you will observe very distinct spikes when you plot it. The position of each spike denotes one of the constituent frequencies of the waveform, with the largest spike representing the note.
{ "pile_set_name": "StackExchange" }
Q: jQuery - Display all dates between JSON .startTime & .endTime values I'm trying to get a php read-only calendar to display dates from a Google Calendar, using jQuery to apply color to the background of the relevant cells. Code for each calendar table looks like this: <?php $monthNames = Array("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"); if (!isset($_REQUEST["month"])) $_REQUEST["month"] = date("n"); if (!isset($_REQUEST["year"])) $_REQUEST["year"] = date("Y"); $cMonth = $_REQUEST["month"]; $cYear = $_REQUEST["year"]; $prev_year = $cYear; $next_year = $cYear; $prev_month = $cMonth-1; $next_month = $cMonth+1; if ($prev_month == 0 ) { $prev_month = 12; $prev_year = $cYear - 1; } if ($next_month == 13 ) { $next_month = 1; $next_year = $cYear + 1; } if (!isset($_REQUEST["short-month"])) $_REQUEST["short-month"] = date("m"); $cShortMonth = $_REQUEST["short-month"]; ?> // Generate the calendar <div class="month"> <?php $month_of_year = 1; ?> <h2><?php echo $monthNames[$cMonth+$month_of_year-2].' '.$cYear; ?></h2> <table class="cal"> <tr> <td class="day-cell">S</td> <td class="day-cell">M</td> <td class="day-cell">T</td> <td class="day-cell">W</td> <td class="day-cell">T</td> <td class="day-cell">F</td> <td class="day-cell">S</td> </tr> <?php $timestamp = mktime(0,0,0,$cMonth+$month_of_year-1,1,$cYear); $maxday = date("t",$timestamp); $thismonth = getdate ($timestamp); $startday = $thismonth['wday']; for ($i=0; $i<($maxday+$startday); $i++) { $year_id = $cYear; $month_id_raw = $cShortMonth+$month_of_year-1; $month_id = str_pad($month_id_raw, 2, "0", STR_PAD_LEFT); $day_id_raw = $i - $startday + 1; $day_id = str_pad($day_id_raw, 2, "0", STR_PAD_LEFT); if(($i % 7) == 0 ) echo "<tr>"; if($i < $startday) echo "<td></td>"; else echo "<td class='date-cell' id='" . $year_id . "-" . $month_id . "-" . $day_id . "'>" . ($i - $startday + 1) . "</td>"; if(($i % 7) == 6 ) echo "</tr>"; }?> </table> </div> Which generates a calendar table that I've repeated x12: It gives each date on the calendar a unique id in date format YYYY-MM-DD, which seems to be working. That is in preparation for the jQuery below (matches the JSON format in the XML), which is where I get stuck: function GCalEvents() { var calendar_json_url = "https://www.google.com/calendar/feeds/myemail%40googlemail.com/public/full?orderby=starttime&sortorder=ascending&max-results=3&futureevents=true&alt=json" // Get list of upcoming events formatted in JSON jQuery.getJSON(calendar_json_url, function(data){ // Parse and render each event jQuery.each(data.feed.entry, function(i, item){ // Apply background to start dates. var start_time_id = item.gd$when[0].startTime; var end_time_id = item.gd$when[0].endTime; jQuery("#" + start_time_id).css("background","red"); jQuery("#" + end_time_id).css("background","green"); }); }); } As you can see, I can get jQuery to use the .startTime/.endTime as the ID, which allows me to colour the individual dates. But I need to color up all the days between .startTime and .endTime (usually a whole week) in one go. They don't have to be different colors - I've just done that to highlight start/end date. So what I'm looking for is the way to colour up the whole week in one hit. If anyone can help I'd be very grateful as its proving to be beyond me. A: You could use this to obtain the dates between the start and end date, formatted as "YYYY-MM-DD" var formatInt = function (i) { if (i < 10) return "0" + i; return i; }; var format = function (d) { var date = d.getDate(); var month = d.getMonth() + 1; var year = d.getFullYear(); return year + "-" + formatInt(month) + "-" + formatInt(date); }; var getDates = function (start, end) { var current = new Date(start); var finish = new Date(end); var result = []; do { current.setDate(current.getDate() + 1); result.push(format(current)); } while (current < finish); return result; }; You can then do something like: var start = item.gd$when[0].startTime; var end = item.gd$when[0].endTime; var dates = getDates(start, end).map(function toId(date) { return "#" + date }).join(","); $(dates).css('background', 'green');
{ "pile_set_name": "StackExchange" }
Q: How to jumble a word from EditText and apply the jumbled word into a TextView I need to know how to jumble a word entered into EditText. The jumbled word will show in another TextView in the same interface. I have tried to do this but I get a force close error. This is what I have tried within the button: wordE = (EditText)findViewById(R.id.entry); jumble = (TextView) findViewById(R.id.jumble); Button link5Btn = (Button)findViewById( R.id.selected ); link5Btn.setOnClickListener( new View.OnClickListener() { public void onClick(View v) { jumbleMe(al); } Which calls the method: private void jumbleMe( String word ){ al = wordE.getText().toString(); ArrayList<Character> al = new ArrayList<Character>(); for (int i = 0; i < wordE.length(); i++) { al.add(word.charAt(i)); } Collections.shuffle(al); jumble.setText( al.toString() ); } I would appreciate any help on this. Thanks A: You made some mistakes. Try changing the code to: link5Btn.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { jumbleMe(wordE.getText().toString()); } }); and private void jumbleMe(String word) { ArrayList<Character> al = new ArrayList<Character>(); for (int i = 0; i < wordE.length(); i++) { al.add(word.charAt(i)); } Collections.shuffle(al); String result = ""; for (Character character : al) { result += character; } jumble.setText(result); }
{ "pile_set_name": "StackExchange" }
Q: Is there any advantage to using properties over public variables? This might be a very stupid question, but I have to ask it anyway. I am graduating in about a month and while studying, I have always been taught to use properties instead of public variables. So I started wondering what the advantage was and I must say that in some cases, I have no clue at all. Of course it is handy when some other logic needs to be executed when setting properties or getting properties, but is there any advantage to using properties when you are only getting/setting a variable? An example of what I mean is shown below (As3). private var _myVariable:SomeClass; public function get myVariable():SomeClass{ return _myVariable; } public function set myVariable(value:SomeClass):void{ _myVariable = value; } So, to repeat and clarify my question: is there any advantage to programming my getter/setter like this, or could I just change the variable to public and drop the getter/setter? A: If you only wrapping the access to a private variable with public getter and public setter with no further requirements to do something on setting or getting the variable you are fine using a public property. You should think about using getters and setters if you want to inherit from your class later, and may be able to extend it in some other way, you currently don't think about.
{ "pile_set_name": "StackExchange" }
Q: Using PHP and regex, insert a character between a group of matched characters I would like to insert a character between a group of matched characters using regex to define the group and PHP to place the character within the match. Looking here, I see that it may require PHP recursive matching, although I imagine there could be a simpler way. To illustrate, I am attempting to insert a space in a string when there is a combination of 2 or more letters adjacent to a number. The space should be inserted between the letters and number(s). The example, "AXR900DE3", should return "AXR 900 DE 3". Could an answer be to use preg_split to break up the string iteratively and insert spaces along the way? I've begun an attempt using preg_replace below for the pattern 2+letters followed by a number (I will also need to use a pattern, a number followed by 2+letters), but I need another step to insert the space between that match. $sku = "AXR900DEF334"; $string = preg_replace('/(?<=[A-Z]{2}[\d])/',' ', $sku); A: You don't need to do recursive. If I have understood you correctly, you should be able to do this: $sku = "AXR900DEF334"; $string = preg_replace('/((?<=[A-Z]{2})(?=[0-9])|(?<=[0-9])(?=[A-Z]{2}))/',' ', $sku); echo $string; OUTPUT AXR 900 DEF 334 This will match both when the letters precedes and comes after the digits.
{ "pile_set_name": "StackExchange" }
Q: Find only repeated String attributes in list with Java 8 I know below is the code to find out the occurrence of each String attributes in list , how can I filter this list with only duplicates item i.e having more than 1 occurrence. Sorry I am new to java 8 . Map<String, Long> result = list.stream() .collect(Collectors.groupingBy(Function.identity(), Collectors.counting())); A: create a stream from the entrySet and filter: List<Map.Entry<String, Long>> result = list.stream() .collect(Collectors.groupingBy(Function.identity(), Collectors.counting())) .entrySet() .stream() .filter(s -> s.getValue() >= 2) .collect(Collectors.toList()); or if you want to maintain a map then: Map<String, Long> result = stringList().stream() .collect(Collectors.groupingBy(Function.identity(), Collectors.counting())) .entrySet() .stream() .filter(s -> s.getValue() >= 2) .collect(toMap(Map.Entry::getKey, Map.Entry::getValue)); on another note, if you just want the individual numbers that have more than or equal to 2 occurrences then you can do: List<String> result = list.stream() .collect(Collectors.groupingBy(Function.identity(), Collectors.counting())) .entrySet() .stream() .filter(x -> x.getValue() >= 2) .map(Map.Entry::getKey) .collect(toList()); another option being: List<String> result = list.stream() .filter(x -> list.stream().filter(x::equals).limit(2).count() == 2) .distinct() .collect(toList()); A: If your List is mutable, you can directly remove all elements except their second occurrence: // example list List<String> example = new ArrayList<>(); Collections.addAll(example, "foo", "bar", "baz", "bar", "bar", "baz"); // actual operation Map<String,Integer> temp = new HashMap<>(); example.removeIf(s -> temp.merge(s, 1, Integer::sum)!=2); // example output example.forEach(System.out::println);// prints bar baz The solution above keeps only one copy for each string having multiple occurrences while removing all strings having no duplicates. If you want to keep all duplicates and just remove those string not having duplicates, there is no way around determining the duplicate status first. // same example input as above // actual operation Map<String,Boolean> temp = new HashMap<>(); example.forEach(s -> temp.merge(s, true, (a,b) -> false)); example.removeIf(temp::get); // example output example.forEach(System.out::println);// prints bar baz bar bar baz Here, the temporary map can be created with a Stream operation with the same logic: Map<String,Boolean> temp = example.stream() .collect(Collectors.toMap(Function.identity(), s -> true, (a,b) -> false)); example.removeIf(temp::get); A: The other way would be like this. after groupBy then remove entry with value=1; result = list.stream() .collect(Collectors.groupingBy(Function.identity(), Collectors.counting())); result.values().removeIf(v->v.intValue() == 1);
{ "pile_set_name": "StackExchange" }
Q: NoMethodError in Pages#home I'm working through the railtutorial.org online book for rails 3. I've made it through most of chapter 11, where we add the ability to submit a micropost. After adding the appropriate code, I'm unable to render the page. The following is the error returned: > NoMethodError in Pages#home Showing c:/rails_projects/sample_app/app/views/shared/_error_messages.html.erb where line >#1 raised: You have a nil object when you didn't expect it! You might have expected an instance of ActiveRecord::Base. The error occurred while evaluating nil.errors Extracted source (around line #1): 1:<% if @user.errors.any? %> 2:<div id="error_explanation"> 3:<h2><%= pluralize(@user.errors.count, "error") %> 4:prohibited this <%= object.class.to_s.underscore.humanize.downcase %> Trace of template inclusion: app/views/shared/_micropost_form.html.erb, >app/views/pages/home.html.erb The page will render correctly if I remove the following line from app\views\shared_micropost_form.html.erb <%= render 'shared/error_messages', :object => f.object %> Any help is appreciated. A: it's because you're passing a variable object into your partial, but in the partial you're trying to use a variable called @user. Change each instance of @user in that partial to object and it will work fine. 1:<% if object.errors.any? %> 2:<div id="error_explanation"> 3:<h2><%= pluralize(object.errors.count, "error") %> 4:prohibited this <%= object.class.to_s.underscore.humanize.downcase %> UPDATE: Just to clarify, the answers above are assuming there's a fault with setting the @user variable, but it's fine. When you say :object => f.object in your render call, you're telling render to take the object that this form is based on, and send it to the partial - with the variable name object. The whole point of refactoring the error code into a shared partial is that it will be used by multiple forms, for different models. Inside the partial you can't say @user because you will be using this same partial for all your other models. That's why the code in the partial is changed to use a more generic variable name, object.
{ "pile_set_name": "StackExchange" }
Q: Firefox address bar and page are blank when running RSpec test I am getting this error Selenium::WebDriver::Error::WebDriverError: unable to obtain stable firefox connection in 60 seconds (127.0.0.1:7055) Here is the list of my tests gems capybara (2.1.0) rspec (2.14.1) rspec-core (2.14.3) rspec-expectations (2.14.0) rspec-mocks (2.14.1) rspec-rails (2.14.0) selenium-webdriver (2.35.1) My Firefox version is 29 When I downgraded my FF, it works fine. A: I had the same issue and this works for me with Firefox version 28 In your Gemfile, replace the current version with gem "selenium-webdriver", "~> 2.38.0" Then run, gem update selenium-webdriver bundle install
{ "pile_set_name": "StackExchange" }
Q: Access class instance from one file in another file? I have two files, both are in the same project (part of a web scraping framework). File1 processes items that are generated by File2. In File2 I have a function that prints out some basic stats about the processes (counts of how many items have been generated, etc). I have counts in File1 that I would like to print with the stats from File1 but am unsure of how to do that. Take a look at the example code. FILE 1: class Class1(object): def __init__(self): self.stats = counter("name") #This is the instance that I'd like to use in File2 self.stats.count = 10 class counter: def __init__(self, name): self.name = name self.count = 0 def __string__(self): message = self.name + self.count return message FILE 2: (this is what I'd like to do) from project import file1 # this import returns no error def stats(): print file1.Class1.stats # This is where I'm trying to get the instance created in Class1 of File2. #print file1.Class1.stats.count # Furthermore, it would be nice if this worked too. ERROR: exceptions.AttributeError: type object 'Class1' has no attribute 'stats' I know that both files are running, thus so does the 'stats' instance of the 'counter' class, because of other methods being printed out when running the project (this is just a stripped down example. What am I doing wrong here? Is this possible to do? A: This is not working because you never instantiate Class1. __init__ is called when the Class1 is instantiated so Class1.stats is set. You have 2 options here. instantiate Class1 in file 2 somehow. declare a static method in Class1 that returns the count property. A: Your terminology is a little mixed up. "both files are running, thus so does the 'stats' instance of the 'counter' class" - stats is a attribute of objects of the counter class. If you want a count of how many instances of the class are created, you should use a class attribute which is something that is bound to your class, and not an instance of it. class Counter(object): count = 0 def __init__(self, name): self.name = name Counter.count += 1 self.id = Counter.count def __repr__(self): return '<Counter: %s (%d of %d)>' % ( self.name, self.id, Counter.count) So then this can be used like so, >>> foo = Counter('Foo') >>> print foo <Counter: Foo (1 of 1)> >>> bar = Counter('Bar') >>> print bar <Counter: Bar (2 of 2)> >>> print foo <Counter: Foo (1 of 2)> >>> Note that the second time you print foo it has updated the count, but the id remains the same, that is because count is a class attribute, but id is an attribute of the object, so (with this code) the creation of bar doesn't affect the id of foo, but it increments Counter.count.
{ "pile_set_name": "StackExchange" }
Q: .Net-Core Log out of Oauth I've created an application which uses OAuth to login to Coinbase. My startup configuration looks like so: services.AddAuthentication(options => { options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme; options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme; options.DefaultChallengeScheme = COINBASE_AUTH_ID; }) .AddCookie() .AddOAuth(COINBASE_AUTH_ID, options => { options.ClientId = Configuration["Coinbase:ClientId"]; options.ClientSecret = Configuration["Coinbase:ClientSecret"]; options.CallbackPath = new PathString("/signin-coinbase"); options.AuthorizationEndpoint = "https://www.coinbase.com/oauth/authorize?meta[send_limit_amount]=1"; options.TokenEndpoint = "https://api.coinbase.com/oauth/token"; options.UserInformationEndpoint = "https://api.coinbase.com/v2/user"; COINBASE_SCOPES.ForEach(scope => options.Scope.Add(scope)); options.SaveTokens = true; options.ClaimActions.MapJsonKey(ClaimTypes.NameIdentifier, "id"); options.ClaimActions.MapJsonKey(ClaimTypes.Name, "name"); options.ClaimActions.MapJsonKey("urn:coinbase:avatar", "avatar_url"); options.Events = new OAuthEvents { OnCreatingTicket = async context => { var request = new HttpRequestMessage(HttpMethod.Get, context.Options.UserInformationEndpoint); request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", context.AccessToken); request.Headers.Add("CB-VERSION", DateTime.Now.ToShortDateString()); var response = await context.Backchannel.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, context.HttpContext.RequestAborted); response.EnsureSuccessStatusCode(); var user = JObject.Parse(await response.Content.ReadAsStringAsync()); context.RunClaimActions(user); } }; }); When a user logs in I return a challenge result and let the default authentication do it's work. [HttpGet] public IActionResult Login(string returnUrl = "/") { return Challenge(new AuthenticationProperties() { RedirectUri = returnUrl }); } I'm trying to figure out how to logout but when I call Signout on the base controller nothing is happening. [HttpGet] public IActionResult Logout() { this.SignOut(); return Redirect(Url.Content("~/")); } How can I log out of oauth? A: There's probably a more graceful way of doing this but for now. I found I can call the SignOut method on the HTTPContext public async Task<IActionResult> Logout() { await HttpContext.SignOutAsync(); return Redirect(Url.Content("~/")); }
{ "pile_set_name": "StackExchange" }
Q: Disable text "Settings" when click recent button android Why when I press this button, a pop up (with text Settings) is displayed in my app ? How can I remove it? A: For handling this keys you need to override this method of the Activity @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode ==KeyEvent.KEYCODE_MENU) { //return true if you want block button menu return true; } return super.onKeyDown(keyCode, event); }
{ "pile_set_name": "StackExchange" }
Q: How do you remove the "Localize" button from SDL Tridion SiteEdit 2009 I am using SDL Tridion SiteEdit 2009, and would like to remove the Localize button from the ComponentPresentation rollover borders. I have done this in the past, but have no recollection of how I did it. Does anyone know how I may have achieved this? A: Find this section in your SiteEdit.config file (typically in C:\Program Files (x86)\Tridion\SiteEdit 2009\SiteEdit\Application\Configuration): <!-- ** Component Toolbar ** If @Visible is set to "false" the toolbar will not be available. Under <ButtonsVisibility> you can specify the availability of each button. --> <ComponentToolbar Visible="true"> <ButtonsVisibility> <Save>true</Save> <Publish>true</Publish> <EditParent>true</EditParent> <Localize>true</Localize> <StartActivity>true</StartActivity> <FinishActivity>true</FinishActivity> <Refresh>true</Refresh> <Swap>true</Swap> <EditInPopup>true</EditInPopup> </ButtonsVisibility> </ComponentToolbar> And set the value of <Localize> to false.
{ "pile_set_name": "StackExchange" }
Q: How to scrape all reviews if they are on different pages? How to scrape all reviews from walmart review page (ex:http://www.walmart.com/ip/Ematic-9-Dual-Screen-Portable-DVD-Player-with-Dual-DVD-Players-ED929D/28806789) if they are on different pages?I scrape by mechanize(nokogiri) but it can't click on button(it is not part of form,then I can't submit it) <button class="paginator-btn paginator-btn-next"><span class="visuallyhidden">Next Page</span></button> and I can't go to next page.How to solve this problem? A: I solve this task with watir gem.Mechanize cant interact with JavaScript.
{ "pile_set_name": "StackExchange" }
Q: How to tell if your application is Project or Excel with VBA? I have created a custom class that adds references based on what the macros need to run on the particular Project or Excel file. This class works for both MS Project and Excel. The problem I am having is in the code how can I determine if the application is a Project or Excel file? Currently my code works by default assuming that it is in an Excel file, if an error occurs I handle the error by switching the code from "ActiveWorkbook" to "ActiveProject". Is there any way I can avoid using error handling and just run a check to see what I am in. Thanks! A: @Jeeped's comment points to a simple answer--test the Name property of the Application object. Not in the Immediate window, of course, but in an If statement: If Application.Name = "Microsoft Excel" Then....
{ "pile_set_name": "StackExchange" }
Q: Как разместить элементы управления, перекрывающие друг друга? Например, расположена кнопка внутри layout, а поверх неё расположен TextView. A: Это делается с помощью наложения элементов в FrameLayout. <FrameLayout > <Button /> <TextView /> </FrameLayout>
{ "pile_set_name": "StackExchange" }
Q: How did the sequence /str/ become /ʂ/ in Sicilian? Words which have the sound sequence /s/-/t/-/r/ in standard Italian (and probably had that sequence in their Latin ancestor form) have a simple retroflex fricative in Sicilian, which is spelt "str", perhaps copying the Italian spelling of the word. Now I get how "r" could have become a retroflex /ɻ/, maybe due to external influences, and then /t/ could have been retroflected to /ʈ/ when near a /ɻ/, which in turn was devoiced to produce the affricate /ʈʂ/, spelt "tr" in Sicilian. I could even imagine "str" becoming /sʈʂ/ and then /ʂʈʂ/. But how did this turn to a simple /ʂ/? Is it actually the case that /str/>/stɻ/>/sʈʂ/>/ʂʈʂ/>/ʂ/? Or is the evolution different? A: As far as I know, it's actually [ʂɻ] or [ʂɹ], not [ʂ]. Likewise, I read that "tr" and "dr" are actually [t͡ʃɹ~ʈ͡ʂɻ] and [d͡ʒɹ~ɖ͡ʐɻ] respectively, not [ʈ͡ʂ] and [ɖ͡ʐ] It seems that in both Romance and Slavic languages, it is very common to turn the clusters /st͡ʃ/ into a simple /ʃ/. This happens in Russian with the <щ>, which originally represented /st͡ʃ/ or /ʃt͡ʃ/ (which it still does in Ukrainian), but eventually turned into /ʃː/. (I suspect the same thing happened to the Italian "sci" ). I believe this is what might have happened to the Sicilian - [str] ->[sʈ͡ʂɻ~ʂʈ͡ʂɻ] -> [ʂɻ]
{ "pile_set_name": "StackExchange" }
Q: Updating TXTRecordDictionary doesn't always notify monitoring services I'm using bonjour to find other devices. Each device uses TXTRecordData to share its name: NSDictionary* dictionary = @{ @"name": @"Goose" }; [service setTXTRecordData:[NSNetService dataFromTXTRecordDictionary:dictionary]]; Each device listens for changes: - (void) netService:(NSNetService *)sender didUpdateTXTRecordData:(NSData *)data { ... } About 80% of the time it works - didUpdateTXTRecordData is called when a name is changed. Sometimes the other devices are never notified. I've checked and setTXTRecordData returns YES when the data is lost. How can I make sure updates to the TXTRecordData makes it to other devices? A: Someone posted a gist demonstrating what is possibly the above bug. For you Apple people out there, the gist says the relevant rdar is rdar://11018654
{ "pile_set_name": "StackExchange" }
Q: How to stringify Javascript function object with properties? In typescript, a class with static members is compiled into a function when each static member becomes a function object property. For example: class Config { static debug = true; static verbose = false; } Becomes var Config = (function () { function Config() { } Config.debug = true; Config.verbose = false; return Config; })(); Invoking JSON.stringify on such function object will result with undefined. What is the right way to stringify in that case? A: Note that JSON.stringify does not take the functions. You could do it this way: If an object being stringified has a property named toJSON whose value is a function, then the toJSON() method customizes JSON stringification behavior: instead of the object being serialized, the value returned by the toJSON() method when called will be serialized. An example: Function.prototype.toJSON = Function.prototype.toJSON || function(){ var props = {}; for(var x in this){ if(this.hasOwnProperty(x)) props[x] = this[x] } return props } var Config = (function () { function Config() { } Config.debug = true; Config.verbose = false; return Config; })(); console.log(JSON.stringify(Config))
{ "pile_set_name": "StackExchange" }
Q: Lua pattern to replace any word,character, digit or symbol followed by a paticular string I want to replace any word, character, digit or symbol (except ; , .) followed by the string "some-word\" in Lua. More like a '*' option in regex. Is there any thing similar to '*' in Lua? Example: some-word\\test -> some-word\\### some-word\\b*ax#@$6; -> some-word\\###; some-word\\?foo,> -> some-word\\###, The code I'm using: d = "some-word" p = (tostring(d).."\\[.%c%w%p^%;^%,^%.]+") c = "###" s = "testing some-word\\test-2 later some-word\\&^*; some-word\\set_34$ " print(p) res = (string.gsub(s,p,c)) print(res) A: (some%-word)\[^;,.%s]* works, note that: - is a magic character in Lua patterns, it needs to be escaped. some%-word is surrounded by (), so that it's captured with %1. In character class, ^ is used in the beginning to indicate complement of the following. Test: d = "some%-word" p = "(" .. d .. ")" .. "\\[^;,.%s]*" c = "%1###" s = "testing some-word\\test-2 later some-word\\&^*; some-word\\set_34$ " print(p) res = string.gsub(s,p,c) print(res) Output: (some%-word)\[^;,.%s]* testing some-word### later some-word###; some-word###
{ "pile_set_name": "StackExchange" }
Q: Erro CORS api Correios Estou tentando fazer uma requisição para calculo de frete para os correios, mas quando solicito a requisição, retorna o erro de erro de CORS -- Mensagem de erro: Access to XMLHttpRequest at 'http://ws.correios.com.br/calculador/CalcPrecoPrazo.asmx/CalcPrecoPrazo?nCdEmpresa=&sDsSenha=&nCdServico=4510&sCepOrigem=72001835&sCepDestino=75180000&nVlPeso=1&nCdFormato=1&nVlComprimento=16&nVlAltura=5&nVlLargura=15&nVlDiametro=0&sCdMaoPropria=n&nVlValorDeclarado=100&sCdAvisoRecebimento=n' from origin 'http://localhost:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Código da chamada: testeCorreios(){ let url = 'http://ws.correios.com.br/calculador/CalcPrecoPrazo.asmx/CalcPrecoPrazo'; //let h = new HttpHeaders() //.append('Access-Control-Allow-Credentials', 'true') //.append('Access-Control-Allow-Methods', '*') //.append('Access-Control-Allow-Origin', '*'); let p = new HttpParams() .set('nCdEmpresa', '') .set('sDsSenha', '') .set('nCdServico', '4510') .set('sCepOrigem', '72001835') .set('sCepDestino', '75180000') .set('nVlPeso', '1') .set('nCdFormato', '1') .set('nVlComprimento', '16') .set('nVlAltura', '5') .set('nVlLargura', '15') .set('nVlDiametro', '0') .set('sCdMaoPropria', 'n') .set('nVlValorDeclarado', '100') .set('sCdAvisoRecebimento', 'n'); return this.http.get(url, { headers: h, responseType: 'text', params: p }); } Ja tentei adicionar um header e tal, mas não funcionou. Para teste estava usando um plugin do chrome pra passar, porem quando subo pra produção ele nao funciona (ate pq nao ta com o plugin). Alguem me ajuda aii A: Bom, resolvi adicionando essa url ao inicio da minha url -> https://cors-anywhere.herokuapp.com/ Então minha url de chamada ficou assim: -> https://cors-anywhere.herokuapp.com/http://ws.correios.com.br/calculador/CalcPrecoPrazo.asmx/CalcPrecoPrazo
{ "pile_set_name": "StackExchange" }
Q: Three.js: ExtrudeGeometry: Problems setting different material for front and back side I'm creating an ExtrudeGeometry of a hexagon shape and trying to set a different material for the front side and back side, as it is stated in this thread. let shape = new THREE.Shape(); /*...*/ let geometry = new THREE.ExtrudeGeometry(shape, { steps: 2, amount: 0.05, bevelEnabled: false, material: 0, //frontMaterial = green extrudeMaterial: 1 //sideMaterial = gray }); //Searching for the back side and setting the marialIndex accordingly for (let face of geometry.faces) { if (face.normal.z == 1) { face.materialIndex = 2; //backMaterial = red } } let mesh = new THREE.Mesh(geometry, new THREE.MultiMaterial([frontMaterial, sideMaterial, backMaterial])); The problem now is, that this method (iterating over the faces and looking for those with normal.z == 1) does not work correctly with a extrudeGeometry.amount = 0.05. A value of 0.1 works fine. See this jsfiddle Is there another method for setting a different material for front and back side or am I doing it just wrong? Thanks for your help! A: The problem is due to rounding. Do this, instead if ( face.normal.z < - 0.99999 ) { // instead of == - 1 face.materialIndex = 2; } Also, the back face normal is in theory (0, 0, - 1 ). updated fiddle: https://jsfiddle.net/xhbu2e01/3/ three.js r.84
{ "pile_set_name": "StackExchange" }
Q: Determining the of grid used by circle I would like to determine the proportion of a grid cell occupied by one (or more) circles. So, for example, the top left grid cell below would have a small value (~0.1) and the center grid cell (7,7) would have a value of 1, as it is entirely occupied by the circle. At present I am doing this with canvas.context2d.getImageData, by sampling the cell's content to determine what is present. This works but is way too slow. This is this method: var boxRadius = 6; var boxSize = boxRadius * 2 + 1; var cellWidth = gridWidth / boxSize; var cellHeight = gridHeight / boxSize; var scanInterval = 10; var scanCount = 10; for (var x = viewcenterpoint.x - (gridWidth / 2); x <= viewcenterpoint.x + (gridWidth / 2) -1; x += cellWidth) { for (var y = viewcenterpoint.y - (gridHeight / 2) ; y <= viewcenterpoint.y + (gridHeight / 2) -1; y += cellHeight) { var cellthreatlevel = 0.0; for (var cellx = x; cellx < x + cellWidth; cellx += scanInterval){ for (var celly = y; celly < y + cellHeight; celly += scanInterval){ var pixeldata = context.getImageData(cellx, celly, 1, 1).data; cellthreatlevel += ((pixeldata[0] + pixeldata[1] + pixeldata[2])/765 * -1) + 1;//255; //grey tone scancount += 1; } } cellthreatlevel = cellthreatlevel / scanCount; //mean } } The getImageData call is the source of the problem - it is way too slow. Given that I have an array of circles, each with their x, y and radius how can I calculate this? If possible I would like each value to be a decimal fraction (between 0 and 1). The grid is static, but the circles may move within it. I would be happy to get a rough estimate for the value, it doesnt need to be 100% accurate. A: You can use the Monte Carlo Method to get an approximate solution. It is a probability based method, in which you generate random samples in order to estimate some value. In this case, given the coordinates of the circle center, the circle radius and the boundaries of the grid cell, you can estimate the proportion of the grid cell occupied by the circle by generating K random samples (all contained inside the grid cell), and verify the proportion of the samples that are also inside the circle. The more samples you generate, the more accurate your result will be. Remember: to verify if a given sample P is inside a circle with center C and radius R, all you have to do is check if the equation sqrt((Px-Cx)^2 + (Py-Cy)^2) <= R is true
{ "pile_set_name": "StackExchange" }
Q: Strictly diagonally dominant matrices are non singular I try to find a good proof for invertibility of strictly diagonally dominant matrices (defined by $|m_{ii}|>\sum_{j\ne i}|m_{ij}|$). There is a proof of this in this paper but I'm wondering whether there are are better proof such as using determinant, etc to show that the matrix is non singular. A: The proof in the PDF (Theorem 1.1) is very elementary. The crux of the argument is that if $M$ is strictly diagonally dominant and singular, then there exists a vector $u \neq 0$ with $$Mu = 0.$$ $u$ has some entry $u_i > 0$ of largest magnitude. Then \begin{align*} \sum_j m_{ij} u_j &= 0\\ m_{ii} u_i &= -\sum_{j\neq i} m_{ij}u_j\\ m_{ii} &= -\sum_{j\neq i} \frac{u_j}{u_i}m_{ij}\\ |m_{ii}| &\leq \sum_{j\neq i} \left|\frac{u_j}{u_i}m_{ij}\right|\\ |m_{ii}| &\leq \sum_{j\neq i} |m_{ij}|, \end{align*} a contradiction. I'm skeptical you will find a significantly more elementary proof. Incidentally, though, the Gershgorin circle theorem (also described in your PDF) is very beautiful and gives geometric intuition for why no eigenvalue can be zero.
{ "pile_set_name": "StackExchange" }
Q: Parsing OrderedDict to Python list I am using a module called Simple Salesforce to query data from my Salesforce database. The data comes back as an OrderedDict. How can I parse this into simple python lists. Sample of the first two entries as it is returned when queried: OrderedDict([ (u'totalSize', 418), (u'done', True), (u'records', [ OrderedDict([ (u'attributes', OrderedDict([ (u'type', u'Case'), (u'url', u'/services/Case/11111') ])), (u'Id', u'11111'), (u'Subject', u'Case 1') ]), OrderedDict([ (u'attributes', OrderedDict([ (u'type', u'Case'), (u'url', u'/services/Case/2222222') ])), (u'Id', u'2222222'), (u'Subject', u'Case 2') ]), #... ]) ]) I not sure I have the term list correct, but I want it as a multi-dimensional table in the form of: [('11111', 'Case 1'),('2222222', 'Case 2')] Ultimately, I'd like to inner join this list with another list. Is this the best way to set up the data? So the two lists that I would like to inner join would be : List 1: List1 = [('11111', 'Case 1'),('2222222', 'Case 2')] # [ID, Subject] List 2: List2 = [('11111', 'April'),('2222222', 'March'),('333333', 'January')] # [ID, Date] Desired Output: [('11111', 'Case 1','April'),('2222222', 'Case 2','March')] A: You can obtain the two dimensional table using a list comprehension: from collections import OrderedDict od = OrderedDict([ (u'totalSize', 418), (u'done', True), (u'records', [ OrderedDict([ (u'attributes', OrderedDict([ (u'type', u'Case'), (u'url', u'/services/Case/11111') ])), (u'Id', u'11111'), (u'Subject', u'Case 1') ]), OrderedDict([ (u'attributes', OrderedDict([ (u'type', u'Case'), (u'url', u'/services/Case/2222222') ])), (u'Id', u'2222222'), (u'Subject', u'Case 2') ]), #... ]) ]) list1 = [(record['Id'], record['Subject']) for record in od['records']] print list1 # -> [(u'11111', u'Case 1'), (u'2222222', u'Case 2')] An "inner join" could be imitated with code something like this: list2 = [('11111', 'April'), ('2222222', 'March'), ('333333', 'January')] joined = [item1+item2[1:] for item1 in list1 for item2 in list2 if item1[0] == item2[0]] print joined # -> [(u'11111', u'Case 1', 'April'), # (u'2222222', u'Case 2', 'March')] Note: The latter is somewhat inefficient, so you'd want to use more advanced processing techniques and/or data-structures to process large datasets quickly.
{ "pile_set_name": "StackExchange" }
Q: Natural vs. "Forced" language learning Would the "natural" way of learning a language (the way we learn our mother tongue) be better even for acquiring second (and third, etc.) languages? What I mean is: The "natural" way to learn a language is: 0) You hear it (as a baby and toddler) understanding first tone and later meaning 1) You gradually learn to speak it (being immersed in the language, you acquire it "effortlessly") 2) You later learn to read and write it The "forced" (usually it's you forcing yourself) way to learn a language is: 0) You try to read it 1) You try to understand it being spoken 2) You try to speak it Are we (am I) doing it backwards? Maybe what we should do is first listen, listen, listen, and only later try to speak it, and then read and write it? I wonder if this would also make the acquisition of authentic accents easier (by first focusing on listening). As a side note, I learned German half my life ago and am now learning Spanish. I find that learning Spanish is much more difficult for me than German was. My wife says it's because I'm older (I'm 56); my theory/hope is that it's not so much that, but rather the greater difference between English and Spanish than between English (a Germanic language) and German. A: No, I don't think so. First of all, babies and toddlers are helpless and receive parenting and caring nearly 24/7. They literally have nothing to do except to passively absorb language. Second, humans are biologically designed to learn language earlier in life, just like geese imprint on their mother extremely early on during a "critical period." Adults can't learn language like babies and toddlers do because it's not supposed to be that way--that unique neurological ability to naturally pick up language is "intentionally" restricted to infancy. I can say "fui a la tienda ayer" to a new adult Spanish learner and act it out however I like--but the learner will absolutely not understand. The way babies associated meaning with words is through literally hundreds or thousands of instances of usage in different contexts and settings and environments. You probably would need, therefore, some kind of intense immersion to learn a second language in your proposed "natural" way, and this is completely unrealistic for most learners. Without total immersion, structured, organized learning is the only option. But the thing is, with babies and toddlers, when they are in their environment of immersion, they literally have no worries or needs that won't be taken care of because they don't fully grasp the language. An American can't go to Spain not knowing how to speak Spanish and then start crying when he needs to use the bathroom, which is what babies do. And I doubt he'll be able to pick up from simply listening and making repeated, frustrated attempts to express himself how to say, "Is there a public restroom nearby?" Therefore, it is necessary to teach such structured phrases and it is impractical to expect natural passive immersive absorption of language of an adult learner of a second language.
{ "pile_set_name": "StackExchange" }
Q: How can I 'mirror' my git repository locally? I have followed the following instructions in setting a git repository locally in one of my hard drive (1): https://trac.webkit.org/wiki/UsingGitWithWebKit I would like to know if it is possible for me to set up another repository in a different hard drive which mirrors the one I setup in (1)? By mirrors, I mean if I commit some changes the other repository can retrieve it. Thank you. A: First, create a 'bare' clone of your existing repository to use as your backup: $ git clone --bare /path/to/your/repo /path/to/your/backup_repo Next, navigate to your existing repository add a new remote repository definition: $ git remote add backup /path/to/your/backup_repo The name of the remote definition in this instance is called 'backup' but you can call it whatever you like. Now, whenever you're working on your existing repository you can push the changes to your new backup repository by simply executing the following command: $ git push backup You should see results something like this: Counting objects: 5, done. Compressing objects: 100% (2/2), done. Writing objects: 100% (3/3), 287 bytes, done. Total 3 (delta 0), reused 0 (delta 0) Unpacking objects: 100% (3/3), done. To /path/to/your/backup_repo 7c6f003..9eea051 master -> master If you want to automate this process so you don't have to manually execute the push, you could probably just wire up a post-commit hook to do it for you.
{ "pile_set_name": "StackExchange" }
Q: Inline block adding extra space in firefox I have a webpage where I have stacked my div's with inline-Block properties. However, it adds extra spacing only between two div's in Firefox. The design is consistent in Safari and Chrome. Here's the sample fiddle for that. #main { display: block; } #sub11, #sub12, #sub21, #sub22, #sub31, #sub32 { display: inline-block; background:red; padding:0; //margin-right:-4px; margin-top:3px; margin-bottom:3px; } Firefox adds extra space betweeb GHI and TRY row, while the ABC and GHI are consistent with other rows that comes after TRY. A: The code: display: inline-block; Will display spaces, you will have to add a float for them to appear directly after one another. try adding a: float:left; to your #sub11, etc.. A: I used following css fix exclusively for that one row @-moz-document url-prefix() { #myRowID {margin-top:-5px;} } That solves my weird issue.
{ "pile_set_name": "StackExchange" }
Q: xml layout crashes on loading for android app enter image description hereHey guys I'm at the end of my Java 1 class working on my project. We are making a memory/concentration game. My issue is that when I click the easy button for the next activity the app crashes. I have tried using fragments and activities and just can't seem to get it right. I have also tried using the layout I need on my main activity just to see if I could get it to display. Even then it just crashes on startup of the app. Any help would be appreciated. Startup Screen activity. package com.bignerdranch.android.memory; import android.app.Activity; import android.content.Intent; import android.media.AudioManager; import android.media.MediaPlayer; import android.os.Bundle; import android.view.Menu; import android.view.View; import android.widget.Button; import android.widget.CheckBox; public class MemoryActivity extends Activity { private Button mEasy; private Button mMedium; private Button mHard; private CheckBox mSilence; public MediaPlayer player; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_memory); player = new MediaPlayer(); player = MediaPlayer.create(this, R.raw.mkstartmusic); player.setAudioStreamType(AudioManager.STREAM_MUSIC); player.setLooping(true); player.start(); mEasy = (Button)findViewById(R.id.easy); mEasy.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent easy = new Intent(getApplicationContext(), EasyGame.class); startActivity(easy); } }); mMedium = (Button)findViewById(R.id.medium); mMedium.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub } }); mHard = (Button)findViewById(R.id.hard); mHard.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub } }); mSilence = (CheckBox)findViewById(R.id.silence); mSilence.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(mSilence.isChecked()) { player.pause(); } else if(mSilence.isChecked() == false) { player.start(); } } }); } @Override protected void onStop() { super.onPause(); if (player != null){ player.stop(); if (isFinishing()){ player.stop(); player.release(); } } } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.layout.activity_memory, menu); return true; } } Second Activity (Easy option) package com.bignerdranch.android.memory; import android.app.Activity; import android.os.Bundle; import android.view.Menu; import android.view.View; import android.widget.ImageButton; public class EasyGame extends Activity { private ImageButton buttOne; private ImageButton buttTwo; private ImageButton buttThree; private ImageButton buttFour; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_easy); buttOne = (ImageButton)findViewById(R.id.ImageButton01); buttOne.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { } }); buttTwo = (ImageButton)findViewById(R.id.ImageButton02); buttTwo.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { } }); buttThree = (ImageButton)findViewById(R.id.ImageButton03); buttThree.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { } }); buttFour = (ImageButton)findViewById(R.id.ImageButton04); buttFour.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.layout.activity_easy, menu); return true; } } This is the layout for the Easy option <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <ImageView android:id="@+id/easyback" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_alignParentBottom="true" android:layout_alignParentLeft="true" android:layout_alignParentStart="true" android:layout_alignParentTop="true" android:background="@drawable/easyback" android:clickable="false" android:duplicateParentState="false" android:longClickable="false" android:scaleType="centerCrop" /> <ImageButton android:id="@+id/ImageButton04" android:layout_width="80dp" android:layout_height="80dp" android:layout_below="@+id/ImageButton01" android:layout_toRightOf="@+id/ImageButton01" android:layout_toEndOf="@+id/ImageButton01" android:maxHeight="25dp" android:maxWidth="25dp" android:scaleType="fitXY" android:src="@drawable/dragonemb" /> <ImageButton android:id="@+id/ImageButton02" android:layout_width="80dp" android:layout_height="80dp" android:layout_above="@+id/ImageButton04" android:layout_alignParentRight="true" android:layout_alignParentEnd="true" android:layout_marginRight="22dp" android:layout_marginEnd="22dp" android:maxHeight="25dp" android:maxWidth="25dp" android:scaleType="fitXY" android:src="@drawable/dragonemb" /> <ImageButton android:id="@+id/ImageButton03" android:layout_width="80dp" android:layout_height="80dp" android:layout_alignTop="@+id/ImageButton04" android:layout_toLeftOf="@+id/ImageButton04" android:layout_toStartOf="@+id/ImageButton04" android:maxHeight="25dp" android:maxWidth="25dp" android:scaleType="fitXY" android:src="@drawable/dragonemb" /> <ImageButton android:id="@+id/ImageButton01" android:layout_width="80dp" android:layout_height="80dp" android:layout_alignParentTop="true" android:layout_marginTop="152dp" android:layout_toLeftOf="@+id/ImageButton02" android:maxHeight="25dp" android:maxWidth="25dp" android:scaleType="fitXY" android:src="@drawable/dragonemb" /> </RelativeLayout> A: OK It's not the full crash log you posted but at the top of it I saw roidManifest.xml?. And It's sure that you didn't defined your EasyGame Activity in your androidmanifest.xml so add this line inside application tag, <manifest package="com....." . . . > <application . . . > <activity android:name=".EasyGame" android:label="easygame"> </activity> . . . </application> </manifest> In addition you are trying to cast your ImageButton into Button consider fixing that as well.
{ "pile_set_name": "StackExchange" }
Q: Single async function that makes multiple fetches and returns results? I am attempting to write an async function that makes multiple fetches, waits for all to complete, then returns the JSON results as an array. This is what I have so far: file1.js const searchResults = await Api.search(searchText); api.js async function search(searchText) { return util.executeFetchAll([ `/searchA/${searchText}`, `/searchB/${searchText}`, `/searchC/${searchText}` ]); } util.js async function executeFetchAll(urls) { const promises = urls.map(url => fetch(url)); const responses = await Promise.all(promises); debugger; } When execution pauses at the debugger and I inspect responses using Chrome's dev tools, it is correctly an array of 3 Response objects, but if I inspect responses[0].json(), it weirdly returns in the console a Promise {<pending>} object. What am I missing? I'm awaiting Promise.all, which should mean all promises resolve before my debugger line. So why is the json() method weirdly showing a Promise object in a pending state? Thanks. A: response.json() return a Promise! see: https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch So you can await them with something like this: await Promise.all(responses.map(r => r.json()));
{ "pile_set_name": "StackExchange" }
Q: iOS styling an input type="file" I'm trying to style the input with css to display the same way on iOS without the default iOS input styling that it applies. <input name="t1" class="imgupload" type="file" accept="image/*" capture="camera"> input[type='file'] { background: rgb(0, 0, 0); border-radius: 5px; color: rgb(255, 255, 255); font-family: 'Lucida Grande'; padding: 0px 0px 0px 0px; font-size: 16px; margin-bottom: 20px; width: 210px; vertical-align: top; margin-top: -2px; } Is there a specific -webkit class to disable the default styling. A: You need to add -webkit-appearence: none;
{ "pile_set_name": "StackExchange" }
Q: How do I get the file name from nodejs app.post? I want to get the file original name from this app.post (used with multer): app.post('/', upload.array('file'), function(req, res){ console.log(req.files); res.status(204).end(); }); Using console.log(req.files) I get: [ { fieldname: 'file', originalname: 'TSy16rd913.jpg', encoding: '7bit', mimetype: 'image/jpeg', destination: './public/uploads/', filename: 'TSy16rd913.jpg', path: 'public/uploads/TSy16rd913.jpg', size: 110736 } ] Using console.log(req.files.originalname) or console.log(req.files.filename) gives undefined. So how do I get originalname or filename? A: As @Roland Starke answer, req.files is an array, so you have to do something like this req.files[0].filename To get all filenames : req.files.forEach(function(value, key) { console.log(value.filename) })
{ "pile_set_name": "StackExchange" }
Q: MPS Template use of parameter In MPS I have defined a template: template reduce_Car Input Car parameters color : String <TF [<Car>???</Car>] TF> Now I wanted to use the defined parameter "color" in my template? A: You access parameters through genContext. So wrap the text to replace with a property macro <TF [<Car>$[red]</Car>] TF> and down in the Inspector for the property macro access the parameter as 'genContext.color'
{ "pile_set_name": "StackExchange" }
Q: C++ console issue This may seem like a simple question, bu tI just can't figure out what it is that makes my console rapidly open and close? I included system("PAUSE") in my main() function. Program informaton: This program is for a cinema theater ticket system that shows which seats in which row are available (as you can see for the multidimensional arrays). Anybody know why the console won't stay open? I'm not getting ANY error messages in the compiler. #include <iostream> #include <fstream> using namespace std; using std::ifstream; void Init(); void Display(); void SellTicket(); void ReadPrices(); char tickets[15][20]; int revenue = 0; int ticketsSold = 0; int prices[15]; int main() { Init(); ReadPrices(); int choice; cout << "Enter your choice: " << endl; cout << "Press 1 for Display Chart" << endl; cout << "Press 2 for sell ticket" << endl; cout << "Press 3 for exit" << endl; cin >> choice; cout << endl; switch(choice) { case 1: Display(); break; case 2: SellTicket(); break; case 3: exit(0); break; } system("PAUSE"); return 0; } void Init() { for (int row = 0; row < 15; row++) { for (int col = 0; col < 20; col++) { tickets[row][col]='*'; } } } void Display() { cout <<"Seats:\t0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19"<<endl; for (int row = 0; row < 15; row++) { cout << "Row"<< row << "\t"; for (int col = 0; col < 20; col++) { if(col < 10) cout << tickets[row][col] << " "; else cout << tickets[row][col] << " "; } cout << endl; cout << endl; } cout << "Total sold seats are: " << ticketsSold << endl; cout << "Total revenue is: " << revenue << endl; cout << endl; } void SellTicket() { int rowNo,seatNo; //while(1) //{ cout << "Enter Row Number:"; cin >> rowNo; cout << endl; cout << "Enter Seat Number:"; cin >> seatNo; cout << endl; if (tickets[rowNo][seatNo]=='#') { cout << "Ticket is not available " << endl; cout << endl; SellTicket(); } else { tickets[rowNo][seatNo]='#'; revenue+=prices[rowNo]; ticketsSold+=1; char c; cout << "Would you like to sell another ticket? Press y for yes or n for no: "; cin >> c; cout << endl; if (c=='y') { SellTicket(); } } //} } void ReadPrices() { int count=0; ifstream indata; int num; indata.open("prices.dat"); if(!indata) { cerr << "Error: file could not be opened" << endl; exit(1); } indata >> num; while ( !indata.eof() ) { prices[count++]=num; //cout<< "The next number is " << num << endl; indata >> num; } indata.close(); //cout << "End-of-file reached.." << endl; } A: Because in your ReadPrices() function, you fail to open prices.dat file and simply exit(1) application indata.open("prices.dat"); if(!indata) { cerr << "Error: file could not be opened" << endl; exit(1); } If you are using VisualStudio, run application, CTL + F5 the console will stay. Learn how to debug your application is very important, step through each line of code and you can find the issue easily for your case.
{ "pile_set_name": "StackExchange" }
Q: TAB breaks element position I made jsfiddle example over here: http://jsfiddle.net/FE55W/ html: <div class="wrapper"> <div class="slider"> <div class="slide n1"><a href="#">test</a></div> <div class="slide n2"><a href="#">test</a></div> </div> </div> css: .wrapper{ width:500px; height:350px; margin:0 auto; position:relative; overflow:hidden; } .slider{ width:5000px; position:absolute; left:0; top:0; } .slide{ width:500px; height: 350px; float: left; } .slide.n1{ background-color: green; } .slide.n2{ background-color: blue; } Problem is when you click with the mouse on green square and push TAB several times, blue square appears and breaks elemets position. How i can solve this problem? A: Add tabindex="-1" to the anchor that you don't want to TAB to. <div class="slide n2"><a tabindex="-1" href="#">test</a></div> http://jsfiddle.net/Morlock0821/FE55W/1/
{ "pile_set_name": "StackExchange" }
Q: How to list the columns of a view in Postgres? For a physical table, I have been using the following SQL: select column_name, data_type, character_maximum_length from INFORMATION_SCHEMA.COLUMNS where table_name = 'a_table_name' I found that this doesn't work for a view. Is there a way to get the schema of a view by running a SQL command (not via psql). A: Postgres has dedicated System Catalog Information Functions to help with that. To get the full view definition: SELECT pg_get_viewdef('public.view_name'); Schema-qualification is optional. If no schema is prefixed, the current search_path setting decides visibility. To list columns and their data type, in order, you might base the query on pg_attribute: SELECT attname AS column_name, format_type(atttypid, atttypmod) AS data_type FROM pg_attribute WHERE attrelid = 'public.view_name'::regclass -- AND NOT attisdropped -- AND attnum > 0 ORDER BY attnum; Type modifiers like maximum length are included in data_type this way. Internally, a VIEW is implemented as special table with a rewrite rule. Details in the manual here. The table is saved in the system catalogs much like any regular table. About the cast to regclass: How to check if a table exists in a given schema The same query works for tables or materialized views as well. Uncomment the additional filters above to only get visible user columns for tables.
{ "pile_set_name": "StackExchange" }
Q: c# MySqlCommand doesn't appear to be resolving Parameters I'm trying to run a MySqlCommand with a parameter, but when I look in the SQL logs, the parameter is showing up. I've tried with both @ and ?, tried with 'old syntax=yes' in my sqlconnection string also. Here's my code. bool CheckLoginDetails(string username, string password){ DataTable dt = new DataTable (); MySqlCommand command = new MySqlCommand ("select * from `accounts` where `username` = '@username';", SL.Database.connection); command.Parameters.AddWithValue ("@username", username); dt.Load (command.ExecuteReader()); } Here's the SQL logs. 150823 3:19:50 22 Connect root@localhost on unity_test 22 Query SHOW VARIABLES 22 Query SHOW COLLATION 22 Query SET character_set_results=NULL 22 Init DB unity_test 150823 3:19:52 22 Query select * from `accounts` where `username` = '@username' I'm using .net 2.0 and I'm unsure of the mysql dll version, I found that here: http://forum.unity3d.com/threads/reading-database-and-or-spreadsheets.11466/ I'm unable to upgrade .net due to Unity. Any advice would be greatly appreciated! A: Suggestion (not tested): bool CheckLoginDetails(string username, string password){ string sql = select * from accounts where username = ?"; MySqlCommand command = new MySqlCommand(sql); command.Parameters.Add(new MySqlParameter("", username)); MySqlDataReader r = command.ExecuteReader(); ... } The main point is that "?" should work.
{ "pile_set_name": "StackExchange" }
Q: How many positive integers between 50 and 100 are divisible by 7? How many positive integers between 50 and 100 a) are divisible by 7? Which integers are these? This question is in the basic counting section of my textbook and I'm just studying for finals now. For this question, I was wondering if there is a less primitive way of finding this answer. I did: 56, 63, 70, 77, 84, 91, 98; These answers I found by just going on with my 7's multiplications table. The reason I'm wondering this is in case I get asked the same thing but with a much larger number such as 1000. A: $$50 = 7 \times 7 +1$$ $$100 = 14 \times 7 +2$$ and the answer is $14-7=7$. This is effectively what you have done, counting $8 \times 7$, $9 \times 7$, $10 \times 7$, $11 \times 7$, $12 \times 7$, $13 \times 7$, and $14 \times 7$. You will need to be more careful if either of the remainders is $0$.
{ "pile_set_name": "StackExchange" }
Q: Does ES6 `let` and `const` only work in compile time when compiled with babel? I tried babel in babel's official REPL, and found that let, const only compiled to be var. Does that mean that let and const only take effect in compile time? Or let and const do take effects in compiled codes? A: Babel does escape analysis to detemine if there is actually a functional difference between the way var and let is used - so: let x = 5; Usually just gets compiled to var x = 5; Whereas: let x = 5; { let x = 10; } gets compiled to: var x = 5; { var x2 = 10; // _x actually, } This is done because it's much faster than the way old compilers (like traceur) did block scoping in ES5. Block scoping is actually possible in ES5 - it's just really ugly: let x = 5; Gets transpiled to: try { throw 5; } catch (x) { // x defined in this scope }
{ "pile_set_name": "StackExchange" }
Q: Convexity of $|A^TA|$ Assume $A\in\mathbb{R}^{m\times n}$ is a $m$ by $n$ matrix. Let $|\cdot|$ denote the Frobenius norm of matrix. Define function $f:\mathbb{R}^{m\times n}\to\mathbb{R}$ as $f(A):=|A^TA|$. Is $f$ a convex function? Intuitively, I think this function is a composition of a norm and something with quadratic structure, and thus should be convex. To prove this, $f(tA+(1-t)B)=|t^2A^TA+t(1-t)(A^TB+B^TA)+(1-t)^2B^TB|\le t^2|A^TA|+(1-t)^2|B^TB|+t(1-t)|A^TB+B^TA|$. If $|A^TB+B^TA|\le|A^TA|+|B^TB|$, then we get the convexity. Is this inequality true? A: We have $$ |A^\top B|^2 = \operatorname{trace}(B^\top A A^\top B) = \operatorname{trace}(B B^\top A A^\top) = (B B^\top, A A^\top)_F \le |B B^\top| \, |A A^\top| = |B^\top B| \, |A^\top A|.$$ From this, we get $$|A^\top B + B^\top A| \le |A^\top B| + |B^\top A| \le 2 \, |B^\top B|^{1/2} \, |A^\top A|^{1/2} \le |A^\top A| + |B^\top B|.$$
{ "pile_set_name": "StackExchange" }
Q: Python connection to Oracle database I am writing a Python script to fetch and update some data on a remote oracle database from a Linux server. I would like to know how can I connect to remote oracle database from the server. Do I necessarily need to have an oracle client installed on my server or any connector can be used for the same? And also if I use cx_Oracle module in Python, is there any dependency that has to be fulfilled for making it work? A: You have to Install Instance_client for cx_oracle driver to interact with remote oracle server http://www.oracle.com/technetwork/database/features/instant-client/index-097480.html. Use SQLAlchemy (Object Relational Mapper) to make the connection and interact with Oracle Database. The below code you can refer for oracle DB connection. from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker engine = create_engine('oracle+cx_oracle://test_user:test_user@ORACSG') session_factory = sessionmaker(bind=engine, autoflush=False) session = session_factory() res = session.execute("select * from emp"); print res.fetchall()
{ "pile_set_name": "StackExchange" }
Q: How to change text onclick using JavaScript? There are multiple rows like Name   status a          YES (hyperlink) b          NO (hyperlink) c          YES (hyperlink) My Code is: function change_text() { var button = document.getElementById('toggle_button'); if (button.innerHTML === "YES") { button.innerHTML = "NO"; } else { button.innerHTML = "YES"; } } <a href='javascript: toggle()'><p id="toggle_button" onclick="change_text()">YES</p></a> <a href='javascript: toggle()'><p id="toggle_button" onclick="change_text()">NO</p></a> <a href='javascript: toggle()'><p id="toggle_button" onclick="change_text()">YES</p></a> onclick its happening for first row only kindly provide some solution. I am new on javascript or stackoverflow. in case any question please do the comment. A: Here's probably how I'd do it jsbin.com demo // define Toggler "class" var Toggle = function(elem) { elem.addEventListener("click", onClick); function onClick(event) { toggleText(); event.preventDefault(); } function toggleText() { var text = elem.innerHTML; elem.innerHTML = (text === "YES") ? "NO" : "YES"; } this.toggle = toggleText; }; // initialize var toggles = document.getElementsByClassName("toggle"); for (var i=0, len=toggles.length; i<len; i++) { new Toggle(toggles[i]); } This would unobtrusively attach to HTML elements with class toggle <a href="#toggle" class="toggle">YES</a> <a href="#toggle" class="toggle">NO</a> <a href="#toggle" class="toggle">YES</a> As an added convenience, this Toggle "class" provides an API for you to programmatically interact with your togglers <a href="#toggle" id="foo">YES</a> // API example var elem = document.getElementById("foo"); var fooToggle = new Toggler(elem); // toggle off fooToggle.toggle(); // <a href="#toggle" id="foo">NO</a> // toggle on again fooToggle.toggle(); // <a href="#toggle" id="foo">YES</a> Now, since this isn't changing inputs or anything, you might want to use data-value="YES" or data-value="NO" on the a elements. Then when you submit the page, you could collect this data, convert it to JSON, then submit it for processing.
{ "pile_set_name": "StackExchange" }
Q: JSON for Objective-C messes up my array This is a strange error and I'm not sure if I'm using JSON correctly. When I get a response from the server with a proper array, JSON chews it up, turning most of the values to zero and I think it might've forgotten by keys also. 2011-08-01 16:08:15.981 My Alerts[2746:b303] From Server: {"cycleStart":"May 1, 2011","cycleEnds":"May 29, 2011","avg_usage":0,"estimate":0,"totalBudget":0,"Usage":0,"Cost":0} 2011-08-01 16:08:15.982 My Alerts[2746:b303] After JSON: ( 0, 0, 0, 0, "May 29, 2011", "May 1, 2011", 0 ) Here is my code showing where JSON is being used. NSString *post = [NSString stringWithFormat:@"username=%@&acct=%@", username, account]; NSLog(@"POST: %@", post); NSData *postData = [NSData dataWithBytes: [post UTF8String] length: [post length]]; // Submit login data NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease]; [request setURL:[NSURL URLWithString: @"http://***.****.***/file1.php"]]; [request setHTTPMethod: @"POST"]; [request setValue: @"application/x-www-form-urlencoded" forHTTPHeaderField: @"Content-Type"]; [request setHTTPBody: postData]; // Retreive server response NSURLResponse *response; NSError *err; NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err]; if (returnData == nil) { NSLog(@"ERROR: %@", err); } NSString *content = [NSString stringWithUTF8String:[returnData bytes]]; NSLog(@"From Server: %@", content); // <---JSON string returned perfectly from server if (content != @"FAIL") { NSArray *viewDetail = [[NSArray alloc] init]; viewDetail = [[[content JSONValue] allValues] mutableCopy]; // <--JSON appears to be chewing it up NSLog(@"After JSON: %@", viewDetail); // <--Array is now messed up here. // Do stuff with viewDetail array [viewDetail release]; } A: I can't see what's wrong. You wanted allValues, you got all the values. Aside from the ordering, the "from server" and "after JSON" are equivalent. The ordering is not there because NSDictionary (which your JSONValue returns, I believe) does not guarantee order. And the keys are not there because you did not request keys, you requested the values. If you wanted keys, there's allKeys method. And if you wanted a specific value, there's objectForKey: or valueForKey:. You can also use various enumerators. For instance, I believe this should work: NSDictionary *dict = [content JSONValue]; for (id key in dict) { NSLog(@"key: %@ value:%@", key, [dict objectForKey:key]); }
{ "pile_set_name": "StackExchange" }
Q: Issues with whitespace around SVG in IE11, related to text in the SVG I'm having issues with large amounts of whitespace surrounding an SVG in internet explorer. I've created the simplest example I could that reproduces the problem: <!DOCTYPE html> <html lang="en"> <head> <style> svg { border: 1px solid red; } </style> </head> <body> <svg width="600" height="600" viewbox="0 0 600 600"> <rect fill="powderblue" x="0" y="0" width="600" height="600"/> <text x="500" y="500">test</text> </svg> </body> </html> Viewing this in IE11 produces a large amount whitespace to the right and below the SVG. Note the scrollbars in the screenshot below, indicating the large amount of empty space in IE but not in Chrome. The whitespace disappears if I do any of the following: Remove the viewbox attribute Move the text further to the top right Delete the text (don't have to delete the text tags, just the content) As an experiment I added a paragraph below the SVG to see if the whitespace would displace the paragraph. The paragraph appeared directly below the SVG - it wasn't displaced by the whitespace. Any idea how I can fix this so that the whitespace doesn't appear? A: It's obviously a bug in IE. One simple workaround is to set overflow: hidden on the SVG. svg { overflow:hidden; } <svg width="600" height="600" viewbox="0 0 600 600"> <rect fill="powderblue" x="0" y="0" width="600" height="600"/> <text x="500" y="500">test</text> </svg>
{ "pile_set_name": "StackExchange" }
Q: django + uwsgi + ngnix = Django CSRF verification error I have a simple application that allows you to upload images onto the server and it is set up on my production server which consist of of django + uwsgi + ngnix . Now the problem is the csrf token doesn't appear in the template and when I try to upload an image it display this error Forbidden (403) CSRF verification failed. Request aborted. Reason given for failure: CSRF token missing or incorrect. I understand this error clearly . {% csrf_token %} is inside the template and the csrf is enabled on MIDDLEWARE_CLASSES . I also tested my application on development server and it works fine . What can cause the {% csrf_token %} to not appear in the template on my production server. I can see the form but when I view the source there is no csrf token. settings DEBUG = True TEMPLATE_DEBUG = DEBUG ADMINS = ( # ('Your Name', '[email protected]'), ) MANAGERS = ADMINS DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'. 'NAME': '/home/projects/mysite/d.db', # Or path to database file if using sqlite3. # The following settings are not used with sqlite3: 'USER': '', 'PASSWORD': '', 'HOST': '', # Empty for localhost through domain sockets or '127.0.0.1' for localhost through TCP. 'PORT': '', # Set to empty string for default. } } ALLOWED_HOSTS = [] TIME_ZONE = 'America/Chicago' LANGUAGE_CODE = 'en-us' SITE_ID = 1 U SE_I18N = True USE_L10N = True USE_TZ = True MEDIA_ROOT = '/home/projects/mysite/media/' MEDIA_URL = '/media/' STATIC_ROOT = '' STATIC_URL = '/static/' # Additional locations of static files STATICFILES_DIRS = ( # Put strings here, like "/home/html/static" or "C:/www/django/static". # Always use forward slashes, even on Windows. # Don't forget to use absolute paths, not relative paths. ) # List of finder classes that know how to find static files in # various locations. STATICFILES_FINDERS = ( 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', # 'django.contrib.staticfiles.finders.DefaultStorageFinder', ) ist of callables that know how to import templates from various sources. TEMPLATE_LOADERS = ( 'django.template.loaders.filesystem.Loader', 'django.template.loaders.app_directories.Loader', # 'django.template.loaders.eggs.Loader', ) MIDDLEWARE_CLASSES = ( 'django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', # Uncomment the next line for simple clickjacking protection: # 'django.middleware.clickjacking.XFrameOptionsMiddleware', ) ROOT_URLCONF = 'mysite.urls' # Python dotted path to the WSGI application used by Django's runserver. WSGI_APPLICATION = 'mysite.wsgi.application' TEMPLATE_DIRS = ( # Put strings here, like "/home/html/django_templates" or "C:/www/django/templates". # Always use forward slashes, even on Windows. # Don't forget to use absolute paths, not relative paths. ) views def upload(request): form = ImageForm() if request.POST: form = ImageForm(request.POST, request.FILES) image = request.FILES.get('image') CarPhoto.objects.create(user=request.user,cars=1,description='dwq',image=image) return render(request,'image.html',{'form':form}) template <form method="POST" enctype="multipart/form-data"> {% csrf_token %} <div id="c">image</div> {{form.image}} dwqdwqdwq <input type = "submit" value= "add" id="box2"/> </form>{% csrf_token %} view source <form method="POST" enctype="multipart/form-data"><div id="c">image</div><input id="id_image" name="image" type="file" /> dwqdwqdwq <input type="submit" value="add" id="box2"/></form> A: Your view is missing the token since you're not setting it. Change this line return render(request,'image.html',{'form':form}) to context = {'form':form,} context.update(csrf(request)) return render(request,'image.html', context) or from django.core.context_processors import csrf from django.shortcuts import render_to_response return render_to_response('image.html', context, context_instance=RequestContext(request)) You can use either depending on your flavor, also, you have to {% csrf_token %}s in your template. The one outside of the <form> is redundant. Reading the docs is good!
{ "pile_set_name": "StackExchange" }
Q: Dragging inside div - Firefox issue Greetings, I've run into a problem with a simple jQuery mousemove function: When I click and drag inside a div, sometimes the browser will attempt to "drag" the div like it is an image. This only exhibits in Firefox (tested version 4.0), and is causing havoc with my project. I boiled it down to this test case: <style type="text/css" media="screen"> .box { width: 100px; height: 100px; margin: 10px; } .red {background-color: red; } .yellow {background-color: yellow; } .green {background-color: green; } .hidden { display: none; } </style> <div class="box red"></div> <div class="box yellow">Can't Drag Me</div> <div class="box green"><div class="hidden">Can't Drag Me</div></div> To reproduce: click once on a div to select it then click and drag. Red box can be dragged Yellow box cannot be dragged Green box can be dragged So the problem only seems to exhibit when a div is empty or its contents are hidden. Can anyone explain to my why this is happening? What would be the best approach to prevent this "dragging" behavior? Now I know I could add an empty div to the container but I wondered if there was a more elegant approach. Thanks A: I wasn't able to reproduce the issue in Firefox 4, but if it is happening for you, this should stop it... $('div').bind('dragstart', function(event) { event.preventDefault() }); jsFiddle.
{ "pile_set_name": "StackExchange" }
Q: How to find longest consistent increment in a python list? possible_list = [] bigger_list = [] new_list= [0, 25, 2, 1, 14, 1, 14, 1, 4, 6, 6, 7, 0, 10, 11] for i in range(0,len(new_list)): # if the next index is not greater than the length of the list if (i + 1) < (len(new_list)): #if the current value is less than the next value if new_list[i] <= new_list[i+1]: # add the current value to this sublist possible_list.append(new_list[i]) # if the current value is greater than the next, close the list and append it to the lager list bigger_list.append(possible_list) print bigger_list How do I find the longest consistent increment in the list called new_list? I expect the result to be [[0,2], [2], [1,14], [1,14], [1,4,6,6,7], [0,10,11]] I can find the remaining solution from there myself. A: One problem (but not the only one) with your code is that you are always adding the elements to the same possible_list, thus the lists in bigger_list are in fact all the same list! Instead, I suggest using [-1] to access the last element of the list of subsequences (i.e. the one to append to) and [-1][-1] to access the last element of that subsequence (for comparing the current element to). new_list= [0, 25, 2, 1, 14, 1, 14, 1, 4, 6, 6, 7, 0, 10, 11] subseq = [[]] for e in new_list: if not subseq[-1] or subseq[-1][-1] <= e: subseq[-1].append(e) else: subseq.append([e]) This way, subseq ends up the way you want it, and you can use max to get the longest one. >>> subseq [[0, 25], [2], [1, 14], [1, 14], [1, 4, 6, 6, 7], [0, 10, 11]] >>> max(subseq, key=len) [1, 4, 6, 6, 7]
{ "pile_set_name": "StackExchange" }